diff --git a/cudnn/HOW_TO_INSTALL_CUDNN.txt b/cudnn/HOW_TO_INSTALL_CUDNN.txt new file mode 100644 index 0000000000000000000000000000000000000000..590c78d1f007ee773ea729cea50b1f0890cf8ef6 --- /dev/null +++ b/cudnn/HOW_TO_INSTALL_CUDNN.txt @@ -0,0 +1,20 @@ +HOW TO INSTALL cuDNN (PORTABLE METHOD) +===================================== +Since cuDNN requires an NVIDIA Developer login, please follow these steps: + +1. Download the cuDNN ZIP for CUDA 12.x from: + https://developer.nvidia.com/cudnn + +2. Extract the downloaded ZIP. + +3. Copy the CONTENTS of the folders as follows: + - Copy everything from the ZIP's 'bin' folder to: D:\code\apps\devtools\cudnn\bin + - Copy everything from the ZIP's 'include' folder to: D:\code\apps\devtools\cudnn\include + - Copy everything from the ZIP's 'lib/x64' folder to: D:\code\apps\devtools\cudnn\lib\x64 + +4. Restart your terminal (or run activate_env.bat). + +WHY THIS METHOD? +This keeps your C: drive clean. Our devtools environment will automatically +find these files in the 'D:\code\apps\devtools\cudnn' folder and use them +for PyTorch and Unreal Engine development. diff --git a/cudnn/LICENSE b/cudnn/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f9782dbea446ddc7809e9e85f76a0b2055dc1991 --- /dev/null +++ b/cudnn/LICENSE @@ -0,0 +1,305 @@ +LICENSE AGREEMENT FOR NVIDIA SOFTWARE DEVELOPMENT KITS + +This license agreement, including exhibits attached ("Agreement") is a legal agreement between you and NVIDIA Corporation ("NVIDIA") and governs your use of a NVIDIA software development kit ("SDK"). + +Each SDK has its own set of software and materials, but here is a description of the types of items that may be included in a SDK: source code, header files, APIs, data sets and assets (examples include images, textures, models, scenes, videos, native API input/output files), binary software, sample code, libraries, utility programs, programming code and documentation. + +This Agreement can be accepted only by an adult of legal age of majority in the country in which the SDK is used. + +If you are entering into this Agreement on behalf of a company or other legal entity, you represent that you have the legal authority to bind the entity to this Agreement, in which case "you" will mean the entity you represent. + +If you don't have the required age or authority to accept this Agreement, or if you don't accept all the terms and conditions of this Agreement, do not download, install or use the SDK. + +You agree to use the SDK only for purposes that are permitted by (a) this Agreement, and (b) any applicable law, regulation or generally accepted practices or guidelines in the relevant jurisdictions. + +Chapter 1. License. + +1.1. Grant + +Subject to the terms of this Agreement, NVIDIA hereby grants you a non-exclusive, non-transferable license, without the right to sublicense (except as expressly provided in this Agreement) to: + +(i) Install and use the SDK, + +(ii) Modify and create derivative works of sample source code delivered in the SDK, and + +(iii) Distribute those portions of the SDK that are identified in this Agreement as distributable, as incorporated in object code format into a software application that meets the distribution requirements indicated in this Agreement. + +1.2. Distribution Requirements + +These are the distribution requirements for you to exercise the distribution grant: + +(i) Your application must have material additional functionality, beyond the included portions of the SDK. + +(ii) The distributable portions of the SDK shall only be accessed by your application. + +(iii) The following notice shall be included in modifications and derivative works of sample source code distributed: "This software contains source code provided by NVIDIA Corporation." + +(iv) Unless a developer tool is identified in this Agreement as distributable, it is delivered for your internal use only. + +(v) The terms under which you distribute your application must be consistent with the terms of this Agreement, including (without limitation) terms relating to the license grant and license restrictions and protection of NVIDIA's intellectual property rights. Additionally, you agree that you will protect the privacy, security and legal rights of your application users. + +(vi) You agree to notify NVIDIA in writing of any known or suspected distribution or use of the SDK not in compliance with the requirements of this Agreement, and to enforce the terms of your agreements with respect to distributed SDK. + +1.3 Authorized Users + +You may allow employees and contractors of your entity or of your subsidiary(ies) to access and use the SDK from your secure network to perform work on your behalf. + +If you are an academic institution you may allow users enrolled or employed by the academic institution to access and use the SDK from your secure network. + +You are responsible for the compliance with the terms of this Agreement by your authorized users. If you become aware that your authorized users didn't follow the terms of this Agreement, you agree to take reasonable steps to resolve the non-compliance and prevent new occurrences. + +1.4 Pre-Release SDK + +The SDK versions identified as alpha, beta, preview or otherwise as pre-release, may not be fully functional, may contain errors or design flaws, and may have reduced or different security, privacy, accessibility, availability, and reliability standards relative to commercial versions of NVIDIA software and materials. Use of a pre-release SDK may result in unexpected results, loss of data, project delays or other unpredictable damage or loss. + +You may use a pre-release SDK at your own risk, understanding that pre-release SDKs are not intended for use in production or business-critical systems. + +NVIDIA may choose not to make available a commercial version of any pre-release SDK. NVIDIA may also choose to abandon development and terminate the availability of a pre-release SDK at any time without liability. + +1.5 Updates + +NVIDIA may, at its option, make available patches, workarounds or other updates to this SDK. Unless the updates are provided with their separate governing terms, they are deemed part of the SDK licensed to you as provided in this Agreement. + +You agree that the form and content of the SDK that NVIDIA provides may change without prior notice to you. While NVIDIA generally maintains compatibility between versions, NVIDIA may in some cases make changes that introduce incompatibilities in future versions of the SDK. + +1.6 Components Under Other Licenses + +The SDK may come bundled with, or otherwise include or be distributed with, NVIDIA or third party software licensed with separate legal notices or terms as may be described in proprietary notices accompanying the SDK. If and to the extent there is a conflict between the terms in this Agreement and the license terms associated with the component, the license terms associated with the components control only to the extent necessary to resolve the conflict. + +1.7 Reservation of Rights + +NVIDIA reserves all rights, title and interest in and to the SDK not expressly granted to you under this Agreement. + +Chapter 2. Limitations. + +The following license limitations apply to your use of the SDK: + +2.1 You may not reverse engineer, decompile or disassemble, or remove copyright or other proprietary notices from any portion of the SDK or copies of the SDK. + +2.2 Except as expressly provided in this Agreement, you may not copy, sell, rent, sublicense, transfer, distribute, modify, or create derivative works of any portion of the SDK. + +2.3 Unless you have an agreement with NVIDIA for this purpose, you may not indicate that an application created with the SDK is sponsored or endorsed by NVIDIA. + +2.4 You may not bypass, disable, or circumvent any encryption, security, digital rights management or authentication mechanism in the SDK. + +2.5 You may not use the SDK in any manner that would cause it to become subject to an open source software license. As examples, licenses that require as a condition of use, modification, and/or distribution that the SDK be (i) disclosed or distributed in source code form; (ii) licensed for the purpose of making derivative works; or (iii) redistributable at no charge. + +2.6 You acknowledge that the SDK as delivered is not tested or certified by NVIDIA for use in connection with the design, construction, maintenance, and/or operation of any system where the use or failure of such system could result in a situation that threatens the safety of human life or results in catastrophic damages (each, a "Critical Application"). Examples of Critical Applications include use in avionics, navigation, autonomous vehicle applications, ai solutions for automotive products, military, medical, life support or other life critical applications. NVIDIA shall not be liable to you or any third party, in whole or in part, for any claims or damages arising from such uses. You are solely responsible for ensuring that any product or service developed with the SDK as a whole includes sufficient features to comply with all applicable legal and regulatory standards and requirements. + +2.7 You agree to defend, indemnify and hold harmless NVIDIA and its affiliates, and their respective employees, contractors, agents, officers and directors, from and against any and all claims, damages, obligations, losses, liabilities, costs or debt, fines, restitutions and expenses (including but not limited to attorney's fees and costs incident to establishing the right of indemnification) arising out of or related to products or services that use the SDK in or for Critical Applications, and for use of the SDK, outside of the scope of this Agreement or not in compliance with its terms. + +Chapter 3. Ownership. + +3.1 NVIDIA or its licensors hold all rights, title and interest in and to the SDK and its modifications and derivative works, including their respective intellectual property rights, subject to your rights under Section 3.2. This SDK may include software and materials from NVIDIA's licensors, and these licensors are intended third party beneficiaries that may enforce this Agreement with respect to their intellectual property rights. + +3.2 You hold all rights, title and interest in and to your applications and your derivative works of the sample source code delivered in the SDK, including their respective intellectual property rights, subject to NVIDIA's rights under section 3.1. + +3.3 You may, but don't have to, provide to NVIDIA suggestions, feature requests or other feedback regarding the SDK, including possible enhancements or modifications to the SDK. For any feedback that you voluntarily provide, you hereby grant NVIDIA and its affiliates a perpetual, non-exclusive, worldwide, irrevocable license to use, reproduce, modify, license, sublicense (through multiple tiers of sublicensees), and distribute (through multiple tiers of distributors) it without the payment of any royalties or fees to you. NVIDIA will use feedback at its choice. NVIDIA is constantly looking for ways to improve its products, so you may send feedback to NVIDIA through the developer portal at https://developer.nvidia.com. + +Chapter 4. No Warranties. + +THE SDK IS PROVIDED BY NVIDIA "AS IS" AND "WITH ALL FAULTS." TO THE MAXIMUM EXTENT PERMITTED BY LAW, NVIDIA AND ITS AFFILIATES EXPRESSLY DISCLAIM ALL WARRANTIES OF ANY KIND OR NATURE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, NON-INFRINGEMENT, OR THE ABSENCE OF ANY DEFECTS THEREIN, WHETHER LATENT OR PATENT. NO WARRANTY IS MADE ON THE BASIS OF TRADE USAGE, COURSE OF DEALING OR COURSE OF TRADE. + +Chapter 5. Limitations of Liability. + +TO THE MAXIMUM EXTENT PERMITTED BY LAW, NVIDIA AND ITS AFFILIATES SHALL NOT BE LIABLE FOR ANY SPECIAL, INCIDENTAL, PUNITIVE OR CONSEQUENTIAL DAMAGES, OR ANY LOST PROFITS, LOSS OF USE, LOSS OF DATA OR LOSS OF GOODWILL, OR THE COSTS OF PROCURING SUBSTITUTE PRODUCTS, ARISING OUT OF OR IN CONNECTION WITH THIS AGREEMENT OR THE USE OR PERFORMANCE OF THE SDK, WHETHER SUCH LIABILITY ARISES FROM ANY CLAIM BASED UPON BREACH OF CONTRACT, BREACH OF WARRANTY, TORT (INCLUDING NEGLIGENCE), PRODUCT LIABILITY OR ANY OTHER CAUSE OF ACTION OR THEORY OF LIABILITY. IN NO EVENT WILL NVIDIA'S AND ITS AFFILIATES TOTAL CUMULATIVE LIABILITY UNDER OR ARISING OUT OF THIS AGREEMENT EXCEED US$10.00. THE NATURE OF THE LIABILITY OR THE NUMBER OF CLAIMS OR SUITS SHALL NOT ENLARGE OR EXTEND THIS LIMIT. + +These exclusions and limitations of liability shall apply regardless if NVIDIA or its affiliates have been advised of the possibility of such damages, and regardless of whether a remedy fails its essential purpose. These exclusions and limitations of liability form an essential basis of the bargain between the parties, and, absent any of these exclusions or limitations of liability, the provisions of this Agreement, including, without limitation, the economic terms, would be substantially different. + +Chapter 6. Termination. + +6.1 This Agreement will continue to apply until terminated by either you or NVIDIA as described below. + +6.2 If you want to terminate this Agreement, you may do so by stopping to use the SDK. + +6.3 NVIDIA may, at any time, terminate this Agreement if: (i) you fail to comply with any term of this Agreement and the non-compliance is not fixed within thirty (30) days following notice from NVIDIA (or immediately if you violate NVIDIA's intellectual property rights); (ii) you commence or participate in any legal proceeding against NVIDIA with respect to the SDK; or (iii) NVIDIA decides to no longer provide the SDK in a country or, in NVIDIA's sole discretion, the continued use of it is no longer commercially viable. + +6.4 Upon any termination of this Agreement, you agree to promptly discontinue use of the SDK and destroy all copies in your possession or control. Your prior distributions in accordance with this Agreement are not affected by the termination of this Agreement. Upon written request, you will certify in writing that you have complied with your commitments under this section. Upon any termination of this Agreement all provisions survive except for the licenses granted to you. + +Chapter 7. General. + +If you wish to assign this Agreement or your rights and obligations, including by merger, consolidation, dissolution or operation of law, contact NVIDIA to ask for permission. Any attempted assignment not approved by NVIDIA in writing shall be void and of no effect. NVIDIA may assign, delegate or transfer this Agreement and its rights and obligations, and if to a non-affiliate you will be notified. + +You agree to cooperate with NVIDIA and provide reasonably requested information to verify your compliance with this Agreement. + +This Agreement will be governed in all respects by the laws of the United States and of the State of Delaware as those laws are applied to contracts entered into and performed entirely within Delaware by Delaware residents, without regard to the conflicts of laws principles. The United Nations Convention on Contracts for the International Sale of Goods is specifically disclaimed. You agree to all terms of this Agreement in the English language. + +The state or federal courts residing in Santa Clara County, California shall have exclusive jurisdiction over any dispute or claim arising out of this Agreement. Notwithstanding this, you agree that NVIDIA shall still be allowed to apply for injunctive remedies or an equivalent type of urgent legal relief in any jurisdiction. + +If any court of competent jurisdiction determines that any provision of this Agreement is illegal, invalid or unenforceable, such provision will be construed as limited to the extent necessary to be consistent with and fully enforceable under the law and the remaining provisions will remain in full force and effect. Unless otherwise specified, remedies are cumulative. + +Each party acknowledges and agrees that the other is an independent contractor in the performance of this Agreement + +The SDK has been developed entirely at private expense and is "commercial items" consisting of "commercial computer software" and "commercial computer software documentation" provided with RESTRICTED RIGHTS. Use, duplication or disclosure by the U.S. Government or a U.S. Government subcontractor is subject to the restrictions in this Agreement pursuant to DFARS 227.7202-3(a) or as set forth in subparagraphs (b)(1) and (2) of the Commercial Computer Software - Restricted Rights clause at FAR 52.227-19, as applicable. Contractor/ manufacturer is NVIDIA, 2788 San Tomas Expressway, Santa Clara, CA 95051 + +The SDK is subject to United States export laws and regulations. You agree that you will not ship, transfer or export the SDK into any country, or use the SDK in any manner, prohibited by the United States Bureau of Industry and Security or economic sanctions regulations administered by the U.S. Department of Treasury's Office of Foreign Assets Control (OFAC), or any applicable export laws, restrictions or regulations. These laws include restrictions on destinations, end users and end use. By accepting this Agreement, you confirm that you are not a resident or citizen of any country currently embargoed by the U.S. and that you are not otherwise prohibited from receiving the SDK + +Any notice delivered by NVIDIA to you under this Agreement will be delivered via mail, email or fax. You agree that any notices that NVIDIA sends you electronically will satisfy any legal communication requirements. Please direct your legal notices or other correspondence to NVIDIA Corporation, 2788 San Tomas Expressway, Santa Clara, California 95051, United States of America, Attention: Legal Department. + +This Agreement and any exhibits incorporated into this Agreement constitute the entire agreement of the parties with respect to the subject matter of this Agreement and supersede all prior negotiations or documentation exchanged between the parties relating to this SDK license. Any additional and/or conflicting terms on documents issued by you are null, void, and invalid. Any amendment or waiver under this Agreement shall be in writing and signed by representatives of both parties. + +(v. February 22, 2022) + +Chapter 8. cuDNN SUPPLEMENT TO SOFTWARE LICENSE AGREEMENT FOR NVIDIA SOFTWARE DEVELOPMENT KITS + +The terms in this supplement govern your use of the NVIDIA cuDNN SDK under the terms of your license agreement ("Agreement") as modified by this supplement. Capitalized terms used but not defined below have the meaning assigned to them in the Agreement. + +This supplement is an exhibit to the Agreement and is incorporated as an integral part of the Agreement. In the event of conflict between the terms in this supplement and the terms in the Agreement, the terms in this supplement govern. + +4.1 License Scope. The SDK is licensed for you to develop applications only for use in systems with NVIDIA GPUs. + +2. Distribution. The following portions of the SDK are distributable under the Agreement: the runtime files .so and .dll. + +In addition to the rights above, for parties that are developing software intended solely for use on Jetson development kits or Jetson modules and running Linux for Tegra software the following shall apply: the SDK may be distributed in its entirety, as provided by NVIDIA and without separation of its components, for you and/or your licensees to create software development kits for use only on the Jetson platform and running Linux for Tegra software. + +3. Licensing. If the distribution terms in this Agreement are not suitable for your organization, or for any questions regarding this Agreement, please contact NVIDIA at nvidia-compute-license-questions@nvidia.com + +(v. February 22, 2022) + +Notice + +This document is provided for information purposes only and shall not be regarded as a warranty of a certain functionality, condition, or quality of a product. NVIDIA Corporation ("NVIDIA") makes no representations or warranties, expressed or implied, as to the accuracy or completeness of the information contained in this document and assumes no responsibility for any errors contained herein. NVIDIA shall have no liability for the consequences or use of such information or for any infringement of patents or other rights of third parties that may result from its use. This document is not a commitment to develop, release, or deliver any Material (defined below), code, or functionality. + +NVIDIA reserves the right to make corrections, modifications, enhancements, improvements, and any other changes to this document, at any time without notice. + +Customer should obtain the latest relevant information before placing orders and should verify that such information is current and complete. + +NVIDIA products are sold subject to the NVIDIA standard terms and conditions of sale supplied at the time of order acknowledgement, unless otherwise agreed in an individual sales agreement signed by authorized representatives of NVIDIA and customer ("Terms of Sale"). NVIDIA hereby expressly objects to applying any customer general terms and conditions with regards to the purchase of the NVIDIA product referenced in this document. No contractual obligations are formed either directly or indirectly by this document. + +NVIDIA products are not designed, authorized, or warranted to be suitable for use in medical, military, aircraft, space, or life support equipment, nor in applications where failure or malfunction of the NVIDIA product can reasonably be expected to result in personal injury, death, or property or environmental damage. NVIDIA accepts no liability for inclusion and/or use of NVIDIA products in such equipment or applications and therefore such inclusion and/or use is at customer's own risk. + +NVIDIA makes no representation or warranty that products based on this document will be suitable for any specified use. Testing of all parameters of each product is not necessarily performed by NVIDIA. It is customer's sole responsibility to evaluate and determine the applicability of any information contained in this document, ensure the product is suitable and fit for the application planned by customer, and perform the necessary testing for the application in order to avoid a default of the application or the product. Weaknesses in customer's product designs may affect the quality and reliability of the NVIDIA product and may result in additional or different conditions and/or requirements beyond those contained in this document. NVIDIA accepts no liability related to any default, damage, costs, or problem which may be based on or attributable to: (i) the use of the NVIDIA product in any manner that is contrary to this document or (ii) customer product designs. + +No license, either expressed or implied, is granted under any NVIDIA patent right, copyright, or other NVIDIA intellectual property right under this document. Information published by NVIDIA regarding third-party products or services does not constitute a license from NVIDIA to use such products or services or a warranty or endorsement thereof. Use of such information may require a license from a third party under the patents or other intellectual property rights of the third party, or a license from NVIDIA under the patents or other intellectual property rights of NVIDIA. + +Reproduction of information in this document is permissible only if approved in advance by NVIDIA in writing, reproduced without alteration and in full compliance with all applicable export laws and regulations, and accompanied by all associated conditions, limitations, and notices. + +THIS DOCUMENT AND ALL NVIDIA DESIGN SPECIFICATIONS, REFERENCE BOARDS, FILES, DRAWINGS, DIAGNOSTICS, LISTS, AND OTHER DOCUMENTS (TOGETHER AND SEPARATELY, "MATERIALS") ARE BEING PROVIDED "AS IS." NVIDIA MAKES NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. TO THE EXTENT NOT PROHIBITED BY LAW, IN NO EVENT WILL NVIDIA BE LIABLE FOR ANY DAMAGES, INCLUDING WITHOUT LIMITATION ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, PUNITIVE, OR CONSEQUENTIAL DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF ANY USE OF THIS DOCUMENT, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Notwithstanding any damages that customer might incur for any reason whatsoever, NVIDIA's aggregate and cumulative liability towards customer for the products described herein shall be limited in accordance with the Terms of Sale for the product. + +Arm + +Arm, AMBA and Arm Powered are registered trademarks of Arm Limited. Cortex, MPCore and Mali are trademarks of Arm Limited. "Arm" is used to represent Arm Holdings plc; its operating company Arm Limited; and the regional subsidiaries Arm Inc.; Arm KK; Arm Korea Limited.; Arm Taiwan Limited; Arm France SAS; Arm Consulting (Shanghai) Co. Ltd.; Arm Germany GmbH; Arm Embedded Technologies Pvt. Ltd.; Arm Norway, AS and Arm Sweden AB. + +HDMI + +HDMI, the HDMI logo, and High-Definition Multimedia Interface are trademarks or registered trademarks of HDMI Licensing LLC. + +Blackberry/QNX + +Copyright (C) 2020 BlackBerry Limited. All rights reserved. + +Trademarks, including but not limited to BLACKBERRY, EMBLEM Design, QNX, AVIAGE, MOMENTICS, NEUTRINO and QNX CAR are the trademarks or registered trademarks of BlackBerry Limited, used under license, and the exclusive rights to such trademarks are expressly reserved. + +Google + +Android, Android TV, Google Play and the Google Play logo are trademarks of Google, Inc. + +Trademarks + +NVIDIA, the NVIDIA logo, and BlueField, CUDA, DALI, DRIVE, Hopper, JetPack, Jetson AGX Xavier, Jetson Nano, Maxwell, NGC, Nsight, Orin, Pascal, Quadro, Tegra, TensorRT, Triton, Turing and Volta are trademarks and/or registered trademarks of NVIDIA Corporation in the United States and other countries. Other company and product names may be trademarks of the respective companies with which they are associated. + +Copyright + +(C) 2014-2023 NVIDIA Corporation & affiliates. All rights reserved. + +NVIDIA Corporation | 2788 San Tomas Expressway, Santa Clara, CA 95051 + +www.nvidia.com + +THIRD PARTY LICENSES + +zlib + +/* zlib.h -- interface of the 'zlib' general purpose compression library + version 1.2.11, January 15th, 2017 + + Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + +*/ + + + +mateidavid/zstr + +The MIT License (MIT) + +Copyright (C) 2015 Matei David, Ontario Institute for Cancer Research + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + + +RapidJSON + +Tencent is pleased to support the open source community by making RapidJSON available. + +Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. + +Licensed under the MIT License (the "License"); you may not use this file except +in compliance with the License. You may obtain a copy of the License at + +http://opensource.org/licenses/MIT + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. + + + +{fmt} + +Copyright (C) 2012 - present, Victor Zverovich + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--- Optional exception to the license --- + +As an exception, if, as a result of your compiling your source code, portions of this Software are embedded into a machine-executable object form of such source code, you may redistribute such embedded portions in such object form without including the above copyright and permission notices. + + + +Sleef + +Copyright Naoki Shibata and contributors 2010 - 2021. +Distributed under the Boost Software License, Version 1.0. +(See accompanying file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt) diff --git a/directstorage/.signature.p7s b/directstorage/.signature.p7s new file mode 100644 index 0000000000000000000000000000000000000000..c304bce8ef92c8f2825982775ead50cedf12a125 Binary files /dev/null and b/directstorage/.signature.p7s differ diff --git a/directstorage/LICENSE-CODE.txt b/directstorage/LICENSE-CODE.txt new file mode 100644 index 0000000000000000000000000000000000000000..44378268be1b87777827ab64b1ea2d98e808850e --- /dev/null +++ b/directstorage/LICENSE-CODE.txt @@ -0,0 +1,21 @@ +Copyright (c) Microsoft Corporation. + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/directstorage/LICENSE.txt b/directstorage/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..105ee9b8b3e5345f0845360523a66dc22a7782d6 --- /dev/null +++ b/directstorage/LICENSE.txt @@ -0,0 +1,165 @@ +MICROSOFT SOFTWARE LICENSE TERMS + +MICROSOFT DIRECTSTORAGE SDK + +These license terms are an agreement between you and Microsoft Corporation (or one of its affiliates). They +apply to the software named above and any Microsoft services or software updates (except to the extent such +services or updates are accompanied by new or additional terms, in which case those different terms apply +prospectively and do not alter your or Microsoft's rights relating to pre-updated software or services). IF YOU +COMPLY WITH THESE LICENSE TERMS, YOU HAVE THE RIGHTS BELOW. BY USING THE SOFTWARE, YOU +ACCEPT THESE TERMS. + +1. INSTALLATION AND USE RIGHTS. + a) General. You may install and use any number of copies of the software to develop and test your + applications. + b) Third Party Components. The software may include third party components with separate legal + notices or governed by other agreements, as may be described in the ThirdPartyNotices file(s) + accompanying the software. + +2. DISTRIBUTABLE CODE. The software may contain code you are permitted to distribute (i.e. make + available for third parties) in applications you develop, as described in this Section. + a) Distribution Rights. The code and test files described below are distributable if included with the + software. + i. Distributables. You may copy and distribute the object code form of the software listed in the + distributables file list in the software; and + ii. Third Party Distribution. You may permit distributors of your applications to copy and distribute + any of this distributable code you elect to distribute with your applications. + b) Distribution Requirements. For any code you distribute, you must: + i. add significant primary functionality to it in your applications; + ii. require distributors and external end users to agree to terms that protect it and Microsoft at least + as much as this agreement; and + iii. indemnify, defend, and hold harmless Microsoft from any claims, including attorneys' fees, related + to the distribution or use of your applications, except to the extent that any claim is based solely + on the unmodified distributable code. + c) Distribution Restrictions. You may not: + i. use Microsoft's trademarks or trade dress in your application in any way that suggests your + application comes from or is endorsed by Microsoft; or + ii. modify or distribute the source code of any distributable code so that any part of it becomes + subject to any license that requires that the distributable code, any other part of the software, or + any of Microsoft's other intellectual property be disclosed or distributed in source code form, or + that others have the right to modify it. + +3. SCOPE OF LICENSE. The software is licensed, not sold. Microsoft reserves all other rights. Unless + applicable law gives you more rights despite this limitation, you will not (and have no right to): + a) work around any technical limitations in the software that only allow you to use it in certain ways; + b) reverse engineer, decompile or disassemble the software, or otherwise attempt to derive the source + code for the software, except and to the extent required by third party licensing terms governing use + of certain open source components that may be included in the software; + c) remove, minimize, block, or modify any notices of Microsoft or its suppliers in the software; + d) use the software in any way that is against the law or to create or propagate malware; or + e) share, publish, distribute, or lease the software (except for any distributable code, subject to the + terms above), provide the software as a stand-alone offering for others to use, or transfer the + software or this agreement to any third party. + +4. DATA. + a) Data Collection. The software may collect information about you and your use of the software, and + send that to Microsoft. Microsoft may use this information to provide services and improve our + products and services. You may opt-out of many of these scenarios, but not all, as described in the + product documentation. There are also some features in the software that may enable you to collect + data from users of your applications. If you use these features to enable data collection in your + applications, you must comply with applicable law, including providing appropriate notices to users of + your applications. You can learn more about data collection and use in the help documentation and + the privacy statement at https://aka.ms/privacy. Your use of the software operates as your consent to + these practices. + b) Processing of Personal Data. To the extent Microsoft is a processor or subprocessor of personal + data in connection with the software, Microsoft makes the commitments in the European Union + General Data Protection Regulation Terms of the Online Services Terms to all customers effective May + 25, 2018, at https://docs.microsoft.com/en-us/legal/gdpr. + +5. EXPORT RESTRICTIONS. You must comply with all domestic and international export laws and + regulations that apply to the software, which include restrictions on destinations, end users, and end use. + For further information on export restrictions, visit https://aka.ms/exporting. + +6. SUPPORT SERVICES. Microsoft is not obligated under this agreement to provide any support services for + the software. Any support provided is "as is", "with all faults", and without warranty of any kind. + +7. UPDATES. The software may periodically check for updates, and download and install them for you. You + may obtain updates only from Microsoft or authorized sources. Microsoft may need to update your system + to provide you with updates. You agree to receive these automatic updates without any additional notice. + Updates may not include or support all existing software features, services, or peripheral devices. + +8. ENTIRE AGREEMENT. This agreement, and any other terms Microsoft may provide for supplements, + updates, or third-party applications, is the entire agreement for the software. + +9. APPLICABLE LAW AND PLACE TO RESOLVE DISPUTES. If you acquired the software in the United + States or Canada, the laws of the state or province where you live (or, if a business, where your principal + place of business is located) govern the interpretation of this agreement, claims for its breach, and all + other claims (including consumer protection, unfair competition, and tort claims), regardless of conflict of + laws principles. If you acquired the software in any other country, its laws apply. If U.S. federal jurisdiction + exists, you and Microsoft consent to exclusive jurisdiction and venue in the federal court in King County, + Washington for all disputes heard in court. If not, you and Microsoft consent to exclusive jurisdiction and + venue in the Superior Court of King County, Washington for all disputes heard in court. + +10. CONSUMER RIGHTS; REGIONAL VARIATIONS. This agreement describes certain legal rights. You + may have other rights, including consumer rights, under the laws of your state or country. Separate and + apart from your relationship with Microsoft, you may also have rights with respect to the party from which + you acquired the software. This agreement does not change those other rights if the laws of your state or + country do not permit it to do so. For example, if you acquired the software in one of the below regions, or + mandatory country law applies, then the following provisions apply to you: + a) Australia. You have statutory guarantees under the Australian Consumer Law and nothing in this + agreement is intended to affect those rights. + b) Canada. If you acquired this software in Canada, you may stop receiving updates by turning off the + automatic update feature, disconnecting your device from the Internet (if and when you re-connect to + the Internet, however, the software will resume checking for and installing updates), or uninstalling + the software. The product documentation, if any, may also specify how to turn off updates for your + specific device or software. + c) Germany and Austria. + i. Warranty. The properly licensed software will perform substantially as described in any Microsoft + materials that accompany the software. However, Microsoft gives no contractual guarantee in + relation to the licensed software. + ii. Limitation of Liability. In case of intentional conduct, gross negligence, claims based on the + Product Liability Act, as well as, in case of death or personal or physical injury, Microsoft is liable + according to the statutory law. + Subject to the foregoing clause ii., Microsoft will only be liable for slight negligence if Microsoft is in + breach of such material contractual obligations, the fulfillment of which facilitate the due performance + of this agreement, the breach of which would endanger the purpose of this agreement and the + compliance with which a party may constantly trust in (so-called "cardinal obligations"). In other cases + of slight negligence, Microsoft will not be liable for slight negligence. + +11. DISCLAIMER OF WARRANTY. THE SOFTWARE IS LICENSED "AS IS." YOU BEAR THE RISK OF + USING IT. MICROSOFT GIVES NO EXPRESS WARRANTIES, GUARANTEES, OR CONDITIONS. + TO THE EXTENT PERMITTED UNDER APPLICABLE LAWS, MICROSOFT EXCLUDES ALL IMPLIED + WARRANTIES, INCLUDING MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND + NON-INFRINGEMENT. + +12. LIMITATION ON AND EXCLUSION OF DAMAGES. IF YOU HAVE ANY BASIS FOR RECOVERING + DAMAGES DESPITE THE PRECEDING DISCLAIMER OF WARRANTY, YOU CAN RECOVER FROM + MICROSOFT AND ITS SUPPLIERS ONLY DIRECT DAMAGES UP TO U.S. $5.00. YOU CANNOT + RECOVER ANY OTHER DAMAGES, INCLUDING CONSEQUENTIAL, LOST PROFITS, SPECIAL, + INDIRECT, OR INCIDENTAL DAMAGES. + This limitation applies to (a) anything related to the software, services, content (including + code) on third party Internet sites, or third party applications; and (b) claims for breach of + contract, warranty, guarantee, or condition; strict liability, negligence, or other tort; or any + other claim; in each case to the extent permitted by applicable law. + It also applies even if Microsoft knew or should have known about the possibility of the + damages. The above limitation or exclusion may not apply to you because your state, + province, or country may not allow the exclusion or limitation of incidental, consequential, or + other damages. + +Please note: As this software is distributed in Canada, some of the clauses in this agreement are +provided below in French. +Remarque: Ce logiciel étant distribué au Canada, certaines des clauses dans ce contrat sont +fournies ci-dessous en français. +EXONÉRATION DE GARANTIE. Le logiciel visé par une licence est offert " tel quel ". Toute +utilisation de ce logiciel est à votre seule risque et péril. Microsoft n'accorde aucune autre +garantie expresse. Vous pouvez bénéficier de droits additionnels en vertu du droit local sur la +protection des consommateurs, que ce contrat ne peut modifier. La ou elles sont permises par le +droit locale, les garanties implicites de qualité marchande, d'adéquation à un usage particulier et +d'absence de contrefaçon sont exclues. +LIMITATION DES DOMMAGES-INTÉRÊTS ET EXCLUSION DE RESPONSABILITÉ POUR LES +DOMMAGES. Vous pouvez obtenir de Microsoft et de ses fournisseurs une indemnisation en cas de +dommages directs uniquement à hauteur de 5,00 $ US. Vous ne pouvez prétendre à aucune +indemnisation pour les autres dommages, y compris les dommages spéciaux, indirects ou +accessoires et pertes de bénéfices. +Cette limitation concerne: +• tout ce qui est relié au logiciel, aux services ou au contenu (y compris le code) figurant sur +des sites Internet tiers ou dans des programmes tiers; et +• les réclamations au titre de violation de contrat ou de garantie, ou au titre de responsabilité +stricte, de négligence ou d'une autre faute dans la limite autorisée par la loi en vigueur. +Elle s'applique également, même si Microsoft connaissait ou devrait connaître l'éventualité d'un +tel dommage. Si votre pays n'autorise pas l'exclusion ou la limitation de responsabilité pour les +dommages indirects, accessoires ou de quelque nature que ce soit, il se peut que la limitation ou +l'exclusion ci-dessus ne s'appliquera pas à votre égard. +EFFET JURIDIQUE. Le présent contrat décrit certains droits juridiques. Vous pourriez avoir +d'autres droits prévus par les lois de votre pays. Le présent contrat ne modifie pas les droits que +vous confèrent les lois de votre pays si celles-ci ne le permettent pas. diff --git a/directstorage/Microsoft.Direct3D.DirectStorage.nuspec b/directstorage/Microsoft.Direct3D.DirectStorage.nuspec new file mode 100644 index 0000000000000000000000000000000000000000..34ddf552d75b9d515b10e0989a21978f349d302f --- /dev/null +++ b/directstorage/Microsoft.Direct3D.DirectStorage.nuspec @@ -0,0 +1,18 @@ + + + + Microsoft.Direct3D.DirectStorage + 1.2.2 + DirectStorage + Microsoft + false + LICENSE.txt + https://aka.ms/deprecateLicenseUrl + icon.png + README.md + https://aka.ms/directstorage/ + DirectStorage for Windows + © Microsoft Corporation. All rights reserved. + DirectStorage Direct3D graphics 3D + + \ No newline at end of file diff --git a/directstorage/NOTICES.txt b/directstorage/NOTICES.txt new file mode 100644 index 0000000000000000000000000000000000000000..0a3cb52c8701421232aecbaa8939d2aa58f4228e --- /dev/null +++ b/directstorage/NOTICES.txt @@ -0,0 +1,2161 @@ +NOTICES AND INFORMATION +Do Not Translate or Localize + +This software incorporates material from third parties. +Microsoft makes certain open source code available at https://3rdpartysource.microsoft.com, +or you may send a check or money order for US $5.00, including the product name, +the open source component name, platform, and version number, to: + +Source Code Compliance Team +Microsoft Corporation +One Microsoft Way +Redmond, WA 98052 +USA + +Notwithstanding any other terms, you may reverse engineer this software to the extent +required to debug changes to any libraries licensed under the GNU Lesser General Public License. + +--------------------------------------------------------- + +boost 1.72.0 - Apache-2.0 + + +(c) cosc cos +Copyright 2001 +Copyright 2003 +Copyright 2008 +(c) Copyright John +Copyright (c) 2007 +Copyright (c) 2014 +Copyright (c) 2018 +Copyright 2014 LRI +Copyright 2015 LRI +copyright (c) 2005 +Copyright 2014 LASMEA +(c) 2008 VeriSign, Inc. +Copyright (c) 2010 Ilya +Copyright Nat Goodspeed +(c) 2008 Gordon Woodhull +(c) David Abrahams 2002. +Copyright (c) 2018 Yi Ji +Copyright 2012 IBM Corp. +Copyright 2013 Kyle Lutz +(c) Peter Kankowski, 2008 +Copyright (c) 2019 Damian +Copyright 2003 Bruce Barr +Copyright 2006 Johan Rade +Copyright 2012 K R Walker +Copyright Jaap Suter 2003 +Copyright Jan Langer 2002 +Copyright Lingxi Li 2015. +copyright Jason Rice 2016 +copyright Jason Rice 2017 +copyright Xiaogang Zhang. +(c) MidLetter or MidNumLet +Copyright 2000 Jens Maurer +Copyright 2003 Jeremy Siek +Copyright 2005 Peter Dimov +Copyright 2005 Rene Rivera +Copyright 2007 Peter Dimov +Copyright 2008 Beman Dawes +Copyright 2008 Peter Dimov +Copyright 2011 Simon West. +Copyright 2013 Ankur Sinha +Copyright 2013 Peter Dimov +Copyright 2013 Rene Rivera +Copyright 2014 Neil Groves +Copyright 2014 Peter Dimov +Copyright 2016 Jorge Lodos +Copyright 2018 Peter Dimov +Copyright 2019 Peter Dimov +Copyright Beman Dawes 2002 +Copyright Beman Dawes 2003 +Copyright Beman Dawes 2006 +Copyright Beman Dawes 2007 +Copyright Beman Dawes 2008 +Copyright Beman Dawes 2009 +Copyright Beman Dawes 2010 +Copyright Beman Dawes 2011 +Copyright Beman Dawes 2013 +Copyright Beman Dawes 2014 +Copyright Beman Dawes 2015 +Copyright Bruno Dutra 2015 +Copyright Darin Adler 2000 +Copyright Franz Detro 2014 +Copyright Jens Maurer 2000 +Copyright Jens Maurer 2002 +Copyright Jens Maurer 2006 +Copyright Joel Falcou 2015 +Copyright Peter Dimov 2001 +Copyright Rene Rivera 2013 +Copyright Rene Rivera 2014 +Copyright Rene Rivera 2015 +Copyright Rene Rivera 2017 +(c) Copyright 2014 Jim Bell +Copyright (c) 2005 Voipster +Copyright (c) 2011 Jamboree +Copyright (c) 2013 Jamboree +Copyright (c) 2014 Jamboree +Copyright 2005 Dan Marsden. +Copyright 2008 John Maddock +Copyright 2009 Neil Groves. +Copyright 2010 John Maddock +Copyright 2011, Andrew Ross +Copyright 2013 Paul Bristow +Copyright 2014 John Maddock +Copyright 2014 NumScale SAS +Copyright 2014 Paul Bristow +Copyright 2015 NumScale SAS +Copyright 2015 Peter Dimov. +Copyright 2017 John Maddock +Copyright 2017 Peter Dimov. +Copyright 2017 Vinnie Falco +Copyright Beman Dawes 2001. +Copyright Beman Dawes 2005. +Copyright Beman Dawes, 2009 +Copyright Eric Niebler 2008 +Copyright Eric Niebler 2009 +Copyright Louis Dionne 2013 +Copyright Neil Groves 2007. +Copyright Neil Groves 2009. +Copyright Neil Groves 2010. +Copyright Neil Groves 2014. +Copyright Peter Dimov 2019. +Copyright Thomas Mang 2012. +copyright Louis Dionne 2016 +(c) Copyright Francois Faure +(c) Copyright Howard Hinnant +Copyright (c) 2017 Dynatrace +Copyright 2001 John Maddock. +Copyright 2003 - 2011 LASMEA +Copyright 2004 Eric Niebler. +Copyright 2005 Ben Hutchings +Copyright 2005 Eric Niebler. +Copyright 2006 Eric Niebler. +Copyright 2006 Ion Gaztanaga +Copyright 2007 Aaron Windsor +Copyright 2007 Baruch Zilber +Copyright 2007 Boris Gubenko +Copyright 2007 Eric Niebler. +Copyright 2008 CodeRage, LLC +Copyright 2008 Eric Niebler. +Copyright 2008 Gautam Sewani +Copyright 2009 Eric Niebler. +Copyright 2010 Eric Niebler. +Copyright 2011 Eric Niebler. +Copyright 2011 John Maddock. +Copyright 2012 Chung-Lin Wen +Copyright 2012 Denis Demidov +Copyright 2012 Eric Niebler. +Copyright 2012 John Maddock. +Copyright 2013 John Maddock. +Copyright 2014 MetaScale SAS +Copyright 2015 John Maddock. +Copyright 2016 John Maddock. +Copyright 2017 Daniel James. +Copyright 2018 John Maddock. +Copyright 2019 John Maddock. +Copyright Bryce Lelbach 2010 +Copyright Daniel Walker 2007 +Copyright Dietmar Kuehl 2001 +Copyright Eric Friedman 2002 +Copyright Eric Friedman 2003 +Copyright Eric Niebler 2005. +Copyright Eric Niebler 2014. +Copyright John Maddock 2006. +Copyright John Maddock 2007. +Copyright John Maddock 2008. +Copyright John Maddock 2010. +Copyright John Maddock 2012. +Copyright John Maddock 2014. +Copyright John Maddock 2015. +Copyright John Maddock 2016. +Copyright John Maddock 2017. +Copyright John Maddock 2018. +Copyright Orson Peters 2017. +Copyright Paul Bristow 2014. +Copyright Robert Ramey 2007. +Copyright Robin Eckert 2015. +Copyright Timmo Stange 2007. +(c) Copyright Jens Mauer 2001 +Copyright (c) 2002 Bill Kempf +Copyright (c) 2004 Peder Holt +Copyright (c) 2005 Peder Holt +Copyright (c) 2006 Johan Rade +Copyright (c) 2007 Peder Holt +Copyright (c) 2010 Peder Holt +Copyright (c) 2014 Ian Forbed +Copyright (c) 2015 Mario Lang +Copyright (c) 2018 Fady Essam +Copyright 2002 Daryle Walker. +Copyright 2005 Daniel Egloff. +Copyright 2005 Daniel Wallin. +Copyright 2005 Jeremy G. Siek +Copyright 2006 Andy Tompkins. +Copyright 2006 Douglas Gregor +Copyright 2007 Andy Tompkins. +Copyright 2007 David Jenkins. +Copyright 2008 David Jenkins. +Copyright 2008 Howard Hinnant +Copyright 2009 Andy Tompkins. +Copyright 2009, Andrew Sutton +Copyright 2010 Andy Tompkins. +Copyright 2010 Mario Mulansky +Copyright 2011 Karsten Ahnert +Copyright 2011 Mario Mulansky +Copyright 2012 Christoph Koke +Copyright 2012 Karsten Ahnert +Copyright 2012 Mario Mulansky +Copyright 2013 Karsten Ahnert +Copyright 2013 Mario Mulansky +Copyright 2013 Nikhar Agrawal +Copyright 2014 Anton Bikineev +Copyright 2014 Bill Gallafent +Copyright 2015 John Fletcher. +Copyright 2015 Mario Mulansky +Copyright 2018 Hans Dembinski +Copyright 2018 Stefan Seefeld +Copyright 2019 Hans Dembinski +Copyright 2019 Mateusz Loskot +Copyright Andy Tompkins 2006. +Copyright Daniel Walker 2006. +Copyright Daniel Wallin 2005. +Copyright Daniel Wallin 2006. +Copyright Daniel Wallin 2007. +Copyright Marco Guazzone 2014 +Copyright Nat Goodspeed 2014. +Copyright Nick Thompson 2017. +Copyright Nick Thompson 2019. +Copyright Nick Thompson, 2017 +Copyright Nick Thompson, 2018 +Copyright Nick Thompson, 2019 +Copyright Ruslan Baratov 2017 +Copyright Samuel Krempp 2003. +Copyright Steven J. Ross 2014 +Copyright Vladimir Prus 2002. +Copyright Vladimir Prus 2004. +Copyright Vladimir Prus, 2002 +(c) Copyright Beman Dawes 2002 +(c) Copyright Bill Kempf 2001. +(c) Copyright Bill Kempf 2002. +(c) Copyright Brian Kuhl 2016. +(c) Copyright Darin Adler 2000 +(c) Copyright Jeremy Siek 2006 +(c) Copyright Johan Rade 2006. +(c) Copyright Paul Moore 1999. +(c) Copyright Peter Dimov 2019 +(c) Copyright Synge Todo 2003. +(c) Copyright Tobias Schwinger +Copyright (c) 2001 Darin Adler +Copyright (c) 2001 Doug Gregor +Copyright (c) 2001 Peter Dimov +Copyright (c) 2002 Beman Dawes +Copyright (c) 2002 Jens Maurer +Copyright (c) 2002 Peter Dimov +Copyright (c) 2003 Daniel Frey +Copyright (c) 2003 Peter Dimov +Copyright (c) 2003 Thomas Witt +Copyright (c) 2005 Dan Marsden +Copyright (c) 2006 Dan Marsden +Copyright (c) 2006 Peter Dimov +Copyright (c) 2007 Dan Marsden +Copyright (c) 2007 Peter Dimov +Copyright (c) 2008 Beman Dawes +Copyright (c) 2008 Peter Dimov +Copyright (c) 2009 Carl Barron +Copyright (c) 2009 Peter Dimov +Copyright (c) 2010 Neil Groves +Copyright (c) 2012 David Stone +Copyright (c) 2013 Carl Barron +Copyright (c) 2013 Peter Dimov +Copyright (c) 2014 Lee Clagett +Copyright (c) 2014 Peter Dimov +Copyright (c) 2014 Tomoki Imai +Copyright (c) 2015 Seth Heeren +Copyright (c) 2016 Lee Clagett +Copyright (c) 2016 Peter Dimov +Copyright (c) 2017 Minmin Gong +Copyright (c) 2018 Peter Dimov +Copyright (c) Beman Dawes 2011 +Copyright (c) Beman Dawes 2015 +Copyright (c) Dan Watkins 2003 +Copyright (c) Jeremy Siek 2001 +Copyright 2000 Maarten Keijzer +Copyright 2005 Douglas Gregor. +Copyright 2005 Joel de Guzman. +Copyright 2006 Roland Schwarz. +Copyright 2008 Hartmut Kaiser. +Copyright 2010 Kenneth Riddile +Copyright 2011 Steven Watanabe +Copyright 2012 Andreas Pokorny +Copyright 2012 Steven Watanabe +Copyright 2013 Andrey Semashev +Copyright 2013 Pascal Germroth +Copyright 2014 Andrey Semashev +Copyright 2014 Antony Polukhin +Copyright 2015 Andrey Semashev +Copyright 2015 Antony Polukhin +Copyright 2015 Steven Watanabe +Copyright 2016 Andrey Semashev +Copyright 2017 Andrey Semashev +Copyright 2018 Steven Watanabe +Copyright 2019 Henry Schreiner +Copyright Alain Miniussi 2014. +Copyright Beman Dawes 1994-99. +Copyright David Abrahams 2001. +Copyright David Abrahams 2002. +Copyright David Abrahams 2003. +Copyright David Abrahams 2004. +Copyright David Abrahams 2005. +Copyright David Abrahams 2006. +Copyright David Abrahams 2009. +Copyright Douglas Gregor 2003. +Copyright Douglas Gregor 2004. +Copyright Emil Dotchevski 2007 +Copyright Jim Bosch 2010-2012. +Copyright John Maddock 2007-8. +Copyright Oliver Kowalke 2009. +Copyright Oliver Kowalke 2013. +Copyright Oliver Kowalke 2014. +Copyright Oliver Kowalke 2015. +Copyright Oliver Kowalke 2016. +Copyright Oliver Kowalke 2017. +Copyright Oliver Kowalke 2018. +Copyright Paul Mensonides 2003 +Copyright Sergey Krivonos 2017 +Copyright Shreyans Doshi 2017. +Copyright Stefan Seefeld 2005. +Copyright Stefan Seefeld 2016. +Copyright Steven Watanabe 2009 +Copyright Steven Watanabe 2010 +Copyright Steven Watanabe 2011 +Copyright Steven Watanabe 2014 +(c) Copyright 2002 Robert Ramey +(c) Copyright 2004 Robert Ramey +(c) Copyright 2005 John Maddock +(c) Copyright 2005 Robert Ramey +(c) Copyright 2007 Robert Ramey +(c) Copyright 2008 Robert Ramey +(c) Copyright 2009 Robert Ramey +(c) Copyright 2010 Daniel James +(c) Copyright 2010 Robert Ramey +(c) Copyright 2014 Robert Ramey +(c) Copyright Beman Dawes 1999. +(c) Copyright Beman Dawes 2000. +(c) Copyright Beman Dawes 2001. +(c) Copyright Beman Dawes 2003. +(c) Copyright Boris Rasin 2014. +(c) Copyright Darin Adler 2001. +(c) Copyright Jens Maurer 2001. +(c) Copyright Jens Maurer 2003. +(c) Copyright Jeremy Siek 1999. +(c) Copyright Jeremy Siek 2000. +(c) Copyright Jeremy Siek 2001. +(c) Copyright Jeremy Siek 2002. +(c) Copyright Jeremy Siek 2004. +(c) Copyright Jim Douglas 2005. +(c) Copyright Jorge Lodos 2008. +(c) Copyright Peter Dimov 2001. +(c) Copyright Peter Dimov 2002. +(c) Copyright Peter Dimov 2008. +(c) Copyright Peter Dimov 2017. +(c) Copyright Rene Rivera 2005. +(c) Copyright Robert Ramey 2004 +(c) Copyright Thomas Witt 2002. +(c) Copyright Toon Knapen 2001. +(c) Copyright Toon Knapen 2003. +Copyright (c) 2002 John Maddock +Copyright (c) 2003 John Maddock +Copyright (c) 2003 Martin Wille +Copyright (c) 2004 John Maddock +Copyright (c) 2005 Eric Niebler +Copyright (c) 2005 Peter Dimov. +Copyright (c) 2006 Eric Niebler +Copyright (c) 2006 John Maddock +Copyright (c) 2006 Stephen Nutt +Copyright (c) 2007 John Maddock +Copyright (c) 2008 Roelof Naude +Copyright (c) 2009 John Maddock +Copyright (c) 2010 Eric Niebler +Copyright (c) 2011 Aaron Graham +Copyright (c) 2011 Brandon Kohn +Copyright (c) 2011 Eric Niebler +Copyright (c) 2011 John Maddock +Copyright (c) 2012 Nathan Ridge +Copyright (c) 2012 Oswin Krause +Copyright (c) 2012 Robert Ramey +Copyright (c) 2013 Eurodecision +Copyright (c) 2014 Eric Niebler +Copyright (c) 2015 John Maddock +Copyright (c) 2015 Orson Peters +Copyright (c) 2015 Robert Ramey +Copyright (c) 2017 John Maddock +Copyright (c) 2017 Robert Ramey +Copyright (c) 2017 Vinnie Falco +Copyright (c) Thomas Witt 2002. +Copyright 2002-2018 Peter Dimov +Copyright 2003-2005 Peter Dimov +Copyright 2004-2005 Peter Dimov +Copyright 2004-2006 Peter Dimov +Copyright 2004-2008 Peter Dimov +Copyright 2005 Matthias Troyer. +Copyright 2005-2013 Peter Dimov +Copyright 2007 Tobias Schwinger +Copyright 2008 Christophe Henry +Copyright 2008,2012 Peter Dimov +Copyright 2011 Christophe Henry +Copyright 2012 (c) Google, Inc. +Copyright 2012 Lucanus Simonson +Copyright 2012, Philipp Moeller +Copyright 2013 Maciej Piechotka +Copyright Adam D. Walling 2012. +Copyright Aleksey Gurtovoy 2004 +Copyright Aleksey Gurtovoy 2006 +Copyright Aleksey Gurtovoy 2008 +Copyright Alexander Grund 2018. +Copyright Andrey Semashev 2013. +Copyright Andrey Semashev 2015. +Copyright Andrey Semashev 2016. +Copyright Andrey Semashev 2018. +Copyright Andrey Semashev 2019. +Copyright Beman Dawes 2002-2009 +Copyright Benjamin Sobotta 2012 +Copyright Benjamin Worpitz 2018 +Copyright Bertolt Mildner 2004. +Copyright Charly Chevalier 2015 +Copyright Daniel Trebbien 2010. +Copyright Frank Mori Hess 2007. +Copyright Frank Mori Hess 2008. +Copyright Frank Mori Hess 2009. +Copyright Jens Maurer 2000-2001 +Copyright Jens Maurer 2006-1011 +Copyright Jessica Hamilton 2014 +Copyright John Maddock 2008-11. +Copyright John R. Bandela 2001. +Copyright Paul A. Bristow 2006. +Copyright Paul A. Bristow 2007. +Copyright Paul A. Bristow 2010. +Copyright Paul A. Bristow 2014. +Copyright Paul A. Bristow 2017. +Copyright Peter Dimov 2000-2002 +Copyright Peter Dimov 2000-2003 +Copyright Peter Dimov 2001-2002 +Copyright Peter Dimov 2001-2003 +Copyright Rene Rivera 2005-2016 +Copyright Rene Rivera 2008-2013 +Copyright Rene Rivera 2008-2015 +Copyright Rene Rivera 2008-2017 +Copyright Rene Rivera 2008-2019 +Copyright Rene Rivera 2011-2012 +Copyright Rene Rivera 2011-2015 +Copyright Rene Rivera 2012-2015 +Copyright Rene Rivera 2013-2015 +Copyright Rene Rivera 2013-2018 +Copyright Rene Rivera 2014-2015 +Copyright Rene Rivera 2015-2016 +Copyright Rene Rivera 2015-2019 +(c) Copyright 2007 Andrew Sutton +(c) Copyright 2007 David Deakins +(c) Copyright 2008 CodeRage, LLC +(c) Copyright 2012 Vicente Botet +(c) Copyright 2013 Tim Blechmann +(c) Copyright Andrew Sutton 2007 +(c) Copyright Balint Cserni 2017 +(c) Copyright Bryce Lelbach 2010 +(c) Copyright Bryce Lelbach 2011 +(c) Copyright Daniel K. O. 2005. +(c) Copyright Edward Diener 2012 +(c) Copyright Hubert Holin 2001. +(c) Copyright Ion Gaztanaga 2008 +(c) Copyright Jeremy Siek, 2001. +(c) Copyright John Maddock 2000. +(c) Copyright John Maddock 2001. +(c) Copyright John Maddock 2002. +(c) Copyright John Maddock 2003. +(c) Copyright John Maddock 2005. +(c) Copyright John Maddock 2006. +(c) Copyright John Maddock 2007. +(c) Copyright John Maddock 2008. +(c) Copyright John Maddock 2010. +(c) Copyright John Maddock 2011. +(c) Copyright John Maddock 2015. +(c) Copyright John Maddock 2017. +(c) Copyright John Maddock 2018. +(c) Copyright Lie-Quan Lee 2001. +(c) Copyright Martin Wille 2003. +(c) Copyright Orson Peters 2017. +(c) Copyright Rani Sharoni 2003. +Copyright (3) Ion Gaztanaga 2013 +Copyright (c) 2001 Bruce Florman +Copyright (c) 2001 Daniel Nuffer +Copyright (c) 2001 Dietmar Kuehl +Copyright (c) 2002 Jeff Westfahl +Copyright (c) 2003 Eric Friedman +Copyright (c) 2003 Giovanni Bajo +Copyright (c) 2003 Vaclav Vesely +Copyright (c) 2004 Angus Leeming +Copyright (c) 2004 Daniel Wallin +Copyright (c) 2005 Aaron Windsor +Copyright (c) 2005 Stefan Arentz +Copyright (c) 2006 Daniel Wallin +Copyright (c) 2006 Tomas Puverle +Copyright (c) 2008 Eric Niebler. +Copyright (c) 2008 Ion Gaztanaga +Copyright (c) 2009 Andrew Sutton +Copyright (c) 2009 Helge Bahmann +Copyright (c) 2009 Phil Endecott +Copyright (c) 2010 Artyom Beilis +Copyright (c) 2010 Bryce Lelbach +Copyright (c) 2010 Helge Bahmann +Copyright (c) 2010 Thomas Heller +Copyright (c) 2010 Tim Blechmann +Copyright (c) 2011 Bryce Lelbach +Copyright (c) 2011 Helge Bahmann +Copyright (c) 2011 Thomas Heller +Copyright (c) 2011 Tim Blechmann +Copyright (c) 2012 Paul Fultz II +Copyright (c) 2012 Tim Blechmann +Copyright (c) 2013 Agustin Berge +Copyright (c) 2013 Joaquim Duran +Copyright (c) 2013 Tim Blechmann +Copyright (c) 2014 Agustin Berge +Copyright (c) 2014 Ahmed Charles +Copyright (c) 2014 John Fletcher +Copyright (c) 2014 Paul Fultz II +Copyright (c) 2015 Artyom Beilis +Copyright (c) 2015 Ion Gaztanaga +Copyright (c) 2015 John Fletcher +Copyright (c) 2015 Paul Fultz II +Copyright (c) 2016 Barrett Adair +Copyright (c) 2016 Paul Fultz II +Copyright (c) 2017 Michel Morin. +Copyright (c) Aaron Windsor 2007 +Copyright (c) Kevlin Henney 2001 +Copyright (c) Pablo Aguilar 2005 +Copyright 2002, 2009 Peter Dimov +Copyright 2005, 2014 Peter Dimov +Copyright 2006 Thorsten Ottosen. +Copyright 2007 Christian Henning +Copyright 2007, 2014 Peter Dimov +Copyright 2007, 2019 Peter Dimov +Copyright 2008 Christian Henning +Copyright 2008 Intel Corporation +Copyright 2009 Christian Henning +Copyright 2009-2014 Neil Groves. +Copyright 2010 Christian Henning +Copyright 2010 Thomas Claveirole +Copyright 2012 Christian Henning +Copyright 2012 Olivier Tournaire +Copyright 2013 Christian Henning +Copyright 2013 Christian Shelton +Copyright 2013 Cromwell D. Enage +Copyright 2015-2017 Peter Dimov. +Copyright 2015-2019 Peter Dimov. +Copyright 2016, 2017 Peter Dimov +Copyright 2017 James E. King III +Copyright 2017-2019 Peter Dimov. +Copyright Alexander Nasonov 2004 +Copyright Beman Dawes 1995-2001. +Copyright Beman Dawes 2002, 2006 +Copyright Beman Dawes 2003, 2006 +Copyright Beman Dawes 2006, 2007 +Copyright Beman Dawes, 2002-2005 +Copyright Christopher Brown 2013 +Copyright Jason Rhinelander 2016 +Copyright Louis Dionne 2013-2017 +Copyright Neil Groves 2003-2004. +Copyright Nicholas Thompson 2018 +Copyright Nikhar Agrawal 2013-14 +Copyright Nikolay Mladenov 2007. +Copyright Pavol Droba 2002-2003. +Copyright Pavol Droba 2002-2004. +Copyright Pavol Droba 2002-2006. +Copyright Peter Dimov 2017, 2018 +Copyright Thorsten Ottosen 2006. +Copyright Thorsten Ottosen 2008. +copyright Boost Software License +copyright Louis Dionne 2013-2016 +copyright Louis Dionne 2013-2017 +(c) Copyright 2006 David Abrahams +(c) Copyright 2006 Douglas Gregor +(c) Copyright 2009 Eric Bose-Wolf +(c) Copyright 2013 Ruslan Baratov +(c) Copyright Anton Bikineev 2014 +(c) Copyright Artyom Beilis 2010. +(c) Copyright Boris Gubenko 2007. +(c) Copyright Bruno Lalande 2008. +(c) Copyright Daniel Wallin 2004. +(c) Copyright Daryle Walker 2001. +(c) Copyright Douglas Gregor 2010 +(c) Copyright Edward Diener 2011. +(c) Copyright Edward Diener 2013. +(c) Copyright Edward Diener 2014. +(c) Copyright Edward Diener 2015. +(c) Copyright Edward Diener 2016. +(c) Copyright Edward Diener 2019. +(c) Copyright Gennaro Prota 2003. +(c) Copyright Howard Hinnant 2004 +(c) Copyright Ion Gaztanaga 2005. +(c) Copyright Ion Gaztanaga 2006. +(c) Copyright Ion Gaztanaga 2009. +(c) Copyright Ion Gaztanaga 2014. +(c) Copyright Juergen Hunold 2008 +(c) Copyright Milan Svoboda 2008. +(c) Copyright Nick Thompson 2017. +(c) Copyright Nick Thompson 2018. +(c) Copyright Nick Thompson 2019. +(c) Copyright Noel Belcourt 2007. +(c) Copyright Pablo Halpern 2009. +(c) Copyright Ronald Garcia 2002. +Copyright (c) 2000 Stephen Cleary +Copyright (c) 2001 Daryle Walker. +Copyright (c) 2001 David Abrahams +Copyright (c) 2001 Stephen Cleary +Copyright (c) 2002 David Abrahams +Copyright (c) 2002 Joel de Guzman +Copyright (c) 2003 David Abrahams +Copyright (c) 2003 Gennaro Prota. +Copyright (c) 2003 Hartmut Kaiser +Copyright (c) 2003 Howard Hinnant +Copyright (c) 2003 Joel de Guzman +Copyright (c) 2003 Vesa Karvonen. +Copyright (c) 2003 Vladimir Prus. +Copyright (c) 2004 Hartmut Kaiser +Copyright (c) 2004 Joel de Guzman +Copyright (c) 2004 Ralf Mattethat +Copyright (c) 2005 Igor Chesnokov +Copyright (c) 2006 Douglas Gregor +Copyright (c) 2006 Piotr Wyderski +Copyright (c) 2006 Xiaogang Zhang +Copyright (c) 2006-7 John Maddock +Copyright (c) 2007 Douglas Gregor +Copyright (c) 2007 Hartmut Kaiser +Copyright (c) 2007 Joel de Guzman +Copyright (c) 2008 Michael Marcin +Copyright (c) 2009 Chris Hoeppler +Copyright (c) 2009 Francois Barel +Copyright (c) 2009 Gunter Winkler +Copyright (c) 2009 Hartmut Kaiser +Copyright (c) 2009 Sebastian Redl +Copyright (c) 2010 Alfredo Correa +Copyright (c) 2011 ! Brandon Kohn +Copyright (c) 2011 Hartmut Kaiser +Copyright (c) 2011 Thomas Bernard +Copyright (c) 2012 Hartmut Kaiser +Copyright (c) 2012 Martin Raspaud +Copyright (c) 2013 Anton Bikineev +Copyright (c) 2013 Mateusz Loskot +Copyright (c) 2013 Sebastian Redl +Copyright (c) 2014 Erik Erlandson +Copyright (c) 2014 Glen Fernandes +Copyright (c) 2014 Joel de Guzman +Copyright (c) 2014 Oliver Kowalke +Copyright (c) 2014 Thomas Bernard +Copyright (c) 2015 Sebastian Redl +Copyright (c) 2016 Norbert Wenzel +Copyright (c) 2017 Daniela Engert +Copyright (c) 2018 Alain Miniussi +Copyright (c) 2018 Evgeny Shulgin +Copyright (c) 2018 Stefan Seefeld +Copyright (c) 2019 Joel de Guzman +Copyright (c) Chris Glover, 2016. +Copyright (c) Douglas Gregor 2004 +Copyright (c) Douglas Gregor 2008 +Copyright (c) Marshall Clow 2014. +Copyright (c) Marshall Clow 2017. +Copyright (c) Vladimir Prus 2003. +Copyright 2001 Indiana University +Copyright 2005 Alexander Nasonov. +Copyright 2005-2009 Daniel James. +Copyright 2005-2011 Daniel James. +Copyright 2005-2012 Daniel James. +Copyright 2005-2014 Daniel James. +Copyright 2006-2007 Boris Gubenko +Copyright 2007 Alexandre Courpron +Copyright 2007-2008 CodeRage, LLC +Copyright 2007-2012 Ion Gaztanaga +Copyright 2015, 2016 Peter Dimov. +Copyright 2015, 2017 Peter Dimov. +Copyright 2015, 2019 Peter Dimov. +Copyright 2017 James E. King, III +Copyright 2017, 2018 Peter Dimov. +Copyright 2017, 2019 Peter Dimov. +Copyright Barrett Adair 2015-2017 +Copyright Barrett Adair 2015-2018 +Copyright Barrett Adair 2016-2017 +Copyright Cromwell D. Enage 2013. +Copyright Cromwell D. Enage 2017. +Copyright Cromwell D. Enage 2018. +Copyright Cromwell D. Enage 2019. +Copyright Dave Abrahams 2001-2002 +Copyright Eric Friedman 2002-2003 +Copyright John Maddock 2005-2006. +Copyright John Maddock 2005-2008. +Copyright Jonathan Turkanis 2005. +Copyright Thijs van den Berg 2014 +Copyright Thorsten Ottosen, 2009. +(c) Copyright 2005 Matthias Troyer +(c) Copyright 2007 Matthias Troyer +(c) Copyright 2008 Matthias Troyer +(c) Copyright 2013 Andrey Semashev +(c) Copyright 2017 Andrey Semashev +(c) Copyright David Abrahams 2000. +(c) Copyright David Abrahams 2001. +(c) Copyright David Abrahams 2002. +(c) Copyright David Abrahams 2003. +(c) Copyright David Abrahams 2004. +(c) Copyright Douglas Gregor 2001. +(c) Copyright Douglas Gregor 2002. +(c) Copyright Ignacy Gawedzki 2010 +(c) Copyright Joel de Guzman 2003. +(c) Copyright John Maddock 2001-8. +(c) Copyright John Maddock 2006-8. +(c) Copyright Paul A. Bristow 2011 +(c) Copyright Roland Richter 2003. +(c) Copyright Stefan Slapeta 2004. +(c) Copyright Stephen Cleary 2000. +Copyright (c) 1995, Gerald Evenden +Copyright (c) 2000 David Abrahams. +Copyright (c) 2003 Paul Mensonides +Copyright (c) 2003-2008 Jan Gaspar +Copyright (c) 2005 Douglas Gregor. +Copyright (c) 2005-2007 Peder Holt +Copyright (c) 2006 Steven Watanabe +Copyright (c) 2006-2008 Johan Rade +Copyright (c) 2007 Alexey Baskakov +Copyright (c) 2007 Matthias Troyer +Copyright (c) 2008 Frank Mori Hess +Copyright (c) 2008 Steven Watanabe +Copyright (c) 2008-2009 Ben Hanson +Copyright (c) 2009 Boris Schaeling +Copyright (c) 2009 Frank Mori Hess +Copyright (c) 2009 Steven Watanabe +Copyright (c) 2009, Gunter Winkler +Copyright (c) 2009, Marco Guazzone +Copyright (c) 2010 Paul A. Bristow +Copyright (c) 2011 Emil Dotchevski +Copyright (c) 2011 Steven Watanabe +Copyright (c) 2012 Boris Schaeling +Copyright (c) 2012 Kohei Takahashi +Copyright (c) 2012, Michele Caini. +Copyright (c) 2013 Antony Polukhin +Copyright (c) 2013 Paul A. Bristow +Copyright (c) 2014 Andrey Semashev +Copyright (c) 2014 Christoph Weiss +Copyright (c) 2014 Kohei Takahashi +Copyright (c) 2015 Andrey Semashev +Copyright (c) 2015 Kohei Takahashi +Copyright (c) 2016 Kohei Takahashi +Copyright (c) 2017 Andrey Semashev +Copyright (c) 2017 Kohei Takahashi +Copyright (c) 2018 Andrey Semashev +Copyright (c) 2018 Kohei Takahashi +Copyright (c) 2018-2019 Cem Bassoy +Copyright (c) 2019 Andrey Semashev +Copyright (c) Andrey Semashev 2017 +Copyright (c) David Abrahams 2001. +Copyright 2002 Indiana University. +Copyright 2003 Guillaume Melquiond +Copyright 2005 Guillaume Melquiond +Copyright 2007 Stanford University +Copyright 2009-2011 Karsten Ahnert +Copyright 2009-2011 Mario Mulansky +Copyright 2009-2012 Karsten Ahnert +Copyright 2009-2012 Mario Mulansky +Copyright 2009-2013 Karsten Ahnert +Copyright 2009-2013 Mario Mulansky +Copyright 2009-2015 Mario Mulansky +Copyright 2010-2011 Karsten Ahnert +Copyright 2010-2011 Mario Mulansky +Copyright 2010-2012 Karsten Ahnert +Copyright 2010-2012 Mario Mulansky +Copyright 2010-2013 Karsten Ahnert +Copyright 2010-2013 Mario Mulansky +Copyright 2010-2014 Mario Mulansky +Copyright 2010-2015 Mario Mulansky +Copyright 2011 -2013 John Maddock. +Copyright 2011-2012 Karsten Ahnert +Copyright 2011-2012 Mario Mulansky +Copyright 2011-2013 Karsten Ahnert +Copyright 2011-2013 Mario Mulansky +Copyright 2011-2015 Mario Mulansky +Copyright 2012-2013 Karsten Ahnert +Copyright 2012-2013 Mario Mulansky +Copyright 2012-2015 Mario Mulansky +Copyright 2013-2014 Karsten Ahnert +Copyright 2013-2014 Mario Mulansky +Copyright 2015 Klemens Morgenstern +Copyright 2015-2016 Hans Dembinski +Copyright 2015-2017 Hans Dembinski +Copyright 2015-2018 Hans Dembinski +Copyright 2015-2019 Hans Dembinski +Copyright 2016 Klemens Morgenstern +Copyright 2018-2019 Hans Dembinski +Copyright 2019 Przemyslaw Bartosik +Copyright Christoper Kohlhoff 2007 +Copyright David Abrahams 2000-2002 +Copyright David Abrahams 2001-2002 +Copyright David Abrahams 2002-2003 +Copyright David Abrahams 2003-2004 +Copyright Douglas Gregor 2001-2006 +Copyright John Maddock 2006, 2007. +Copyright John Maddock 2006, 2010. +Copyright John Maddock 2007, 2014. +Copyright John Maddock 2010, 2012. +Copyright Vladimir Prus 2002-2004. +(c) Copyright 2004 Pavel Vozenilek. +(c) Copyright 2007 Anthony Williams +(c) Copyright 2008 Anthony Williams +(c) Copyright 2016 Raffi Enficiaud. +(c) Copyright Andrey Semashev 2017. +(c) Copyright Antony Polukhin 2013. +(c) Copyright Antony Polukhin 2014. +(c) Copyright Craig Henderson 2002. +(c) Copyright Dustin Spicuzza 2009. +(c) Copyright Jonathan Graehl 2004. +(c) Copyright Paul A. Bristow 2006. +(c) Copyright Paul Mensonides 2002. +(c) Copyright Paul Mensonides 2003. +(c) Copyright Paul Mensonides 2005. +(c) Copyright Paul Mensonides 2011. +(c) Copyright Paul Mensonides 2012. +(c) Copyright Peter Dimov 2004-2005 +(c) Copyright Raffi Enficiaud 2017. +(c) Copyright Raffi Enficiaud 2018. +(c) Copyright Raffi Enficiaud 2019. +Copyright (c) 2000, Frank Warmerdam +Copyright (c) 2001-2003 Mac Murrett +Copyright (c) 2001-2005 Peter Dimov +Copyright (c) 2001-2008 Peter Dimov +Copyright (c) 2002, Frank Warmerdam +Copyright (c) 2003-2005 Peter Dimov +Copyright (c) 2004 Arkadiy Vertleyb +Copyright (c) 2005 Arkadiy Vertleyb +Copyright (c) 2005-2006 Dan Marsden +Copyright (c) 2005-2007 Dan Marsden +Copyright (c) 2006 Arkadiy Vertleyb +Copyright (c) 2006 Tobias Schwinger +Copyright (c) 2007 Tobias Schwinger +Copyright (c) 2011 Julio Hoffimann. +Copyright (c) 2012 Anthony Williams +Copyright (c) 2012 Lorenzo Caminiti +Copyright (c) 2013-2014 Damien Buhl +Copyright (c) 2016 K. Noel Belcourt +Copyright (c) 2016-2019Damian Jarek +Copyright 2002, 2005 Daryle Walker. +Copyright 2008 Andreas Huber Doenni +Copyright 2008-2009 Frank Mori Hess +Copyright 2008-2010 Gordon Woodhull +Copyright 2011 - 2013 John Maddock. +Copyright 2011-2012 Steven Watanabe +Copyright 2012-2013 Steven Watanabe +Copyright 2015-2018 Andrey Semashev +Copyright 2016-2018 Andrey Semashev +Copyright 2017, NVIDIA CORPORATION. +Copyright Douglas Gregor 2001-2003. +Copyright Douglas Gregor 2001-2004. +Copyright Douglas Gregor 2002-2003. +Copyright Douglas Gregor 2002-2004. +Copyright Eric Niebler 2013-present +Copyright Gottfried Ganssauge 2003. +Copyright Howard Hinnant 2007-2010. +Copyright John R. Bandela 2000-2002 +Copyright Kevlin Henney, 2000-2005. +Copyright Michael Drexl 2005, 2006. +Copyright Sebastian Ramacher, 2007. +Copyright Steven Watanabe 2009-2011 +Copyright Steven Watanabe 2010-2011 +Copyright Thijs van den Berg, 2008. +(c) Copyright 2002, 2003 Beman Dawes +(c) Copyright 2002-2009 Robert Ramey +(c) Copyright 2002-2014 Robert Ramey +(c) Copyright 2002-4 Pavel Vozenilek +(c) Copyright 2016 Ashish Sadanandan +(c) Copyright Aleksey Gurtovoy 2002. +(c) Copyright Aleksey Gurtovoy 2003. +(c) Copyright Beman Dawes 1995-2001. +(c) Copyright Beman Dawes 1999-2003. +(c) Copyright Beman Dawes 2006, 2009 +(c) Copyright Daniel Frey 2002-2017. +(c) Copyright Eric Niebler 2004-2005 +(c) Copyright Herve Bronnimann 2004. +(c) Copyright Jeremiah Willcock 2004 +(c) Copyright Jeremy Siek 1999-2001. +(c) Copyright Jessica Hamilton 2014. +(c) Copyright Markus Schoepflin 2007 +(c) Copyright Matthias Troyerk 2006. +(c) Copyright Peter Dimov 2001, 2002 +(c) Copyright Reimar Doffinger 2018. +(c) Copyright Thomas Claveirole 2010 +(c) Copyright Thorsten Ottosen 2005. +Copyright (2) Beman Dawes 2010, 2011 +Copyright (c) 1998-2002 John Maddock +Copyright (c) 1998-2004 John Maddock +Copyright (c) 1998-2005 John Maddock +Copyright (c) 1998-2009 John Maddock +Copyright (c) 1999-2003 Jaakko Jarvi +Copyright (c) 2001 Alexander Peslyak +Copyright (c) 2001 Daniel C. Nuffer. +Copyright (c) 2001, 2002 Peter Dimov +Copyright (c) 2001, Daniel C. Nuffer +Copyright (c) 2001-2003 John Maddock +Copyright (c) 2002, 2003 Peter Dimov +Copyright (c) 2002-2003 Martin Wille +Copyright (c) 2003 Gerald I. Evenden +Copyright (c) 2003-2005 John Maddock +Copyright (c) 2004 Gerald I. Evenden +Copyright (c) 2005 Matthew Calabrese +Copyright (c) 2005-2009 Jongsoo Park +Copyright (c) 2005-2016 Daniel James +Copyright (c) 2007 Marcin Kalicinski +Copyright (c) 2007, 2008 Peter Dimov +Copyright (c) 2007, 2013 Peter Dimov +Copyright (c) 2007, 2014 Peter Dimov +Copyright (c) 2008 Gerald I. Evenden +Copyright (c) 2008, 2009 Peter Dimov +Copyright (c) 2008, 2011 Peter Dimov +Copyright (c) 2008, 2018 Peter Dimov +Copyright (c) 2009, 2015 Peter Dimov +Copyright (c) 2010-2011 David Bellot +Copyright (c) 2013 Tim Blechmann ARM +Copyright (c) 2015-2019 Vinnie Falco +Copyright (c) 2016-2019 Vinnie Falco +Copyright (c) 2017 James E. King III +Copyright (c) 2018 James E. King III +Copyright (c) Christof Meerwald 2003 +Copyright (c) Jeremy Siek 2001-2003. +Copyright (c) T. Zachary Laine 2018. +Copyright 2011, 2012 Paul A. Bristow +Copyright 2011-2013 Thorsten Ottosen +Copyright 2013 Christopher Kormanyos +Copyright 2013 University of Warsaw. +Copyright 2013, 2017 Andrey Semashev +Copyright 2013, 2017-2018 Cray, Inc. +Copyright 2014 Christopher Kormanyos +Copyright 2015, 2017 Andrey Semashev +Copyright 2015-2019 Antony Polukhin. +Copyright 2016, 2017 Andrey Semashev +Copyright 2016-2019 Antony Polukhin. +Copyright 2018, 2019 Andrey Semashev +Copyright 2018-2019 Antony Polukhin. +Copyright Aleksey Gurtovoy 2000-2002 +Copyright Aleksey Gurtovoy 2000-2003 +Copyright Aleksey Gurtovoy 2000-2004 +Copyright Aleksey Gurtovoy 2000-2006 +Copyright Aleksey Gurtovoy 2000-2008 +Copyright Aleksey Gurtovoy 2000-2009 +Copyright Aleksey Gurtovoy 2000-2010 +Copyright Aleksey Gurtovoy 2001-2004 +Copyright Aleksey Gurtovoy 2001-2006 +Copyright Aleksey Gurtovoy 2001-2007 +Copyright Aleksey Gurtovoy 2001-2008 +Copyright Aleksey Gurtovoy 2002-2004 +Copyright Aleksey Gurtovoy 2002-2006 +Copyright Aleksey Gurtovoy 2003-2004 +Copyright Aleksey Gurtovoy 2003-2007 +Copyright Frank Mori Hess 2007,2009. +Copyright Frank Mori Hess 2007-2008. +Copyright Frank Mori Hess 2007-2009. +Copyright Frank Mori Hess 2007-2010. +Copyright Kohei Takahashi 2012-2014. +Copyright Paul A. Bristow 2006-2011. +Copyright Paul A. Bristow 2007, 2009 +Copyright Shunsuke Sogame 2005-2006. +copyright 2004 Brian Ravnsgaard Riis +(c) Copyright 2005-7 Anthony Williams +(c) Copyright 2005-8 Anthony Williams +(c) Copyright 2006-7 Anthony Williams +(c) Copyright 2006-8 Anthony Williams +(c) Copyright 2007-2009 Andrew Sutton +(c) Copyright 2007-8 Anthony Williams +(c) Copyright 2007-9 Anthony Williams +(c) Copyright 2008-9 Anthony Williams +(c) Copyright Edward Diener 2011,2012 +(c) Copyright Edward Diener 2011-2015 +(c) Copyright Edward Diener 2012,2013 +(c) Copyright Gennadiy Rozental 2001. +(c) Copyright Ion Gaztanaga 2006-2015 +(c) Copyright Ion Gaztanaga 2010-2013 +(c) Copyright Ion Gaztanaga 2013-2014 +(c) Copyright John Maddock 2005-2006. +(c) Copyright John Maddock 2006, 2015 +(c) Copyright Jonathan Turkanis 2003. +(c) Copyright Jonathan Turkanis 2004. +(c) Copyright Markus Schoepflin 2005. +(c) Copyright Michael Glassford 2004. +(c) Copyright Rani Sharoni 2003-2005. +(c) Copyright Yuriy Krasnoschek 2009. +Copyright (c) 1991-2009 Unicode, Inc. +Copyright (c) 2001-2003 Daniel Nuffer +Copyright (c) 2002 Raghavendra Satish +Copyright (c) 2002-2003 Eric Friedman +Copyright (c) 2003-2004 Gennaro Prota +Copyright (c) 2004 Kristopher Beevers +Copyright (c) 2005, 2014 Eric Niebler +Copyright (c) 2005-2006 Joao Abecasis +Copyright (c) 2005-2008 Daniel James. +Copyright (c) 2005-2011 Daniel James. +Copyright (c) 2006, Stephan Diederich +Copyright (c) 2007, 2013 John Maddock +Copyright (c) 2007, Tobias Schwinger. +Copyright (c) 2007-8 Anthony Williams +Copyright (c) 2007-9 Anthony Williams +Copyright (c) 2008-2011 Daniel James. +Copyright (c) 2008-2013 Tim Blechmann +Copyright (c) 2008-2016 Daniel James. +Copyright (c) 2008-2016 Tim Blechmann +Copyright (c) 2009-2011 Artyom Beilis +Copyright (c) 2009-2013 Tim Blechmann +Copyright (c) 2010-2011 Bryce Lelbach +Copyright (c) 2010-2011 Thomas Heller +Copyright (c) 2010-2011 Tim Blechmann +Copyright (c) 2011 Jan Frederick Eick +Copyright (c) 2011-2013 Andrew Hundt. +Copyright (c) 2013-2014 Agustin Berge +Copyright (c) 2013-2014 Ion Gaztanaga +Copyright (c) 2014-2015 John Fletcher +Copyright (c) Intel Corporation 2008. +Copyright 1999-2003 Aleksey Gurtovoy. +Copyright 2007-2008 Christian Henning +Copyright 2008 Joaquin M Lopez Munoz. +Copyright 2016 Joaquin M Lopez Munoz. +Copyright 2016 Klemens D. Morgenstern +Copyright 2017 Joaquin M Lopez Munoz. +Copyright 2017 Valentin Noah Hartmann +Copyright 2018 Joaquin M Lopez Munoz. +Copyright Andrii Sydorchuk 2010-2012. +Copyright Antony Polukhin, 2011-2019. +Copyright Antony Polukhin, 2013-2014. +Copyright Antony Polukhin, 2013-2019. +Copyright Antony Polukhin, 2016-2019. +Copyright Beman Dawes 1994-2007, 2011 +Copyright Beman Dawes 2002-2005, 2009 +Copyright Christopher Kormanyos 2013. +Copyright Christopher Kormanyos 2014. +Copyright Matthew Pulver 2018 - 2019. +Copyright Paul A. Bristow 2006, 2007. +Copyright Paul A. Bristow 2008, 2010. +Copyright Paul A. Bristow 2008, 2014. +Copyright Paul A. Bristow 2011, 2012. +Copyright Steven J. Ross 2001 - 2009. +Copyright Steven J. Ross 2001 - 2014. +Copyright Thorsten Ottosen 2003-2004. +Copyright Thorsten Ottosen 2003-2005. +Copyright Thorsten Ottosen 2003-2006. +Copyright Thorsten Ottosen 2003-2007. +Copyright Thorsten Ottosen 2003-2008. +copyright Gonzalo Brito Gadeschi 2015 +(c) Copyright 2007-10 Anthony Williams +(c) Copyright 2008-10 Anthony Williams +(c) Copyright 2009-2011 Frederic Bron. +(c) Copyright Beman Dawes 2001 - 2003. +(c) Copyright Beman Dawes 2002 - 2003. +(c) Copyright Darin Adler 2001 - 2002. +(c) Copyright Daryle Walker 2000-2001. +(c) Copyright Daryle Walker 2001-2002. +(c) Copyright Edward Diener 2011,2013. +(c) Copyright Edward Diener 2011,2014. +(c) Copyright Edward Diener 2014,2019. +(c) Copyright Eric Friedman 2002-2003. +(c) Copyright Ion Gaztanaga 2004-2015. +(c) Copyright Ion Gaztanaga 2005-2012. +(c) Copyright Ion Gaztanaga 2005-2013. +(c) Copyright Ion Gaztanaga 2005-2014. +(c) Copyright Ion Gaztanaga 2005-2015. +(c) Copyright Ion Gaztanaga 2005-2016. +(c) Copyright Ion Gaztanaga 2006-2012. +(c) Copyright Ion Gaztanaga 2006-2013. +(c) Copyright Ion Gaztanaga 2006-2014. +(c) Copyright Ion Gaztanaga 2007-2012. +(c) Copyright Ion Gaztanaga 2007-2013. +(c) Copyright Ion Gaztanaga 2007-2014. +(c) Copyright Ion Gaztanaga 2008-2012. +(c) Copyright Ion Gaztanaga 2008-2013. +(c) Copyright Ion Gaztanaga 2008-2015. +(c) Copyright Ion Gaztanaga 2009-2012. +(c) Copyright Ion Gaztanaga 2009-2013. +(c) Copyright Ion Gaztanaga 2010-2012. +(c) Copyright Ion Gaztanaga 2010-2016. +(c) Copyright Ion Gaztanaga 2011-2012. +(c) Copyright Ion Gaztanaga 2011-2013. +(c) Copyright Ion Gaztanaga 2011-2014. +(c) Copyright Ion Gaztanaga 2012-2012. +(c) Copyright Ion Gaztanaga 2012-2013. +(c) Copyright Ion Gaztanaga 2012-2015. +(c) Copyright Ion Gaztanaga 2012-2016. +(c) Copyright Ion Gaztanaga 2013-2013. +(c) Copyright Ion Gaztanaga 2014-2014. +(c) Copyright Ion Gaztanaga 2014-2015. +(c) Copyright Ion Gaztanaga 2014-2017. +(c) Copyright Ion Gaztanaga 2015-2015. +(c) Copyright Ion Gaztanaga 2015-2016. +(c) Copyright Ion Gaztanaga 2015-2017. +(c) Copyright Ion Gaztanaga 2016-2016. +(c) Copyright Ion Gaztanaga 2017-2017. +(c) Copyright Ion Gaztanaga 2017-2018. +(c) Copyright Ion Gaztanaga 2018-2018. +(c) Copyright Jens Maurer 2001 - 2002. +(c) Copyright Jens Maurer 2001 - 2003. +(c) Copyright Jens Maurer 2002 - 2003. +(c) Copyright Toon Knapen 2001 - 2003. +(c) Copyright Vicente J. Botet Escriba +Copyright (c) 1998-2003 Joel de Guzman +Copyright (c) 1998-2008 Joel de Guzman +Copyright (c) 2001-2002 Joel de Guzman +Copyright (c) 2001-2003 Hartmut Kaiser +Copyright (c) 2001-2003 Joel de Guzman +Copyright (c) 2001-2007 Hartmut Kaiser +Copyright (c) 2001-2007 Joel de Guzman +Copyright (c) 2001-2008 Hartmut Kaiser +Copyright (c) 2001-2008 Joel de Guzman +Copyright (c) 2001-2009 Joel de Guzman +Copyright (c) 2001-2010 Hartmut Kaiser +Copyright (c) 2001-2010 Joel de Guzman +Copyright (c) 2001-2011 Joel de Guzman +Copyright (c) 2001-2011 Thomas Bernard +Copyright (c) 2001-2012 Joel de Guzman +Copyright (c) 2001-2013 Joel de Guzman +Copyright (c) 2001-2014 Joel de Guzman +Copyright (c) 2001-2015 Joel de Guzman +Copyright (c) 2001-2019 Joel de Guzman +Copyright (c) 2002-2003 David Abrahams +Copyright (c) 2002-2003 Hartmut Kaiser +Copyright (c) 2002-2003 Joel de Guzman +Copyright (c) 2002-2006 Hartmut Kaiser +Copyright (c) 2004 Jonathan Brandmeyer +Copyright (c) 2005-2006 Alain Miniussi +Copyright (c) 2005-2006 Douglas Gregor +Copyright (c) 2005-2008 Hartmut Kaiser +Copyright (c) 2005-2010 Joel de Guzman +Copyright (c) 2005-2011 Joel de Guzman +Copyright (c) 2005-2012 Joel de Guzman +Copyright (c) 2005-2013 Joel de Guzman +Copyright (c) 2007-2011 Hartmut Kaiser +Copyright (c) 2008, 2016 Tim Blechmann +Copyright (c) 2008-2011 Hartmut Kaiser +Copyright (c) 2009 Christopher Schmidt +Copyright (c) 2009, 2011 Helge Bahmann +Copyright (c) 2009, 2016 Tim Blechmann +Copyright (c) 2009-2010 Hartmut Kaiser +Copyright (c) 2010 Christopher Schmidt +Copyright (c) 2011, 2016 Tim Blechmann +Copyright (c) 2011-2012 ! Brandon Kohn +Copyright (c) 2011-2012 Thomas Bernard +Copyright (c) 2014 Riccardo Marcangelo +Copyright (c) Christopher Diggins 2005 +Copyright (c) Marshall Clow 2008-2012. +Copyright (c) Marshall Clow 2010-2012. +Copyright (c) Marshall Clow 2011-2012. +Copyright (c) Marshall Clow 2012-2012. +Copyright (c) Marshall Clow 2012-2015. +Copyright 2002, 2009, 2014 Peter Dimov +Copyright 2007 University of Karlsruhe +Copyright Andrey Semashev 2007 - 2013. +Copyright Andrey Semashev 2007 - 2014. +Copyright Andrey Semashev 2007 - 2015. +Copyright Andrey Semashev 2007 - 2016. +Copyright Beman Dawes 1994, 2006, 2008 +Copyright Beman Dawes 2003, 2006, 2008 +Copyright Beman Dawes 2003, 2006, 2010 +Copyright Beman Dawes 2003, 2006, 2011 +Copyright Beman Dawes 2010, 2011, 2014 +(c) Copyright 2005-2006 Matthias Troyer +(c) Copyright 2005-2007 Matthias Troyer +(c) Copyright Guillaume Melquiond 2003. +(c) Copyright Howard Hinnant 2007-2010. +(c) Copyright John Maddock 2001 - 2002. +(c) Copyright John Maddock 2001 - 2003. +(c) Copyright John Maddock 2002 - 2003. +(c) Copyright Nicolai M. Josuttis 2001. +(c) Copyright Olaf Krzikalla 2004-2006. +Copyright (c) 1998-2000 Dr John Maddock +Copyright (c) 2000, 2001 Stephen Cleary +Copyright (c) 2001-2009, Hartmut Kaiser +Copyright (c) 2001-2011 Hartmut Kaiser. +Copyright (c) 2001-2012 Hartmut Kaiser. +Copyright (c) 2001-2013 Hartmut Kaiser. +Copyright (c) 2007-2008 Steven Watanabe +Copyright (c) 2007-2009 Steven Watanabe +Copyright (c) 2007-2010 Steven Watanabe +Copyright (c) 2008-2009 Frank Mori Hess +Copyright (c) 2009-2010, Marco Guazzone +Copyright (c) 2009-2012, Marco Guazzone +Copyright (c) 2009-2016 Vladimir Batov. +Copyright (c) 2011-2015 Akira Takahashi +Copyright (c) 2011-2019 Antony Polukhin +Copyright (c) 2012 Pieter Bastiaan Ober +Copyright (c) 2012-2014 Kohei Takahashi +Copyright (c) 2013-2014 Andrey Semashev +Copyright (c) 2014 Pieter Bastiaan Ober +Copyright (c) 2014,2018 Kohei Takahashi +Copyright (c) 2014-2015 Kohei Takahashi +Copyright (c) 2014-2019 Antony Polukhin +Copyright (c) 2015 Andrzej Krzemienski. +Copyright (c) 2015-2019 Antony Polukhin +Copyright (c) 2016 Andrzej Krzemienski. +Copyright (c) 2016-2019 Antony Polukhin +Copyright (c) 2017 Andrzej Krzemienski. +Copyright (c) 2018-2019 Antony Polukhin +Copyright 2002-2003 Guillaume Melquiond +Copyright 2009 Vicente J. Botet Escriba +Copyright 2010 Vicente J. Botet Escriba +Copyright 2011 Vicente J. Botet Escriba +Copyright 2012 Vicente J. Botet Escriba +Copyright 2015, 2017, 2019 Peter Dimov. +Copyright 2016, 2018, 2019 Peter Dimov. +Copyright Alexander Nasonov, 2006-2010. +Copyright Christopher Kormanyos 2013-14 +Copyright John Maddock 2005-2006, 2011. +Copyright John Maddock 2006-7, 2013-14. +Copyright Vicente J. Botet Escriba 2009 +Copyright Vicente J. Botet Escriba 2010 +(c) Copyright 2007-2010 Anthony Williams +(c) Copyright 2009-2012 Anthony Williams +(c) Copyright Boris Gubenko 2006 - 2007. +(c) Copyright Gennaro Prota 2003 - 2004. +(c) Copyright Microsoft Corporation 2014 +(c) Copyright Paul Mensonides 2002-2011. +Copyright (arg) 2001-2014 Joel de Guzman +Copyright (c) 2001-2003 William E. Kempf +Copyright (c) 2004-2008 Rene Nyffenegger +Copyright (c) 2005, 2006 Douglas Gregor. +Copyright (c) 2006-2007 Matias Capeletto +Copyright (c) 2006-2007 Tobias Schwinger +Copyright (c) 2007-2008 Tobias Schwinger +Copyright (c) 2008-2018 Lorenzo Caminiti +Copyright (c) 2008-2019 Lorenzo Caminiti +Copyright (c) 2009-2012 Lorenzo Caminiti +Copyright (c) 2010 Athanasios Iliopoulos +Copyright (c) 2011 Christopher Jefferson +Copyright (c) 2012-2019 Antony Polukhin. +Copyright (c) 2013 Christopher Kormanyos +Copyright (c) 2013-2019 Antony Polukhin. +Copyright (c) 2014, 2019 Andrey Semashev +Copyright (c) 2014, Andrzej Krzemienski. +Copyright (c) 2015 Agustin K-ballo Berge +Copyright (c) 2016-2018 T. Zachary Laine +Copyright (c) Microsoft Corporation 2014 +Copyright 2000 University of Notre Dame. +Copyright 2001 University of Notre Dame. +Copyright 2002-2006 Andreas Huber Doenni +Copyright 2002-2007 Andreas Huber Doenni +Copyright 2002-2008 Andreas Huber Doenni +Copyright 2002-2010 Andreas Huber Doenni +Copyright 2005-2006 Andreas Huber Doenni +Copyright 2005-2008 Andreas Huber Doenni +Copyright 2012-2013 Andreas Angelopoulos +Copyright Paul A. Bristow 2007, 2013-14. +Copyright Ralf W. Grosse-Kunstleve 2006. +Copyright Vicente J. Botet Escriba 2012. +(c) Copyright 2003-2007 Jonathan Turkanis +(c) Copyright 2004-2007 Jonathan Turkanis +(c) Copyright 2005-2007 Jonathan Turkanis +(c) Copyright Christopher Jefferson 2011. +(c) Copyright David Abrahams 2001 - 2002. +(c) Copyright David Abrahams 2002 - 2003. +(c) Copyright Jeremy William Murphy 2015. +(c) Copyright Jeremy William Murphy 2016. +(c) Copyright R.W. Grosse-Kunstleve 2002. +(c) Copyright Thorsten Ottosen 2002-2003. +CNRS/Univ. Clermont II Copyright 2014 LRI +Copyright (c) 1999-2003 Jeremiah Willcock +Copyright (c) 2001-2009, 2012 Peter Dimov +Copyright (c) 2002 by Andrei Alexandrescu +Copyright (c) 2002-2006 Marcin Kalicinski +Copyright (c) 2002-2007 Marcin Kalicinski +Copyright (c) 2004, 2005 Arkadiy Vertleyb +Copyright (c) 2007-2009 Joachim Faulhaber +Copyright (c) 2007-2010 Joachim Faulhaber +Copyright (c) 2007-2011 Joachim Faulhaber +Copyright (c) 2007-2012 Joachim Faulhaber +Copyright (c) 2008 Federico J. Fernandez. +Copyright (c) 2008-2009 Joachim Faulhaber +Copyright (c) 2008-2010 Joachim Faulhaber +Copyright (c) 2008-2011 Joachim Faulhaber +Copyright (c) 2008-2012 Joachim Faulhaber +Copyright (c) 2008-2012 Simonson Lucanus. +Copyright (c) 2009-2009 Joachim Faulhaber +Copyright (c) 2009-2010 Joachim Faulhaber +Copyright (c) 2009-2011 Joachim Faulhaber +Copyright (c) 2010-2010 Joachim Faulhaber +Copyright (c) 2010-2011 Joachim Faulhaber +Copyright (c) 2011-2011 Joachim Faulhaber +Copyright (c) 2012 - 2014 Andrey Semashev +Copyright (c) 2012-2012 Andrii Sydorchuk. +Copyright (c) 2013 - 2014 Andrey Semashev +Copyright (c) 2013 - 2018 Andrey Semashev +Copyright (c) 2014 - 2018 Andrey Semashev +Copyright (c) 2014, Athanasios Iliopoulos +Copyright (c) 2016 Klemens D. Morgenstern +Copyright (c) 2017 - 2018 Andrey Semashev +Copyright (c) 2017 Klemens D. Morgenstern +Copyright (c) 2018 Klemens D. Morgenstern +Copyright (c) 2019 Klemens D. Morgenstern +Copyright 2001, 2004, 2011 Daryle Walker. +Copyright 2006 Michael van der Westhuizen +Copyright 2008 Adobe Systems Incorporated +Copyright 2010-2012, D. E. Shaw Research. +Copyright Gottfried Ganssauge 2003..2006. +copyright (c) 1995-2010 Geodan, Amsterdam +(c) Copyright 2011Vicente J. Botet Escriba +(c) Copyright Beman Dawes 2006, 2009, 2014 +(c) Copyright Edward Diener 2011,2012,2013 +(c) Copyright Edward Diener 2011-2015,2019 +(c) Copyright Jonathan Turkanis 2004-2005. +(c) Copyright Peter Dimov 2001, 2002, 2003 +(c) Copyright Samuli-Petrus Korhonen 2017. +Copyright (c) 1994 Hewlett-Packard Company +Copyright (c) 2000 Cadenza New Zealand Ltd +Copyright (c) 2001 by Andrei Alexandrescu. +Copyright (c) 2001, 2002, 2003 Peter Dimov +Copyright (c) 2001, 2002, 2012 Peter Dimov +Copyright (c) 2002, 2008, 2013 Peter Dimov +Copyright (c) 2002, 2009, 2014 Peter Dimov +Copyright (c) 2003, 2006 Gerald I. Evenden +Copyright (c) 2006, 2009 Marcin Kalicinski +Copyright (c) 2007, 2008, 2012 Peter Dimov +Copyright (c) 2007, 2013, 2015 Peter Dimov +Copyright (c) 2017, 2018 James E. King III +Copyright 2003-2008 Joaquin M Lopez Munoz. +Copyright 2003-2013 Joaquin M Lopez Munoz. +Copyright 2003-2014 Joaquin M Lopez Munoz. +Copyright 2003-2015 Joaquin M Lopez Munoz. +Copyright 2003-2016 Joaquin M Lopez Munoz. +Copyright 2003-2017 Joaquin M Lopez Munoz. +Copyright 2003-2018 Joaquin M Lopez Munoz. +Copyright 2003-2019 Joaquin M Lopez Munoz. +Copyright 2006 Eric Niebler, Olivier Gygi. +Copyright 2006-2008 Joaquin M Lopez Munoz. +Copyright 2006-2009 Joaquin M Lopez Munoz. +Copyright 2006-2011 Joaquin M Lopez Munoz. +Copyright 2006-2013 Joaquin M Lopez Munoz. +Copyright 2006-2014 Joaquin M Lopez Munoz. +Copyright 2006-2015 Joaquin M Lopez Munoz. +Copyright 2006-2018 Joaquin M Lopez Munoz. +Copyright 2006-2019 Joaquin M Lopez Munoz. +Copyright 2015-2018 Klemens D. Morgenstern +Copyright 2016-2017 Joaquin M Lopez Munoz. +Copyright 2016-2018 Joaquin M Lopez Munoz. +Copyright 2016-2019 Joaquin M Lopez Munoz. +Copyright 2017-2018 Joaquin M Lopez Munoz. +Copyright Arno Schoedl & Neil Groves 2009. +Copyright Kevlin Henney, 2000, 2001, 2002. +Portions Copyright (c) 2002 David Abrahams +(c) Copyright 2010 Vicente J. Botet Escriba +(c) Copyright 2011 Vicente J. Botet Escriba +(c) Copyright 2012 Vicente J. Botet Escriba +(c) Copyright 2013 Vicente J. Botet Escriba +(c) Copyright 2014 Vicente J. Botet Escriba +(c) Copyright Aleksey Gurtovoy 2002 - 2003. +Copyright (c) 2003-2004, 2008 Gennaro Prota +Copyright (c) 2003-2006, 2008 Gennaro Prota +Copyright (c) 2009-2010 Christopher Schmidt +Copyright (c) 2009-2011 Christopher Schmidt +Copyright (c) 2010-2011 Christopher Schmidt +Copyright (c) 2011 Vicente J. Botet Escriba +Copyright (c) 2011-2013, 2016 Tim Blechmann +Copyright (c) 2012 Vicente J. Botet Escriba +Copyright (c) 2013 Vicente J. Botet Escriba +Copyright (c) 2014 Vicente J. Botet Escriba +Copyright (c) 2015 Vicente J. Botet Escriba +Copyright (c) 2017 Vicente J. Botet Escriba +Copyright 2002 Brad King and Douglas Gregor +Copyright 2005 Daniel Egloff, Eric Niebler. +Copyright 2005 Daniel Egloff, Olivier Gygi. +Copyright 2005 Eric Niebler, Daniel Egloff. +Copyright 2006 Daniel Egloff, Olivier Gygi. +Copyright 2006 Olivier Gygi, Daniel Egloff. +Copyright 2006, Eric Niebler, Olivier Gygi. +Copyright 2010 Daniel Wallin, Eric Niebler. +Copyright Paul A. Bristow 2006, 2007, 2012. +Copyright Paul A. Bristow 2006, 2012, 2017. +Copyright Paul A. Bristow 2016, 2017, 2018. +(c) Copyright Eric Ford & Hubert Holin 2001. +(c) Copyright Eric Ford 2001 & Hubert Holin. +(c) Copyright Markus Schoepflin 2002 - 2003. +(c) Copyright Vicente J. Botet Escriba 2010. +(c) Copyright Vicente J. Botet Escriba 2014. +Copyright (c) 2002 Eric Friedman, Itay Maman +Copyright (c) 2002 Juan Carlos Arevalo-Baeza +Copyright (c) 2003 Eric Friedman, Itay Maman +Copyright (c) 2008, 2009, 2016 Tim Blechmann +Copyright (c) 2012 Barend Gehrels, Amsterdam +Copyright (c) 2013 Barend Gehrels, Amsterdam +Copyright (c) 2014 Barend Gehrels, Amsterdam +Copyright (c) 2014,2015,2018 Kohei Takahashi +Copyright (c) 2014-2016 Andrzej Krzemienski. +Copyright (c) 2015 Barend Gehrels, Amsterdam +Copyright (c) 2015-2018 Andrzej Krzemienski. +Copyright (c) 2017 Barend Gehrels, Amsterdam +Copyright (c) 2019 Barend Gehrels, Amsterdam +Copyright 2009-2010 Vicente J. Botet Escriba +Copyright 2009-2011 Vicente J. Botet Escriba +Copyright 2009-2012 Vicente J. Botet Escriba +Copyright 2012 (c) Jeffrey Lee Hellrung, Jr. +Copyright Christopher Kormanyos 2002 - 2011. +Copyright Christopher Kormanyos 2002 - 2013. +Copyright Vicente J. Botet Escriba 2009-2011 +(c) Copyright Joaquin M Lopez Munoz 2006-2013 +Copyright (c) 2006 Michael van der Westhuizen +Copyright (c) 2014, 2015 Andrzej Krzemienski. +Copyright 1997-2001 University of Notre Dame. +Copyright 2000 Jeremy Siek (jsiek@lsc.nd.edu) +Copyright 2005 Trustees of Indiana University +Copyright 2006 Trustees of Indiana University +Copyright Beman Dawes and Daryle Walker 1999. +Copyright Daniel Wallin, David Abrahams 2005. +Copyright Daniel Wallin, David Abrahams 2010. +Copyright David Abrahams, Daniel Wallin 2003. +Copyright David Abrahams, Daniel Wallin 2005. +Copyright Thorsten Ottosen, Neil Groves 2006. +(c) Copyright Guillaume Melquiond 2002 - 2003. +Copyright (c) 2004 CrystalClear Software, Inc. +Copyright (c) 2005 CrystalClear Software, Inc. +Copyright (c) 2006 CrystalClear Software, Inc. +Copyright (c) 2006, 2007 Julio M. Merino Vidal +Copyright (c) 2011 Jeff Flinn, Boris Schaeling +Copyright (c) 2012 Mateusz Loskot, London, UK. +Copyright (c) 2013 Mateusz Loskot, London, UK. +Copyright (c) 2014 - 2018 Andrzej Krzemienski. +Copyright (c) 2014 Mateusz Loskot, London, UK. +Copyright (c) 2015 - 2017 Andrzej Krzemienski. +Copyright (c) 2016 Modified Work Barrett Adair +Copyright 2005 Eric Niebler, Michael Gauckler. +Copyright 2005-2007 Adobe Systems Incorporated +Copyright 2009 Trustees of Indiana University. +Copyright 2011 Garmin Ltd. or its subsidiaries +Copyright 2012 Chung-Lin Wen, Davide Anastasia +Copyright David Abrahams and Jeremy Siek 2003. +Copyright John Maddock 2006, 2007, 2012, 2014. +Copyright Peter Dimov and David Abrahams 2002. +Copyright (c) 1995 Maarten Hilferink, Amsterdam +Copyright (c) 2002 Brad King and Douglas Gregor +Copyright (c) 2003 Gunter Winkler, Joerg Walter +Copyright (c) 2003-2011 Christopher M. Kohlhoff +Copyright (c) 2003-2019 Christopher M. Kohlhoff +Copyright (c) 2005-2019 Christopher M. Kohlhoff +Copyright (c) 2006-2009, 2012 Alexander Nasonov +Copyright (c) 2012 - 2014, 2017 Andrey Semashev +Copyright (c) 2013 Tim Blechmann Linux-specific +Copyright 2001, 2003, 2004, 2012 Daryle Walker. +Copyright 2002 Rensselaer Polytechnic Institute +Copyright 2004-9 Trustees of Indiana University +Copyright 2010 Fabien Castan, Christian Henning +(c) Copyright 2004 Robert Ramey and Martin Ecker +(c) Copyright 2009-2012 Vicente J. Botet Escriba +(c) Copyright 2010-2011 Vicente J. Botet Escriba +(c) Copyright 2011-2012 Vicente J. Botet Escriba +(c) Copyright 2011-2013 Vicente J. Botet Escriba +(c) Copyright 2011-2015 Vicente J. Botet Escriba +(c) Copyright 2013,2014 Vicente J. Botet Escriba +(c) Copyright 2013,2015 Vicente J. Botet Escriba +(c) Copyright Daniel Frey and Robert Ramey 2009. +(c) Copyright Eric Jourdanneau, Joel Falcou 2010 +CNRS/Univ. Clermont II Copyright 2009 - 2011 LRI +Copyright (c) 2001, Thomas Flemming, tf@ttqv.com +Copyright (c) 2005 Arkadiy Vertleyb, Peder Holt. +Copyright (c) 2008 Ilya Sokolov, Boris Schaeling +Copyright (c) 2009, Spirent Communications, Inc. +Copyright (c) 2010 Eric Jourdanneau, Joel Falcou +Copyright (c) 2010 Felipe Tanus, Boris Schaeling +Copyright (c) 2011-2012 Vicente J. Botet Escriba +Copyright (c) 2011-2013 Vicente J. Botet Escriba +Copyright (c) 2012 Bruno Lalande, Paris, France. +Copyright (c) 2012-2013 Vicente J. Botet Escriba +Copyright (c) 2013 Bruno Lalande, Paris, France. +Copyright (c) 2013 John Maddock, Antony Polukhin +Copyright (c) 2013,2014 Vicente J. Botet Escriba +Copyright (c) 2013-2014 Vicente J. Botet Escriba +Copyright (c) 2014 Bruno Lalande, Paris, France. +Copyright (c) 2014-2015 Vicente J. Botet Escriba +Copyright (c) 2014-2017 Vicente J. Botet Escriba +Copyright (c) 2015 Oracle and/or its affiliates. +Copyright (c) 2016 Oracle and/or its affiliates. +Copyright (c) 2017 Oracle and/or its affiliates. +Copyright (c) 2018 Oracle and/or its affiliates. +Copyright (c) 2019 Oracle and/or its affiliates. +Copyright 2003 Guillaume Melquiond, Sylvain Pion +Copyright 2010 Gaetano Mendola, 2011 Simon West. +Copyright Justinas Vygintas Daugmaudis 2010-2018 +copyright (c) 2014 Oracle and/or its affiliates. +copyright (c) 2015 Oracle and/or its affiliates. +copyright (c) 2016 Oracle and/or its affiliates. +copyright (c) 2017 Oracle and/or its affiliates. +copyright (c) 2018 Oracle and/or its affiliates. +copyright (c) 2019 Oracle and/or its affiliates. +(c) Copyright David Abrahams, Vicente Botet 2009. +(c) Copyright John Maddock and Steve Cleary 2000. +(c) Copyright Vicente J. Botet Escriba 2013-2014. +(c) Copyright Vicente J. Botet Escriba 2013-2017. +(c) Copyright Vicente J. Botet Escriba 2014-2015. +Copyright (c) 2002-2003 Eric Friedman, Itay Maman +Copyright (c) 2003-2004 Jeremy B. Maitin-Shepard. +Copyright (c) 2006 Trustees of Indiana University +Copyright (c) 2007 Trustees of Indiana University +Copyright (c) 2007-2011 Barend Gehrels, Amsterdam +Copyright (c) 2007-2012 Barend Gehrels, Amsterdam +Copyright (c) 2007-2013 Barend Gehrels, Amsterdam +Copyright (c) 2007-2014 Barend Gehrels, Amsterdam +Copyright (c) 2007-2015 Barend Gehrels, Amsterdam +Copyright (c) 2007-2016 Barend Gehrels, Amsterdam +Copyright (c) 2007-2017 Barend Gehrels, Amsterdam +Copyright (c) 2008-2012 Barend Gehrels, Amsterdam +Copyright (c) 2008-2014 Barend Gehrels, Amsterdam +Copyright (c) 2008-2015 Barend Gehrels, Amsterdam +Copyright (c) 2009 Trustees of Indiana University +Copyright (c) 2009-2012 Barend Gehrels, Amsterdam +Copyright (c) 2009-2015 Barend Gehrels, Amsterdam +Copyright (c) 2010-2012 Barend Gehrels, Amsterdam +Copyright (c) 2011-2012 Barend Gehrels, Amsterdam +Copyright (c) 2011-2015 Barend Gehrels, Amsterdam +Copyright (c) 2012-2014 Barend Gehrels, Amsterdam +Copyright (c) 2012-2015 Barend Gehrels, Amsterdam +Copyright (c) 2012-2019 Barend Gehrels, Amsterdam +Copyright (c) 2013 Adam Wulkiewicz, Lodz, Poland. +Copyright (c) 2014 Adam Wulkiewicz, Lodz, Poland. +Copyright (c) 2014, Oracle and/or its affiliates. +Copyright (c) 2014-2015 Barend Gehrels, Amsterdam +Copyright (c) 2015, Oracle and/or its affiliates. +Copyright (c) 2015-2016 Barend Gehrels, Amsterdam +Copyright (c) 2016, Oracle and/or its affiliates. +Copyright (c) 2017 Adam Wulkiewicz, Lodz, Poland. +Copyright (c) 2017, Oracle and/or its affiliates. +Copyright (c) 2017-2017 Barend Gehrels, Amsterdam +Copyright (c) 2018 Adam Wulkiewicz, Lodz, Poland. +Copyright (c) 2018, Oracle and/or its affiliates. +Copyright (c) 2018-2019 Barend Gehrels, Amsterdam +Copyright (c) 2019, Oracle and/or its affiliates. +Copyright (c) 2019-2019 Barend Gehrels, Amsterdam +Copyright 2003 The Trustees of Indiana University +Copyright 2005 Felix Hofling, Guillaume Melquiond +Copyright 2008 Christian Henning, Lubomir Bourdev +Copyright 2012 Kenneth Riddile, Christian Henning +Copyright Paul A. Bristow 2006, 2007, 2009, 2010. +Copyright Paul A. Bristow 2007, 2010, 2012, 2014. +copyright (c) 2013, Oracle and/or its affiliates. +copyright (c) 2014, Oracle and/or its affiliates. +copyright (c) 2015, Oracle and/or its affiliates. +copyright (c) 2016, Oracle and/or its affiliates. +copyright (c) 2017, Oracle and/or its affiliates. +copyright (c) 2018, Oracle and/or its affiliates. +Copyright (c) 2000-2002 Joerg Walter, Mathias Koch +Copyright (c) 2000-2004 Joerg Walter, Mathias Koch +Copyright (c) 2001 Vladimir Prus +Copyright (c) 2003-2008 Matthias Christian Schabel +Copyright (c) 2003-2009 Matthias Christian Schabel +Copyright 2002 The Trustees of Indiana University. +Copyright 2004 The Trustees of Indiana University. +Copyright 2005 The Trustees of Indiana University. +Copyright 2006 The Trustees of Indiana University. +Copyright 2009 The Trustees of Indiana University. +Copyright 2010 The Trustees of Indiana University. +Copyright 2012 Fernando Vilas 2010 Daniel Trebbien +Copyright 2012 The Trustees of Indiana University. +Copyright 2018 Mateusz Loskot +Copyright Abel Sinkovics (abel@sinkovics.hu) 2010. +Copyright Abel Sinkovics (abel@sinkovics.hu) 2011. +Copyright Abel Sinkovics (abel@sinkovics.hu) 2012. +Copyright Abel Sinkovics (abel@sinkovics.hu) 2013. +Copyright Abel Sinkovics (abel@sinkovics.hu) 2014. +Copyright Abel Sinkovics (abel@sinkovics.hu) 2015. +Copyright Abel Sinkovics (abel@sinkovics.hu) 2016. +Copyright Abel Sinkovics (abel@sinkovics.hu) 2017. +Copyright Abel Sinkovics (abel@sinkovics.hu) 2018. +(c) Copyright Dave Abrahams and Daryle Walker 2001. +(c) Copyright Jeremy Siek and John R. Bandela 2001. +(c) Copyright John Maddock & Thorsten Ottosen 2005. +(c) Copyright Kevlin Henney and Dave Abrahams 1999. +Copyright (c) 2000 Gary Powell (powellg@amazon.com) +Copyright (c) 2001 Peter Dimov and Multi Media Ltd. +Copyright (c) 2001, 2002 Python Software Foundation +Copyright (c) 2001-2007 Hartmut Kaiser Revised 2007 +Copyright (c) 2002 Peter Dimov and Multi Media Ltd. +Copyright (c) 2002,2003 CrystalClear Software, Inc. +Copyright (c) 2002-2004 CrystalClear Software, Inc. +Copyright (c) 2002-2005 CrystalClear Software, Inc. +Copyright (c) 2002-2006 CrystalClear Software, Inc. +Copyright (c) 2003-2004 CrystalClear Software, Inc. +Copyright (c) 2003-2005 CrystalClear Software, Inc. +Copyright (c) 2004-2005 CrystalClear Software, Inc. +Copyright (c) 2009-2011 Mateusz Loskot, London, UK. +Copyright (c) 2009-2012 Mateusz Loskot, London, UK. +Copyright (c) 2009-2013 Mateusz Loskot, London, UK. +Copyright (c) 2009-2014 Mateusz Loskot, London, UK. +Copyright (c) 2009-2015 Mateusz Loskot, London, UK. +Copyright (c) 2009-2017 Mateusz Loskot, London, UK. +Copyright (c) 2011-2012 Mateusz Loskot, London, UK. +Copyright (c) 2012-2014 Mateusz Loskot, London, UK. +Copyright (c) 2014-2015 Mateusz Loskot, London, UK. +Copyright 2004, 2005 Trustees of Indiana University +Copyright 2005 David Abrahams and Aleksey Gurtovoy. +Copyright 2012 Olivier Tournaire, Christian Henning +Copyright 2014 Renato Tegon Forti, Antony Polukhin. +Copyright 2016 Klemens Morgenstern, Antony Polukhin +Copyright 2019 Miral Shah +Copyright Alexander Nasonov & Paul A. Bristow 2006. +Copyright David Abrahams and Nikolay Mladenov 2003. +(c) Copyright 2005 Matthias Troyer and Dave Abrahams +Copyright (c) 2011, 2012 Jeff Flinn, Boris Schaeling +Copyright (c) 2013 Kyle Lutz +Copyright (c) 2015 Jakub Pola +Copyright (c) 2015 Jakub Szuppe +Copyright (c) 2016 Jakub Szuppe +Copyright (c) 2018 Adeel Ahmad, Islamabad, Pakistan. +Copyright (c) 2018 Jakub Szuppe +Copyright (c) 2018, Cem Bassoy, cem.bassoy@gmail.com +Copyright 2000 John Maddock (john@johnmaddock.co.uk) +Copyright 2004-5 The Trustees of Indiana University. +Copyright 2013 Christian Henning and Juan V. Puertos +Copyright David Abrahams 2002, Joel de Guzman, 2002. +Copyright Peter Dimov and Multi Media Ltd 2001, 2002 +Copyright Thorsten Ottosen, Neil Groves 2006 - 2008. +(c) Copyright 2003-4 Pavel Vozenilek and Robert Ramey +(c) Copyright 2008-2009,2012 Vicente J. Botet Escriba +(c) Copyright 2011,2012,2015 Vicente J. Botet Escriba +(c) Copyright 2011-2012,2015 Vicente J. Botet Escriba +(c) Copyright Greg Colvin and Beman Dawes 1998, 1999. +Copyright (c) 2000 Gary Powell (gwpowell@hotmail.com) +Copyright (c) 2001 Jeremy Siek +Copyright (c) 2001-2002 Chuck Allison and Jeremy Siek +Copyright (c) 2002 Gary Powell (gwpowell@hotmail.com) +Copyright (c) 2002-2003 David Moore, William E. Kempf +Copyright (c) 2003, Fernando Luis Cacciola Carballal. +Copyright (c) 2005, Fernando Luis Cacciola Carballal. +Copyright (c) 2006 Xiaogang Zhang, 2015 John Maddock. +Copyright (c) 2007 Douglas Gregor and Matthias Troyer +Copyright (c) 2008-2011 Bruno Lalande, Paris, France. +Copyright (c) 2008-2012 Bruno Lalande, Paris, France. +Copyright (c) 2008-2013 Bruno Lalande, Paris, France. +Copyright (c) 2008-2014 Bruno Lalande, Paris, France. +Copyright (c) 2008-2015 Bruno Lalande, Paris, France. +Copyright (c) 2008-2017 Bruno Lalande, Paris, France. +Copyright (c) 2011-2012 Bruno Lalande, Paris, France. +Copyright (c) 2012-2014 Bruno Lalande, Paris, France. +Copyright (c) 2014 Samuel Debionne, Grenoble, France. +Copyright (c) 2014-2015 Bruno Lalande, Paris, France. +Copyright (c) 2014-2016 Oracle and/or its affiliates. +Copyright (c) 2014-2018 Oracle and/or its affiliates. +Copyright (c) 2014-2019 Oracle and/or its affiliates. +Copyright (c) 2015-2016 Oracle and/or its affiliates. +Copyright (c) 2015-2017 Oracle and/or its affiliates. +Copyright (c) 2015-2018 Oracle and/or its affiliates. +Copyright (c) 2016-2017 Oracle and/or its affiliates. +Copyright (c) 2016-2018 Oracle and/or its affiliates. +Copyright (c) 2016-2019 Oracle and/or its affiliates. +Copyright (c) 2017-2018 Oracle and/or its affiliates. +Copyright (c) 2017-2019 Oracle and/or its affiliates. +Copyright (c) 2018-2019 Oracle and/or its affiliates. +Copyright (c) Alexander Zaitsev +Copyright David Abrahams 2002, Nikolay Mladenov 2007. +Copyright David Abrahams and Thomas Becker 2000-2006. +copyright (c) 2013-2017 Oracle and/or its affiliates. +copyright (c) 2013-2018 Oracle and/or its affiliates. +copyright (c) 2013-2019 Oracle and/or its affiliates. +copyright (c) 2014-2015 Oracle and/or its affiliates. +copyright (c) 2014-2017 Oracle and/or its affiliates. +copyright (c) 2014-2018 Oracle and/or its affiliates. +copyright (c) 2014-2019 Oracle and/or its affiliates. +copyright (c) 2015-2016 Oracle and/or its affiliates. +copyright (c) 2015-2017 Oracle and/or its affiliates. +copyright (c) 2015-2018 Oracle and/or its affiliates. +copyright (c) 2015-2019 Oracle and/or its affiliates. +copyright (c) 2016-2018 Oracle and/or its affiliates. +copyright (c) 2016-2019 Oracle and/or its affiliates. +copyright (c) 2017-2018 Oracle and/or its affiliates. +copyright (c) 2017-2019 Oracle and/or its affiliates. +(c) Copyright Vicente J. Botet Escriba 2008-2009,2012. +Copyright (c) 2004 The Trustees of Indiana University. +Copyright (c) 2006 The Trustees of Indiana University. +Copyright (c) 2007 The Trustees of Indiana University. +Copyright (c) 2011-2013 Adam Wulkiewicz, Lodz, Poland. +Copyright (c) 2011-2014 Adam Wulkiewicz, Lodz, Poland. +Copyright (c) 2011-2015 Adam Wulkiewicz, Lodz, Poland. +Copyright (c) 2011-2016 Adam Wulkiewicz, Lodz, Poland. +Copyright (c) 2011-2017 Adam Wulkiewicz, Lodz, Poland. +Copyright (c) 2011-2018 Adam Wulkiewicz, Lodz, Poland. +Copyright (c) 2011-2019 Adam Wulkiewicz, Lodz, Poland. +Copyright (c) 2012-2013 Adam Wulkiewicz, Lodz, Poland. +Copyright (c) 2012-2015 Adam Wulkiewicz, Lodz, Poland. +Copyright (c) 2013-2014 Adam Wulkiewicz, Lodz, Poland. +Copyright (c) 2013-2015 Adam Wulkiewicz, Lodz, Poland. +Copyright (c) 2013-2017 Adam Wulkiewicz, Lodz, Poland. +Copyright (c) 2014-2015 Adam Wulkiewicz, Lodz, Poland. +Copyright (c) 2014-2015, Oracle and/or its affiliates. +Copyright (c) 2014-2017 Adam Wulkiewicz, Lodz, Poland. +Copyright (c) 2014-2017, Oracle and/or its affiliates. +Copyright (c) 2014-2018 Adam Wulkiewicz, Lodz, Poland. +Copyright (c) 2014-2018, Oracle and/or its affiliates. +Copyright (c) 2014-2019, Oracle and/or its affiliates. +Copyright (c) 2015-2017, Oracle and/or its affiliates. +Copyright (c) 2015-2018, Oracle and/or its affiliates. +Copyright (c) 2015-2019, Oracle and/or its affiliates. +Copyright (c) 2016, 2018 Oracle and/or its affiliates. +Copyright (c) 2016-2017, Oracle and/or its affiliates. +Copyright (c) 2016-2018, Oracle and/or its affiliates. +Copyright (c) 2016-2019, Oracle and/or its affiliates. +Copyright (c) 2017, 2019 Oracle and/or its affiliates. +Copyright (c) 2017-2018, Oracle and/or its affiliates. +Copyright (c) 2017-2019, Oracle and/or its affiliates. +Copyright (c) 2018, 2019 Oracle and/or its affiliates. +Copyright (c) 2018-2019, Oracle and/or its affiliates. +Copyright (c) Alexander Zaitsev +Copyright (c) Jeremy Siek 2001, Marc Wintermantel 2002 +Copyright 2007-2008 Andreas Pokorny, Christian Henning +Copyright 2007-2008 Christian Henning, Andreas Pokorny +Copyright 2007-2012 Christian Henning, Andreas Pokorny +Copyright 2007-2012 Christian Henning, Lubomir Bourdev +Copyright 2010-2012 Kenneth Riddile, Christian Henning +copyright (c) 2013, 2014 Oracle and/or its affiliates. +copyright (c) 2013-2014, Oracle and/or its affiliates. +copyright (c) 2013-2015, Oracle and/or its affiliates. +copyright (c) 2013-2017, Oracle and/or its affiliates. +copyright (c) 2013-2018, Oracle and/or its affiliates. +copyright (c) 2013-2019, Oracle and/or its affiliates. +copyright (c) 2014, 2018 Oracle and/or its affiliates. +copyright (c) 2014-2015, Oracle and/or its affiliates. +copyright (c) 2014-2017, Oracle and/or its affiliates. +copyright (c) 2014-2018, Oracle and/or its affiliates. +copyright (c) 2014-2019, Oracle and/or its affiliates. +copyright (c) 2015-2016, Oracle and/or its affiliates. +copyright (c) 2015-2017, Oracle and/or its affiliates. +copyright (c) 2015-2018, Oracle and/or its affiliates. +copyright (c) 2015-2019, Oracle and/or its affiliates. +copyright (c) 2016-2017, Oracle and/or its affiliates. +copyright (c) 2016-2018, Oracle and/or its affiliates. +copyright (c) 2016-2019, Oracle and/or its affiliates. +copyright (c) 2017, 2019 Oracle and/or its affiliates. +copyright (c) 2017-2018, Oracle and/or its affiliates. +copyright (c) 2017-2019, Oracle and/or its affiliates. +copyright (c) 2018, 2019 Oracle and/or its affiliates. +copyright (c) 2018-2019, Oracle and/or its affiliates. +(c) 2019 Niall Douglas +(c) Copyright Beman Dawes and Ullrich Koethe 1995-2001. +(c) Copyright David Abrahams 2001, Howard Hinnant 2001. +(c) Copyright Hubert Holin and Daryle Walker 2001-2002. +Copyright (c) 1995, 2007-2015 Barend Gehrels, Amsterdam +Copyright (c) 1995-2013 Jean-loup Gailly and Mark Adler +Copyright (c) 2000 Gary Powell (gary.powell@sierra.com) +Copyright (c) 2001 Gary Powell (gary.powell@sierra.com) +Copyright (c) 2002 Lars Gullik Bjonnes +Copyright (c) 2011 Boris Schaeling (boris@highscore.de) +Copyright (c) 2014 Roshan +Copyright (c) 2014, 2018, Oracle and/or its affiliates. +Copyright (c) 2014, 2019, Oracle and/or its affiliates. +Copyright (c) 2015 Orson Peters +Copyright (c) 2015, 2018, Oracle and/or its affiliates. +Copyright 2004-2006 The Trustees of Indiana University. +Copyright 2005-2009 The Trustees of Indiana University. +Copyright 2019 Pranam Lashkari +copyright (c) 2013, 2014, Oracle and/or its affiliates. +copyright (c) 2014, 2018, Oracle and/or its affiliates. +copyright (c) 2014, 2019, Oracle and/or its affiliates. +copyright (c) 2015, 2018, Oracle and/or its affiliates. +copyright (c) 2015, 2019, Oracle and/or its affiliates. +copyright (c) 2017, 2019, Oracle and/or its affiliates. +copyright (c) 2018, 2019, Oracle and/or its affiliates. +(c) Copyright Boris Rasin and Antony Polukhin 2014-2019. +(c) Copyright Dave Abrahams and Daniel Walker 1999-2003. +(c) Copyright Fernando Luis Cacciola Carballal 2000-2004 +(c) Copyright Robert Ramey 2003. Jonathan Turkanis 2004. +Copyright (c) 2001 Jaakko Jarvi (jaakko.jarvi@cs.utu.fi) +Copyright (c) 2001-2004 Peter Dimov and Multi Media Ltd. +Copyright (c) 2002 Jaakko Jarvi (jaakko.jarvi@cs.utu.fi) +Copyright (c) 2002,2003,2005 CrystalClear Software, Inc. +Copyright (c) 2002-2003,2005 CrystalClear Software, Inc. +Copyright 2004, 2005 The Trustees of Indiana University. +Copyright 2008 CodeRage, LLC 2004-2007 Jonathan Turkanis +Copyright 2014 Marco Guazzone (marco.guazzone@gmail.com) +Copyright 2014-2015 Renato Tegon Forti, Antony Polukhin. +(c) ACM, 2011. http://doi.acm.org/10.1145/1916461.1916469 +(c) Copyright Daryle Walker and Stephen Cleary 2001-2002. +Copyright (c) 2001, 2002 Peter Dimov and Multi Media Ltd. +Copyright (c) 2002, 2003 Peter Dimov and Multi Media Ltd. +Copyright (c) 2002,2003, 2007 CrystalClear Software, Inc. +Copyright (c) 2007 Douglas Gregor +Copyright (c) 2009 Ben Hanson (http://www.benhanson.net/) +Copyright (c) 2013-2014 Kyle Lutz +Copyright (c) 2013-2015 Kyle Lutz +Copyright (c) 2015 Francisco Jose Tapia fjtapia@gmail.com +Copyright (c) 2016 Francisco Jose Tapia fjtapia@gmail.com +Copyright (c) 2017 Francisco Jose Tapia fjtapia@gmail.com +Copyright (c) 2018 Alain Miniussi +Copyright (c) 2018-2019, Cem Bassoy, cem.bassoy@gmail.com +Copyright 2002 Aleksey Gurtovoy (agurtovoy@meta-comm.com) +Copyright 2014 Glen Joseph Fernandes (glenjofe@gmail.com) +Copyright 2015 Glen Joseph Fernandes (glenjofe@gmail.com) +Copyright 2017 Glen Joseph Fernandes (glenjofe@gmail.com) +Copyright 2018 Glen Joseph Fernandes (glenjofe@gmail.com) +Copyright 2019 Glen Joseph Fernandes (glenjofe@gmail.com) +Copyright Abel Sinkovics (abel@sinkovics.hu) 2009 - 2010. +Copyright Abel Sinkovics (abel@sinkovics.hu) 2009 - 2011. +Copyright Abel Sinkovics (abel@sinkovics.hu) 2009 - 2012. +Copyright Abel Sinkovics (abel@sinkovics.hu) 2010 - 2011. +Copyright Abel Sinkovics (abel@sinkovics.hu) 2011 - 2012. +Copyright Ralf W. Grosse-Kunstleve & David Abrahams 2006. +(c) Copyright 2002-2008, Fernando Luis Cacciola Carballal. +(c) Copyright 2011-2012,2017-2018 Vicente J. Botet Escriba +Copyright (c) 1996 Silicon Graphics Computer Systems, Inc. +Copyright (c) 1998 Silicon Graphics Computer Systems, Inc. +Copyright (c) 2001-2003 Douglas Gregor (gregod@cs.rpi.edu) +Copyright (c) 2003, 2008 Fernando Luis Cacciola Carballal. +Copyright (c) 2011, 2012 Martin Lambers +Copyright (c) 2012 Flavio De Lorenzi (fdlorenzi@gmail.com) +Copyright (c) 2014-2015 Samuel Debionne, Grenoble, France. +Copyright 1997, 1998, 1999, 2000 University of Notre Dame. +Copyright 1999, 2000 Jaakko Jarvi (jaakko.jarvi@cs.utu.fi) +Copyright 2009 (c) Dean Michael Berris +Copyright (c) 2001 Jeremy Siek, Douglas Gregor, Brian Osman +Copyright (c) 2004-2006 The Trustees of Indiana University. +Copyright (c) 2004-2008 The Trustees of Indiana University. +Copyright (c) 2004-2009 The Trustees of Indiana University. +Copyright (c) 2005-2006 The Trustees of Indiana University. +Copyright (c) 2005-2008 The Trustees of Indiana University. +Copyright (c) 2005-2010 The Trustees of Indiana University. +Copyright (c) 2006 Tiago de Paula Peixoto +Copyright (c) 2006-2009 Dmitry Bufistov and Andrey Parfenov +Copyright (c) 2006-2010 The Trustees of Indiana University. +Copyright (c) 2017 Denis Demidov +Copyright 2013 Juan V. Puertos G-Cluster, Christian Henning +(c) 2015-2019 Niall Douglas +(c) 2017-2019 Niall Douglas +(c) 2018-2019 Niall Douglas +Copyright (c) 2001 Housemarque Oy http://www.housemarque.com +Copyright (c) Tobias Schwinger http://spirit.sourceforge.net +Copyright (c) 2000-2003 Brian McNamara and Yannis Smaragdakis +Copyright (c) 2003 Martin Wille http://spirit.sourceforge.net +Copyright (c) 2011 Aaron Graham http://spirit.sourceforge.net +Copyright (c) 2014 Glen Joseph Fernandes (glenjofe@gmail.com) +Copyright (c) 2014, 2018, 2019, Oracle and/or its affiliates. +Copyright (c) 2017 Glen Joseph Fernandes (glenjofe@gmail.com) +Copyright (c) Charles Karney (2008-2017) +Copyright (c) Glen Joseph Fernandes 2019 (glenjofe@gmail.com) +(c) 2018 - 2019 Niall Douglas +(c) Copyright 2002-2008 Robert Ramey and Joaquin M Lopez Munoz +(c) Copyright Runar Undheim, Robert Ramey & John Maddock 2008. +Copyright (c) 1999, 2000 Jaakko Jarvi (jaakko.jarvi@cs.utu.fi) +Copyright (c) 2001 Bruce Florman http://spirit.sourceforge.net +Copyright (c) 2001 Daniel Nuffer http://spirit.sourceforge.net +Copyright (c) 2002 Jeff Westfahl http://spirit.sourceforge.net +Copyright (c) 2003 Giovanni Bajo http://spirit.sourceforge.net +Copyright (c) 2003 Vaclav Vesely http://spirit.sourceforge.net +Copyright (c) 2005-2006 Douglas Gregor +Copyright (c) 2006 Joao Abecasis http://spirit.sourceforge.net +Copyright (c) 2007-2009 Ben Hanson (http://www.benhanson.net/) +Copyright (c) 2008-2009 Ben Hanson (http://www.benhanson.net/) +Copyright (c) 2010 2015 Francisco Jose Tapia fjtapia@gmail.com +Copyright (c) 2010 Bryce Lelbach http://spirit.sourceforge.net +Copyright (c) 2010 Matthias Walter (xammy@xammy.homelinux.net) +Copyright (c) 2011 Bryce Lelbach http://spirit.sourceforge.net +Copyright (c) 2013 Agustin Berge http://spirit.sourceforge.net +Copyright (c) 2017 Kristian Popov +Copyright 2012-2019 Glen Joseph Fernandes (glenjofe@gmail.com) +Copyright 2014,2018 Glen Joseph Fernandes (glenjofe@gmail.com) +Copyright 2014-2015 Glen Joseph Fernandes (glenjofe@gmail.com) +Copyright 2014-2016 Glen Joseph Fernandes (glenjofe@gmail.com) +Copyright 2017-2018 Glen Joseph Fernandes (glenjofe@gmail.com) +Copyright 2017-2019 Glen Joseph Fernandes (glenjofe@gmail.com) +Copyright Daniel Walker, Eric Niebler, Michel Morin 2008-2012. +(c) Copyright Andreas Huber Doenni 2002-2005, Eric Niebler 2006 +(c) Copyright Peter Dimov and Multi Media Ltd. 2001, 2002, 2003 +Copyright (c) 1996,1997 Silicon Graphics Computer Systems, Inc. +Copyright (c) 1996-1998 Silicon Graphics Computer Systems, Inc. +Copyright (c) 2001, 2002, 2003 Peter Dimov and Multi Media Ltd. +Copyright (c) 2002 Hartmut Kaiser http://spirit.sourceforge.net +Copyright (c) 2003 Gustavo Guerra http://spirit.sourceforge.net +Copyright (c) 2003 Hartmut Kaiser http://spirit.sourceforge.net +Copyright (c) 2003 Joel de Guzman http://spirit.sourceforge.net +Copyright (c) 2003 Jonathan de Halleux (dehalleux@pelikhan.com) +Copyright (c) 2009 Francois Barel http://spirit.sourceforge.net +Copyright (c) 2011 Thomas Bernard http://spirit.sourceforge.net +Copyright (c) 2016 Frank Hein, maxence business consulting gmbh +(c) Copyright Mat Marcus, Jesse Jones and Adobe Systems Inc 2001 +Copyright (c) 2000-2010 Joerg Walter, Mathias Koch, David Bellot +Copyright (c) 2000-2011 Joerg Walter, Mathias Koch, David Bellot +Copyright (c) 2000-2013 Joerg Walter, Mathias Koch. David Bellot +Copyright (c) 2003, Hartmut Kaiser http://spirit.sourceforge.net +Copyright (c) 2007 Matthias Troyer +Copyright (c) 2002-2003 Toon Knapen, Kresimir Fresl, Joerg Walter +Copyright (c) 2006 Tobias Schwinger http://spirit.sourceforge.net +Copyright (c) 2006-2008 Emil Dotchevski and Reverge Studios, Inc. +Copyright (c) 2006-2009 Emil Dotchevski and Reverge Studios, Inc. +Copyright (c) 2006-2010 Emil Dotchevski and Reverge Studios, Inc. +Copyright (c) 2006-2013 Emil Dotchevski and Reverge Studios, Inc. +Copyright (c) 2008-2009 Emil Dotchevski and Reverge Studios, Inc. +Copyright (c) 2008-2016 Emil Dotchevski and Reverge Studios, Inc. +Copyright (c) 2008-2017 Emil Dotchevski and Reverge Studios, Inc. +Copyright Neil Groves & Thorsten Ottosen & Pavol Droba 2003-2004. +Copyright (c) 2000-2007 Joerg Walter, Mathias Koch, Gunter Winkler +Copyright (c) 2000-2009 Joerg Walter, Mathias Koch, Gunter Winkler +Copyright (c) 2001, Daniel C. Nuffer http://spirit.sourceforge.net +Copyright (c) 2002-2003 Martin Wille http://spirit.sourceforge.net +Copyright 2002 Herve Bronnimann, Guillaume Melquiond, Sylvain Pion +Copyright 2012 Christian Henning, Andreas Pokorny, Lubomir Bourdev +(c) Copyright David Abrahams, Jeremy Siek, Daryle Walker 1999-2001. +Copyright (c) 2001-2003 Daniel Nuffer http://spirit.sourceforge.net +Copyright (c) 2001-2009 Daniel Nuffer http://spirit.sourceforge.net +Copyright (c) 2002 Raghavendra Satish http://spirit.sourceforge.net +Copyright (c) 2018 Yaghyavardhan Singh Khangarot, Hyderabad, India. +Copyright 2019 Olzhas Zhumabek +Copyright (c) 1998-2002 Joel de Guzman http://spirit.sourceforge.net +Copyright (c) 1998-2003 Joel de Guzman http://spirit.sourceforge.net +Copyright (c) 1999-2006 Cortex Software GmbH, Kantstrasse 57, Berlin +Copyright (c) 2001-2003 Hartmut Kaiser http://spirit.sourceforge.net +Copyright (c) 2001-2003 Joel de Guzman http://spirit.sourceforge.net +Copyright (c) 2001-2007 Hartmut Kaiser http://spirit.sourceforge.net +Copyright (c) 2001-2008 Hartmut Kaiser http://spirit.sourceforge.net +Copyright (c) 2001-2010 Hartmut Kaiser http://spirit.sourceforge.net +Copyright (c) 2001-2011 Hartmut Kaiser http://spirit.sourceforge.net +Copyright (c) 2001-2011 Joel de Guzman http://spirit.sourceforge.net +Copyright (c) 2001-2012 Hartmut Kaiser http://spirit.sourceforge.net +Copyright (c) 2001-2012 Joel de Guzman http://spirit.sourceforge.net +Copyright (c) 2001-2014 Joel de Guzman http://spirit.sourceforge.net +Copyright (c) 2002-2003 Hartmut Kaiser http://spirit.sourceforge.net +Copyright (c) 2002-2006 Hartmut Kaiser http://spirit.sourceforge.net +(c) Copyright 2004-2009 Robert Ramey, Martin Ecker and Takatoshi Kondo +Copyright (c) 2008 Rep Invariant Systems, Inc. (info@repinvariant.com) +(c) Copyright 2007, 2008 Steven Watanabe, Joseph Gauterin, Niels Dekker +Copyright (c) 2007, 2008 Steven Watanabe, Joseph Gauterin, Niels Dekker +Copyright (c) 2015 Muhammad Junaid Muzammil +Copyright 2002-2003 Herve Bronnimann, Guillaume Melquiond, Sylvain Pion +Copyright 2007-2008 Christian Henning, Andreas Pokorny, Lubomir Bourdev +Copyright 2007-2012 Christian Henning, Andreas Pokorny, Lubomir Bourdev +Copyright (c) 2001 Ronald Garcia, Indiana University (garcia@osl.iu.edu) +Copyright (c) 2000-2013 Joerg Walter, Mathias Koch, Athanasios Iliopoulos +Copyright 2003-2013 Joaquin M Lopez Munoz. 2019 Mike Dev +(c) Copyright 2002 Rani Sharoni (rani_sharoni@hotmail.com) and Robert Ramey +(c) Copyright Steve Cleary, Beman Dawes, Howard Hinnant & John Maddock 2000. +Copyright (c) 2002-2003 Juan Carlos Arevalo-Baeza http://spirit.sourceforge.net +Copyright (c) 2000-2010 Joerg Walter, Mathias Koch, Gunter Winkler, David Bellot +(c) Copyright Steve Cleary, Beman Dawes, Howard Hinnant & John Maddock 2000-2005. +(c) Copyright 2010 Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk +Copyright (c) 2002 Brad King (brad.king@kitware.com) Douglas Gregor (gregod@cs.rpi.edu) +Copyright (c) 2010 Nuovation System Designs, LLC Grant Erickson +(c) Copyright 2009-2011 Frederic Bron, Robert Stewart, Steven Watanabe & Roman Perepelitsa. +(c) Copyright Dave Abrahams, Steve Cleary, Beman Dawes, Howard Hinnant & John Maddock 2000. +(c) Copyright Dave Abrahams, Steve Cleary, Beman Dawes, Howard Hinnant and John Maddock 2000. +Copyright (c) 2003 Jonathan de Halleux (dehalleux@pelikhan.com) http://spirit.sourceforge.net +(c) Copyright Steve Cleary, Beman Dawes, Aleksey Gurtovoy, Howard Hinnant & John Maddock 2000. +(c) Copyright Dave Abrahams, Steve Cleary, Beman Dawes, Howard Hinnant & John Maddock 2000-2003. +(c) Copyright David Abrahams Steve Cleary, Beman Dawes, Howard Hinnant & John Maddock 2000-2002. +Copyright (c) 1999-2001 Jaakko Jarvi (jaakko.jarvi@cs.utu.fi) Gary Powell (gwpowell@hotmail.com) +Copyright (c) 2013 Jakob Lykke Andersen, University of Southern Denmark (jlandersen@imada.sdu.dk) +Copyright (c) 2001 Jaakko Jarvi (jaakko.jarvi@cs.utu.fi) 2001 Gary Powell (gary.powell@sierra.com) +(c) Copyright Dave Abrahams, Steve Cleary, Beman Dawes, Howard Hinnant and John Maddock 2000, 2010. +Copyright (c) 2003 Jonathan de Halleux http://spirit.sourceforge.net/ http://www.boost.org/libs/spirit +(c) Copyright Dave Abrahams, Steve Cleary, Beman Dawes, Aleksey Gurtovoy, Howard Hinnant & John Maddock 2000. +Copyright 2002 Marc Wintermantel (wintermantel@even-ag.ch) ETH Zurich, Center of Structure Technologies (https://web.archive.org/web/20050307090307/http://www.structures.ethz.ch/) + +Apache License + +Version 2.0, January 2004 + +http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + + + "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + + + + "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + + + + "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + + + + "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + + + + "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + + + + "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + + + + "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + + + + "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + + + + "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + + + + "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); + +you may not use this file except in compliance with the License. + +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software + +distributed under the License is distributed on an "AS IS" BASIS, + +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +See the License for the specific language governing permissions and + +limitations under the License. + +--------------------------------------------------------- + +--------------------------------------------------------- + +Microsoft.Windows.CppWinRT 2.0.210122.3 - MIT + + + + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE + + +--------------------------------------------------------- + +--------------------------------------------------------- + +microsoft/directxtex 595b341626d2a4112bb6b9a3320d507f25c836fd - MIT + + +Copyright (c) Microsoft Corp. +Copyright (c) Microsoft Corporation. +(c) Microsoft Corporation. DirectX DirectXTex + + The MIT License (MIT) + +Copyright (c) 2011-2021 Microsoft Corp + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be included in all copies +or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF +CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE +OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +microsoft/wil 5bb5fbddf4b9c8e602c2da690f342839ad54084a - MIT + + + + MIT License + + Copyright (c) Microsoft Corporation. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE + + +--------------------------------------------------------- + +--------------------------------------------------------- + +GDeflate + +Copyright (c) 2020, 2021, 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + diff --git a/directstorage/README.md b/directstorage/README.md new file mode 100644 index 0000000000000000000000000000000000000000..62384de24ddc89b5b263933904567f68352d18da --- /dev/null +++ b/directstorage/README.md @@ -0,0 +1,106 @@ +# DirectStorage SDK + +This package contains the DirectStorage SDK, including the redistributable binaries. + +For help getting started and other information for DirectStorage, please see: + +https://aka.ms/DirectStorage + +The included licenses apply to the following files: + +- **LICENSE.txt** : applies to all files under `native/bin/` +- **LICENSE-CODE.txt** : applies to all files under `native/include/` +# Changelog + +## 1.2.2 + +### Bug Fixes + +- Fix race condition that would, in some rare circumstances, cause DirectStorage + to stop processing requests when the CPU is under high load. + +- Change DirectStorage worker thread to wakeup periodically and process requests + to catch rare cases where processing has stopped. + +### Breaking Changes +- Remove support for 32-bit ARM. + + +## 1.2.1 +- Ensure that the destination resource is left in the D3D12_RESOURCE_STATE_COMMON state after the DirectStorage request has completed. + +## 1.2.0 + +### New Features +- Add support for enabling buffered file IO for use on HDDs that may benefit from OS file caching behaviors. +- Add IDStorageQueue2::GetCompressionSupport API to indicate what path the DirectStorage runtime will take when decompressing a supported GPU decompression format. +- Update dstorage.h and dstorageerr.h to be covered by the MIT License. +- Add Microsoft.Direct3D.DirectStorage.winmd, to ease generation of non-C++ bindings to the API. + +### Bug Fixes +- Add "Reserved1" field to DSTORAGE_REQUEST_OPTIONS. This makes the in-memory layout of the structure more explicit, but doesn't actually change the layout from previous versions. +- Fix DSTORAGE_REQUEST_DESTINATION_TEXTURE_REGION for 3D textures. +- Fix scheduling issue that manifested when transferring uncompressed data from memory to buffers + +### Performance improvements +- Move the copy after GPU decompression onto the compute queue for GPUs where this is faster. + +## 1.1.1 +- Fix region size calculation for texture destinations with DepthOrArraySize > 1 which caused bogus DirectStorage Error/Warning message DSTORAGE_MESSAGE_ID_SMALLER_UNCOMPRESSED_SIZE + +## 1.1.0 + +### New Features +- Add support for GPU decompression and GDeflate: + - New compression format: `DSTORAGE_COMPRESSION_FORMAT_GDEFLATE` + - New interface: `IDStorageCustomCompressionQueue1` + - New function: `DStorageCreateCompressionCodec` + - New interface: `IDStorageCompressionCodec` +- New interface: `IDStorageQueue1`: + - New method `EnqueueSetEvent()` that allows a Win32 event to be signaled directly by DirectStorage. +- Add more warnings for invalid queue capacity, and invalid request fields. + +### Bug Fixes +- Fix hang when processing memory sourced requests that exceed in total the total size of the available staging buffer size. +- Fix running on Windows Server 2016. +- Add note in `dstorage.h` about how `IDStorageFile::Close()` doesn't affect the reference count. +- Fail enqueued requests that require a D3D device on queues that were created without one. +- For requests to GPU destinations (e.g. buffers, subresources), support requests that have uncompressed size greater than the destination size. + +### Breaking Changes + +1.1.0 is source compatible with 1.0.2, but recompilation will be required so that the DirectStorage binaries match the header: + +- DSTORAGE_ERROR_PARAMETERS_REQUEST::RequestName size changed from MAX_PATH to DSTORAGE_REQUEST_MAX_NAME. +- New DSTORAGE_CONFIGURATION fields. + +This is a trade-off between having a simpler API and binary compatibility. As DirectStorage is now more feature complete with GPU decompression, binary compatibility will become a higher priority. + +### Known Issues +- On older versions of D3D12, the debug layer may generate incorrect warnings that there are simultaneous writes to the input staging buffer from the copy queue that brings the data into the buffer and the compute queue that performs GPU decompression. + - As a workaround, you can use the Agility SDK: https://devblogs.microsoft.com/directx/gettingstarted-dx12agility/. + + + +## 1.0.2 + +### Breaking Changes + +* Update NuGet package layout to be consistent with other native NuGet packages. + +### New Features + +* Add `DSTORAGE_CUSTOM_DECOMPRESSION_FLAGS`; these can be used to determine if the destination for a custom decompression requests is in write-combined memory. + +### Bug Fixes + +* Fix building on x86. +* Improve documentation. + +### Performance Improvements + +* Improve Windows 10 performance. + +## 1.0.0 + +First release. diff --git a/directstorage/[Content_Types].xml b/directstorage/[Content_Types].xml new file mode 100644 index 0000000000000000000000000000000000000000..27945e37ab305c6a29375e934dd25ea8455afd6a --- /dev/null +++ b/directstorage/[Content_Types].xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/directstorage/distributable_files.txt b/directstorage/distributable_files.txt new file mode 100644 index 0000000000000000000000000000000000000000..4d9a3ad5b4784d4833e3fdd1b8257cff5082f635 --- /dev/null +++ b/directstorage/distributable_files.txt @@ -0,0 +1,4 @@ +You may distribute the following files: + +dstorage.dll +dstoragecore.dll diff --git a/dotnet/LICENSE.txt b/dotnet/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..116c722b7a9f6ab1adcb94707b7b38b72c9a505b --- /dev/null +++ b/dotnet/LICENSE.txt @@ -0,0 +1,64 @@ +MICROSOFT SOFTWARE LICENSE TERMS +MICROSOFT .NET LIBRARY +These license terms are an agreement between Microsoft Corporation (or based on where you live, one of its affiliates) and you. Please read them. They apply to the software named above, which includes the media on which you received it, if any. The terms also apply to any Microsoft + * updates, + * supplements, + * Internet-based services, and + * support services +for this software, unless other terms accompany those items. If so, those terms apply. +BY USING THE SOFTWARE, YOU ACCEPT THESE TERMS. IF YOU DO NOT ACCEPT THEM, DO NOT USE THE SOFTWARE. +IF YOU COMPLY WITH THESE LICENSE TERMS, YOU HAVE THE PERPETUAL RIGHTS BELOW. +1. INSTALLATION AND USE RIGHTS. + a. Installation and Use. You may install and use any number of copies of the software to design, develop and test your programs. + b. Third Party Programs. The software may include third party programs that Microsoft, not the third party, licenses to you under this agreement. Notices, if any, for the third party program are included for your information only. +2. DATA. The software may collect information about you and your use of the software, and send that to Microsoft. Microsoft may use this information to improve our products and services. You can learn more about data collection and use in the help documentation and the privacy statement at https://go.microsoft.com/fwlink/?LinkId=528096. Your use of the software operates as your consent to these practices. +3. ADDITIONAL LICENSING REQUIREMENTS AND/OR USE RIGHTS. + a. DISTRIBUTABLE CODE. The software is comprised of Distributable Code. "Distributable Code" is code that you are permitted to distribute in programs you develop if you comply with the terms below. + i. Right to Use and Distribute. + * You may copy and distribute the object code form of the software. + * Third Party Distribution. You may permit distributors of your programs to copy and distribute the Distributable Code as part of those programs. + ii. Distribution Requirements. For any Distributable Code you distribute, you must + * add significant primary functionality to it in your programs; + * require distributors and external end users to agree to terms that protect it at least as much as this agreement; + * display your valid copyright notice on your programs; and + * indemnify, defend, and hold harmless Microsoft from any claims, including attorneys' fees, related to the distribution or use of your programs. + iii. Distribution Restrictions. You may not + * alter any copyright, trademark or patent notice in the Distributable Code; + * use Microsoft's trademarks in your programs' names or in a way that suggests your programs come from or are endorsed by Microsoft; + * include Distributable Code in malicious, deceptive or unlawful programs; or + * modify or distribute the source code of any Distributable Code so that any part of it becomes subject to an Excluded License. An Excluded License is one that requires, as a condition of use, modification or distribution, that + * the code be disclosed or distributed in source code form; or + * others have the right to modify it. +4. SCOPE OF LICENSE. The software is licensed, not sold. This agreement only gives you some rights to use the software. Microsoft reserves all other rights. Unless applicable law gives you more rights despite this limitation, you may use the software only as expressly permitted in this agreement. In doing so, you must comply with any technical limitations in the software that only allow you to use it in certain ways. You may not + * work around any technical limitations in the software; + * reverse engineer, decompile or disassemble the software, except and only to the extent that applicable law expressly permits, despite this limitation; + * publish the software for others to copy; + * rent, lease or lend the software; + * transfer the software or this agreement to any third party; or + * use the software for commercial software hosting services. +5. BACKUP COPY. You may make one backup copy of the software. You may use it only to reinstall the software. +6. DOCUMENTATION. Any person that has valid access to your computer or internal network may copy and use the documentation for your internal, reference purposes. +7. EXPORT RESTRICTIONS. The software is subject to United States export laws and regulations. You must comply with all domestic and international export laws and regulations that apply to the software. These laws include restrictions on destinations, end users and end use. For additional information, see www.microsoft.com/exporting. +8. SUPPORT SERVICES. Because this software is "as is," we may not provide support services for it. +9. ENTIRE AGREEMENT. This agreement, and the terms for supplements, updates, Internet-based services and support services that you use, are the entire agreement for the software and support services. +10. APPLICABLE LAW. + a. United States. If you acquired the software in the United States, Washington state law governs the interpretation of this agreement and applies to claims for breach of it, regardless of conflict of laws principles. The laws of the state where you live govern all other claims, including claims under state consumer protection laws, unfair competition laws, and in tort. + b. Outside the United States. If you acquired the software in any other country, the laws of that country apply. +11. LEGAL EFFECT. This agreement describes certain legal rights. You may have other rights under the laws of your country. You may also have rights with respect to the party from whom you acquired the software. This agreement does not change your rights under the laws of your country if the laws of your country do not permit it to do so. +12. DISCLAIMER OF WARRANTY. THE SOFTWARE IS LICENSED "AS-IS." YOU BEAR THE RISK OF USING IT. MICROSOFT GIVES NO EXPRESS WARRANTIES, GUARANTEES OR CONDITIONS. YOU MAY HAVE ADDITIONAL CONSUMER RIGHTS OR STATUTORY GUARANTEES UNDER YOUR LOCAL LAWS WHICH THIS AGREEMENT CANNOT CHANGE. TO THE EXTENT PERMITTED UNDER YOUR LOCAL LAWS, MICROSOFT EXCLUDES THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. +FOR AUSTRALIA - YOU HAVE STATUTORY GUARANTEES UNDER THE AUSTRALIAN CONSUMER LAW AND NOTHING IN THESE TERMS IS INTENDED TO AFFECT THOSE RIGHTS. +13. LIMITATION ON AND EXCLUSION OF REMEDIES AND DAMAGES. YOU CAN RECOVER FROM MICROSOFT AND ITS SUPPLIERS ONLY DIRECT DAMAGES UP TO U.S. $5.00. YOU CANNOT RECOVER ANY OTHER DAMAGES, INCLUDING CONSEQUENTIAL, LOST PROFITS, SPECIAL, INDIRECT OR INCIDENTAL DAMAGES. +This limitation applies to + * anything related to the software, services, content (including code) on third party Internet sites, or third party programs; and + * claims for breach of contract, breach of warranty, guarantee or condition, strict liability, negligence, or other tort to the extent permitted by applicable law. +It also applies even if Microsoft knew or should have known about the possibility of the damages. The above limitation or exclusion may not apply to you because your country may not allow the exclusion or limitation of incidental, consequential or other damages. +Please note: As this software is distributed in Quebec, Canada, some of the clauses in this agreement are provided below in French. +Remarque : Ce logiciel étant distribué au Québec, Canada, certaines des clauses dans ce contrat sont fournies ci-dessous en français. +EXONÉRATION DE GARANTIE. Le logiciel visé par une licence est offert « tel quel ». Toute utilisation de ce logiciel est à votre seule risque et péril. Microsoft n'accorde aucune autre garantie expresse. Vous pouvez bénéficier de droits additionnels en vertu du droit local sur la protection des consommateurs, que ce contrat ne peut modifier. La ou elles sont permises par le droit locale, les garanties implicites de qualité marchande, d'adéquation à un usage particulier et d'absence de contrefaçon sont exclues. +LIMITATION DES DOMMAGES-INTÉRÊTS ET EXCLUSION DE RESPONSABILITÉ POUR LES DOMMAGES. Vous pouvez obtenir de Microsoft et de ses fournisseurs une indemnisation en cas de dommages directs uniquement à hauteur de 5,00 $ US. Vous ne pouvez prétendre à aucune indemnisation pour les autres dommages, y compris les dommages spéciaux, indirects ou accessoires et pertes de bénéfices. +Cette limitation concerne : + * tout ce qui est relié au logiciel, aux services ou au contenu (y compris le code) figurant sur des sites Internet tiers ou dans des programmes tiers ; et + * les réclamations au titre de violation de contrat ou de garantie, ou au titre de responsabilité stricte, de négligence ou d'une autre faute dans la limite autorisée par la loi en vigueur. +Elle s'applique également, même si Microsoft connaissait ou devrait connaître l'éventualité d'un tel dommage. Si votre pays n'autorise pas l'exclusion ou la limitation de responsabilité pour les dommages indirects, accessoires ou de quelque nature que ce soit, il se peut que la limitation ou l'exclusion ci-dessus ne s'appliquera pas à votre égard. +EFFET JURIDIQUE. Le présent contrat décrit certains droits juridiques. Vous pourriez avoir d'autres droits prévus par les lois de votre pays. Le présent contrat ne modifie pas les droits que vous confèrent les lois de votre pays si celles-ci ne le permettent pas. + diff --git a/dotnet/ThirdPartyNotices.txt b/dotnet/ThirdPartyNotices.txt new file mode 100644 index 0000000000000000000000000000000000000000..3697ea3d1644950f6a98b6733a000243bc040f71 --- /dev/null +++ b/dotnet/ThirdPartyNotices.txt @@ -0,0 +1,1451 @@ +.NET Runtime uses third-party libraries or other resources that may be +distributed under licenses different than the .NET Runtime software. + +In the event that we accidentally failed to list a required notice, please +bring it to our attention. Post an issue or email us: + + dotnet@microsoft.com + +The attached notices are provided for information only. + +License notice for ASP.NET +------------------------------- + +Copyright (c) .NET Foundation. All rights reserved. +Licensed under the Apache License, Version 2.0. + +Available at +https://github.com/dotnet/aspnetcore/blob/main/LICENSE.txt + +License notice for Slicing-by-8 +------------------------------- + +http://sourceforge.net/projects/slicing-by-8/ + +Copyright (c) 2004-2006 Intel Corporation - All Rights Reserved + + +This software program is licensed subject to the BSD License, available at +http://www.opensource.org/licenses/bsd-license.html. + +License notice for Unicode data +------------------------------- + +https://www.unicode.org/license.html + +Copyright © 1991-2020 Unicode, Inc. All rights reserved. +Distributed under the Terms of Use in https://www.unicode.org/copyright.html. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Unicode data files and any associated documentation +(the "Data Files") or Unicode software and any associated documentation +(the "Software") to deal in the Data Files or Software +without restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, and/or sell copies of +the Data Files or Software, and to permit persons to whom the Data Files +or Software are furnished to do so, provided that either +(a) this copyright and permission notice appear with all copies +of the Data Files or Software, or +(b) this copyright and permission notice appear in associated +Documentation. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT OF THIRD PARTY RIGHTS. +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS +NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL +DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, +DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THE DATA FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder +shall not be used in advertising or otherwise to promote the sale, +use or other dealings in these Data Files or Software without prior +written authorization of the copyright holder. + +License notice for Mono +------------------------------- + +http://www.mono-project.com/docs/about-mono/ + +Copyright (c) .NET Foundation Contributors + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the Software), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +License notice for International Organization for Standardization +----------------------------------------------------------------- + +Portions (C) International Organization for Standardization 1986: + Permission to copy in any form is granted for use with + conforming SGML systems and applications as defined in + ISO 8879, provided this notice is included in all copies. + +License notice for Intel +------------------------ + +"Copyright (c) 2004-2006 Intel Corporation - All Rights Reserved + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +License notice for Xamarin and Novell +------------------------------------- + +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +Copyright (c) 2011 Novell, Inc (http://www.novell.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +Third party notice for W3C +-------------------------- + +"W3C SOFTWARE AND DOCUMENT NOTICE AND LICENSE +Status: This license takes effect 13 May, 2015. +This work is being provided by the copyright holders under the following license. +License +By obtaining and/or copying this work, you (the licensee) agree that you have read, understood, and will comply with the following terms and conditions. +Permission to copy, modify, and distribute this work, with or without modification, for any purpose and without fee or royalty is hereby granted, provided that you include the following on ALL copies of the work or portions thereof, including modifications: +The full text of this NOTICE in a location viewable to users of the redistributed or derivative work. +Any pre-existing intellectual property disclaimers, notices, or terms and conditions. If none exist, the W3C Software and Document Short Notice should be included. +Notice of any changes or modifications, through a copyright statement on the new code or document such as "This software or document includes material copied from or derived from [title and URI of the W3C document]. Copyright © [YEAR] W3C® (MIT, ERCIM, Keio, Beihang)." +Disclaimers +THIS WORK IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE OR DOCUMENT WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. +COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR DOCUMENT. +The name and trademarks of copyright holders may NOT be used in advertising or publicity pertaining to the work without specific, written prior permission. Title to copyright in this work will at all times remain with copyright holders." + +License notice for Bit Twiddling Hacks +-------------------------------------- + +Bit Twiddling Hacks + +By Sean Eron Anderson +seander@cs.stanford.edu + +Individually, the code snippets here are in the public domain (unless otherwise +noted) — feel free to use them however you please. The aggregate collection and +descriptions are © 1997-2005 Sean Eron Anderson. The code and descriptions are +distributed in the hope that they will be useful, but WITHOUT ANY WARRANTY and +without even the implied warranty of merchantability or fitness for a particular +purpose. + +License notice for Brotli +-------------------------------------- + +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +compress_fragment.c: +Copyright (c) 2011, Google Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +decode_fuzzer.c: +Copyright (c) 2015 The Chromium Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." + +License notice for Json.NET +------------------------------- + +https://github.com/JamesNK/Newtonsoft.Json/blob/master/LICENSE.md + +The MIT License (MIT) + +Copyright (c) 2007 James Newton-King + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +License notice for vectorized base64 encoding / decoding +-------------------------------------------------------- + +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2016-2017, Matthieu Darbois +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +- Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +License notice for RFC 3492 +--------------------------- + +The punycode implementation is based on the sample code in RFC 3492 + +Copyright (C) The Internet Society (2003). All Rights Reserved. + +This document and translations of it may be copied and furnished to +others, and derivative works that comment on or otherwise explain it +or assist in its implementation may be prepared, copied, published +and distributed, in whole or in part, without restriction of any +kind, provided that the above copyright notice and this paragraph are +included on all such copies and derivative works. However, this +document itself may not be modified in any way, such as by removing +the copyright notice or references to the Internet Society or other +Internet organizations, except as needed for the purpose of +developing Internet standards in which case the procedures for +copyrights defined in the Internet Standards process must be +followed, or as required to translate it into languages other than +English. + +The limited permissions granted above are perpetual and will not be +revoked by the Internet Society or its successors or assigns. + +This document and the information contained herein is provided on an +"AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING +TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING +BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION +HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF +MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + +Copyright(C) The Internet Society 1997. All Rights Reserved. + +This document and translations of it may be copied and furnished to others, +and derivative works that comment on or otherwise explain it or assist in +its implementation may be prepared, copied, published and distributed, in +whole or in part, without restriction of any kind, provided that the above +copyright notice and this paragraph are included on all such copies and +derivative works.However, this document itself may not be modified in any +way, such as by removing the copyright notice or references to the Internet +Society or other Internet organizations, except as needed for the purpose of +developing Internet standards in which case the procedures for copyrights +defined in the Internet Standards process must be followed, or as required +to translate it into languages other than English. + +The limited permissions granted above are perpetual and will not be revoked +by the Internet Society or its successors or assigns. + +This document and the information contained herein is provided on an "AS IS" +basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING TASK FORCE +DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO +ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY +RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A +PARTICULAR PURPOSE. + +License notice for Algorithm from RFC 4122 - +A Universally Unique IDentifier (UUID) URN Namespace +---------------------------------------------------- + +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & +Digital Equipment Corporation, Maynard, Mass. +Copyright (c) 1998 Microsoft. +To anyone who acknowledges that this file is provided "AS IS" +without any express or implied warranty: permission to use, copy, +modify, and distribute this file for any purpose is hereby +granted without fee, provided that the above copyright notices and +this notice appears in all source code copies, and that none of +the names of Open Software Foundation, Inc., Hewlett-Packard +Company, Microsoft, or Digital Equipment Corporation be used in +advertising or publicity pertaining to distribution of the software +without specific, written prior permission. Neither Open Software +Foundation, Inc., Hewlett-Packard Company, Microsoft, nor Digital +Equipment Corporation makes any representations about the +suitability of this software for any purpose." + +License notice for The LLVM Compiler Infrastructure +--------------------------------------------------- + +Developed by: + + LLVM Team + + University of Illinois at Urbana-Champaign + + http://llvm.org + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal with +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + * Neither the names of the LLVM Team, University of Illinois at + Urbana-Champaign, nor the names of its contributors may be used to + endorse or promote products derived from this Software without specific + prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE +SOFTWARE. + +License notice for Bob Jenkins +------------------------------ + +By Bob Jenkins, 1996. bob_jenkins@burtleburtle.net. You may use this +code any way you wish, private, educational, or commercial. It's free. + +License notice for Greg Parker +------------------------------ + +Greg Parker gparker@cs.stanford.edu December 2000 +This code is in the public domain and may be copied or modified without +permission. + +License notice for libunwind based code +---------------------------------------- + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +License notice for Printing Floating-Point Numbers (Dragon4) +------------------------------------------------------------ + +/****************************************************************************** + Copyright (c) 2014 Ryan Juckett + http://www.ryanjuckett.com/ + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +******************************************************************************/ + +License notice for Printing Floating-point Numbers (Grisu3) +----------------------------------------------------------- + +Copyright 2012 the V8 project authors. All rights reserved. +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of Google Inc. nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +License notice for xxHash +------------------------- + +xxHash Library +Copyright (c) 2012-2014, Yann Collet +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +License notice for Berkeley SoftFloat Release 3e +------------------------------------------------ + +https://github.com/ucb-bar/berkeley-softfloat-3 +https://github.com/ucb-bar/berkeley-softfloat-3/blob/master/COPYING.txt + +License for Berkeley SoftFloat Release 3e + +John R. Hauser +2018 January 20 + +The following applies to the whole of SoftFloat Release 3e as well as to +each source file individually. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions, and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +License notice for xoshiro RNGs +-------------------------------- + +Written in 2018 by David Blackman and Sebastiano Vigna (vigna@acm.org) + +To the extent possible under law, the author has dedicated all copyright +and related and neighboring rights to this software to the public domain +worldwide. This software is distributed without any warranty. + +See . + +License for fastmod (https://github.com/lemire/fastmod) +-------------------------------------- + + Copyright 2018 Daniel Lemire + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +License notice for The C++ REST SDK +----------------------------------- + +C++ REST SDK + +The MIT License (MIT) + +Copyright (c) Microsoft Corporation + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +License notice for MessagePack-CSharp +------------------------------------- + +MessagePack for C# + +MIT License + +Copyright (c) 2017 Yoshifumi Kawai + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +License notice for lz4net +------------------------------------- + +lz4net + +Copyright (c) 2013-2017, Milosz Krajewski + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +License notice for Nerdbank.Streams +----------------------------------- + +The MIT License (MIT) + +Copyright (c) Andrew Arnott + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +License notice for RapidJSON +---------------------------- + +Tencent is pleased to support the open source community by making RapidJSON available. + +Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. + +Licensed under the MIT License (the "License"); you may not use this file except +in compliance with the License. You may obtain a copy of the License at + +http://opensource.org/licenses/MIT + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. + +License notice for DirectX Math Library +--------------------------------------- + +https://github.com/microsoft/DirectXMath/blob/master/LICENSE + + The MIT License (MIT) + +Copyright (c) 2011-2020 Microsoft Corp + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be included in all copies +or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF +CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE +OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +License notice for ldap4net +--------------------------- + +The MIT License (MIT) + +Copyright (c) 2018 Alexander Chermyanin + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +License notice for vectorized sorting code +------------------------------------------ + +MIT License + +Copyright (c) 2020 Dan Shechter + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +License notice for musl +----------------------- + +musl as a whole is licensed under the following standard MIT license: + +Copyright © 2005-2020 Rich Felker, et al. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +License notice for "Faster Unsigned Division by Constants" +---------------------------------------------------------- + +Reference implementations of computing and using the "magic number" approach to dividing +by constants, including codegen instructions. The unsigned division incorporates the +"round down" optimization per ridiculous_fish. + +This is free and unencumbered software. Any copyright is dedicated to the Public Domain. + +License notice for mimalloc +--------------------------- + +MIT License + +Copyright (c) 2019 Microsoft Corporation, Daan Leijen + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +License notice for Apple header files +------------------------------------- + +Copyright (c) 1980, 1986, 1993 + The Regents of the University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. All advertising materials mentioning features or use of this software + must display the following acknowledgement: + This product includes software developed by the University of + California, Berkeley and its contributors. +4. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +License notice for Angular v8.0 +-------------------------------- +The MIT License (MIT) +===================== + +Copyright (c) 2010-2019 Google LLC. http://angular.io/license + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +License notice for corefx + +License notice for BedrockFramework +=================================== + +MIT License + +Copyright (c) 2019 David Fowler + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +License notice for Swashbuckle +=================================== + +The MIT License (MIT) + +Copyright (c) 2016 Richard Morris + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +License notice for cli-spinners +============================================= + +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +License notice for dotnet-deb-tool +------------------------------------ + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +License notice for IIS-Common +------------------------------------ + +MIT License + +Copyright (c) Microsoft Corporation. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE + +License notice for IIS-Setup +------------------------------------ + +MIT License + +Copyright (c) Microsoft Corporation. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE + +License notice for LZMA SDK +--------------------------- + +http://7-zip.org/sdk.html + +LZMA SDK is placed in the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or distribute the +original LZMA SDK code, either in source code form or as a compiled binary, +for any purpose, commercial or non-commercial, and by any means. + +License notice for MonoDevelop +------------------------------ + +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +Copyright (c) 2011 Novell, Inc (http://www.novell.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +License notice for Nuget.Client +------------------------------- + +Copyright (c) .NET Foundation. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +these files except in compliance with the License. You may obtain a copy of the +License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. + +License notice for Ookie.Dialogs +-------------------------------- + +http://www.ookii.org/software/dialogs/ + +Copyright © Sven Groot (Ookii.org) 2009 +All rights reserved. + + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1) Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. +2) Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. +3) Neither the name of the ORGANIZATION nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +THE POSSIBILITY OF SUCH DAMAGE. + +License notice for viz.js +------------------------------------ + +Copyright (c) 2014-2018 Michael Daines + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +License notice for West Wind Live Reload ASP.NET Core Middleware +============================================= + + + +--- + +lz4net + +Copyright (c) 2013-2017, Milosz Krajewski + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +MIT License +----------- + +Copyright (c) 2019-2020 West Wind Technologies + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +License for fastmod (https://github.com/lemire/fastmod) and ibm-fpgen (https://github.com/nigeltao/parse-number-fxx-test-data) +-------------------------------------- + + Copyright 2018 Daniel Lemire + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +License notice for Angular v8.0 +-------------------------------------------- +The MIT License (MIT) +===================== + +Copyright (c) 2010-2019 Google LLC. http://angular.io/license + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +License notice for corefx + +License notice for JavaScript queues +------------------------------------- + +CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER. + +Statement of Purpose +The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work"). +Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others. +For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following: +the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work; +moral rights retained by the original author(s) and/or performer(s); +publicity and privacy rights pertaining to a person's image or likeness depicted in a Work; +rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below; +rights protecting the extraction, dissemination, use and reuse of data in a Work; +database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and +other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof. +2. Waiver. To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose. +3. Public License Fallback. Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose. +4. Limitations and Disclaimers. +a. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document. +b. Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law. +c. Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work. +d. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work. + +License notice for MSBuild Locator +------------------------------------- + +https://github.com/Microsoft/MSBuildLocator + +Copyright (c) 2018 .NET Foundation and Contributors + +This software is licensed subject to the MIT license, available at +https://opensource.org/licenses/MIT + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +License notice for Newtonsoft.Json +=================================== + +The MIT License (MIT) + +Copyright (c) 2007 James Newton-King + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +License notice for NuGet.Client +------------------------------- + +In reference to: https://github.com/dotnet/templating/blob/main/build/nuget.exe + +https://github.com/NuGet/NuGet.Client/blob/dev/LICENSE.txt + +Copyright (c) .NET Foundation. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +these files except in compliance with the License. You may obtain a copy of the +License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. + +License notice for Roslyn Clr Heap Allocation Analyzer +------------------------------------- + +https://github.com/Microsoft/RoslynClrHeapAllocationAnalyzer + +Copyright (c) 2018 Microsoft Corporation + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +License notice for StyleCop Analyzers +------------------------------------- + +The MIT License (MIT) + +Copyright (c) Tunnel Vision Laboratories, LLC + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +------------------------------------------------ + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/dotnet/vcruntime140_1.dll b/dotnet/vcruntime140_1.dll new file mode 100644 index 0000000000000000000000000000000000000000..2071f2814bbc6dac9a18b32c77ca86da09d579c3 Binary files /dev/null and b/dotnet/vcruntime140_1.dll differ diff --git a/ffmpeg/LICENSE b/ffmpeg/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..94a9ed024d3859793618152ea559a168bbcbb5e2 --- /dev/null +++ b/ffmpeg/LICENSE @@ -0,0 +1,674 @@ + 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 +. diff --git a/ffmpeg/LICENSE.txt b/ffmpeg/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..94a9ed024d3859793618152ea559a168bbcbb5e2 --- /dev/null +++ b/ffmpeg/LICENSE.txt @@ -0,0 +1,674 @@ + 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 +. diff --git a/ffmpeg/README.txt b/ffmpeg/README.txt new file mode 100644 index 0000000000000000000000000000000000000000..aa925ee385d47600723e415cf3f00245e95284cf --- /dev/null +++ b/ffmpeg/README.txt @@ -0,0 +1,916 @@ +FFmpeg 64-bit static Windows build from www.gyan.dev + +Version: 2026-05-11-git-17bc88e67f-full_build-www.gyan.dev + +License: GPL v3 + +Source Code: https://github.com/FFmpeg/FFmpeg/commit/17bc88e67f + +External Assets +frei0r plugins: https://www.gyan.dev/ffmpeg/builds/ffmpeg-frei0r-plugins +lensfun database: https://www.gyan.dev/ffmpeg/builds/ffmpeg-lensfun-db +whisper models: https://huggingface.co/ggerganov/whisper.cpp/tree/main + +git-full build configuration: + +ARCH x86 (generic) +big-endian no +runtime cpu detection yes +standalone assembly yes +x86 assembler nasm +MMX enabled yes +MMXEXT enabled yes +SSE enabled yes +SSSE3 enabled yes +AESNI enabled yes +CLMUL enabled yes +AVX enabled yes +AVX2 enabled yes +AVX-512 enabled yes +AVX-512ICL enabled yes +XOP enabled yes +FMA3 enabled yes +FMA4 enabled yes +i686 features enabled yes +CMOV is fast yes +EBX available yes +EBP available yes +debug symbols yes +strip symbols yes +optimize for size no +optimizations yes +static yes +shared no +network support yes +threading support pthreads +safe bitstream reader yes +texi2html enabled no +perl enabled yes +pod2man enabled yes +makeinfo enabled yes +makeinfo supports HTML yes +experimental features yes +xmllint enabled yes + +External libraries: +avisynth libgsm libsvtav1 +bzlib libharfbuzz libsvtjpegxs +cairo libilbc libtheora +chromaprint libjxl libtwolame +frei0r liblc3 libuavs3d +gmp liblensfun libvidstab +gnutls libmodplug libvmaf +iconv libmp3lame libvo_amrwbenc +ladspa libmysofa libvorbis +lcms2 liboapv libvpx +libaom libopencore_amrnb libvvenc +libaribb24 libopencore_amrwb libwebp +libaribcaption libopenjpeg libx264 +libass libopenmpt libx265 +libbluray libopus libxavs2 +libbs2b libplacebo libxevd +libcaca libqrencode libxeve +libcdio libquirc libxml2 +libcodec2 librav1e libxvid +libdav1d librist libzimg +libdavs2 librubberband libzmq +libdvdnav libshaderc libzvbi +libdvdread libshine lzma +libflite libsnappy mediafoundation +libfontconfig libsoxr openal +libfreetype libspeex sdl2 +libfribidi libsrt whisper +libgme libssh zlib + +External libraries providing hardware acceleration: +amf d3d12va nvdec +cuda dxva2 nvenc +cuda_llvm ffnvcodec opencl +cuvid libmfx vaapi +d3d11va libvpl vulkan + +Libraries: +avcodec avformat swscale +avdevice avutil +avfilter swresample + +Programs: +ffmpeg ffplay ffprobe + +Enabled decoders: +aac fmvc pcm_u32be +aac_fixed fourxm pcm_u32le +aac_latm fraps pcm_u8 +aasc frwu pcm_vidc +ac3 ftr pcx +ac3_fixed g2m pdv +acelp_kelvin g723_1 pfm +adpcm_4xm g728 pgm +adpcm_adx g729 pgmyuv +adpcm_afc gdv pgssub +adpcm_agm gem pgx +adpcm_aica gif phm +adpcm_argo gremlin_dpcm photocd +adpcm_circus gsm pictor +adpcm_ct gsm_ms pixlet +adpcm_dtk h261 pjs +adpcm_ea h263 png +adpcm_ea_maxis_xa h263i ppm +adpcm_ea_r1 h263p prores +adpcm_ea_r2 h264 prores_raw +adpcm_ea_r3 h264_amf prosumer +adpcm_ea_xas h264_cuvid psd +adpcm_g722 h264_qsv ptx +adpcm_g726 hap qcelp +adpcm_g726le hca qdm2 +adpcm_ima_acorn hcom qdmc +adpcm_ima_alp hdr qdraw +adpcm_ima_amv hevc qoa +adpcm_ima_apc hevc_amf qoi +adpcm_ima_apm hevc_cuvid qpeg +adpcm_ima_cunning hevc_qsv qtrle +adpcm_ima_dat4 hnm4_video r10k +adpcm_ima_dk3 hq_hqa r210 +adpcm_ima_dk4 hqx ra_144 +adpcm_ima_ea_eacs huffyuv ra_288 +adpcm_ima_ea_sead hymt ralf +adpcm_ima_escape iac rasc +adpcm_ima_hvqm2 idcin rawvideo +adpcm_ima_hvqm4 idf realtext +adpcm_ima_iss iff_ilbm rka +adpcm_ima_magix ilbc rl2 +adpcm_ima_moflex imc roq +adpcm_ima_mtf imm4 roq_dpcm +adpcm_ima_oki imm5 rpza +adpcm_ima_pda indeo2 rscc +adpcm_ima_qt indeo3 rtv1 +adpcm_ima_rad indeo4 rv10 +adpcm_ima_smjpeg indeo5 rv20 +adpcm_ima_ssi interplay_acm rv30 +adpcm_ima_wav interplay_dpcm rv40 +adpcm_ima_ws interplay_video rv60 +adpcm_ima_xbox ipu s302m +adpcm_ms jacosub sami +adpcm_mtaf jpeg2000 sanm +adpcm_n64 jpegls sbc +adpcm_psx jv scpr +adpcm_psxc kgv1 screenpresso +adpcm_sanyo kmvc sdx2_dpcm +adpcm_sbpro_2 lagarith sga +adpcm_sbpro_3 lead sgi +adpcm_sbpro_4 libaom_av1 sgirle +adpcm_swf libaribb24 sheervideo +adpcm_thp libaribcaption shorten +adpcm_thp_le libcodec2 simbiosis_imx +adpcm_vima libdav1d sipr +adpcm_xa libdavs2 siren +adpcm_xmd libgsm smackaud +adpcm_yamaha libgsm_ms smacker +adpcm_zork libilbc smc +agm libjxl smvjpeg +ahx libjxl_anim snow +aic liblc3 sol_dpcm +alac libopencore_amrnb sonic +alias_pix libopencore_amrwb sp5x +als libopus speedhq +amrnb libspeex speex +amrwb libsvtjpegxs srgc +amv libuavs3d srt +anm libvorbis ssa +ansi libvpx_vp8 stl +anull libvpx_vp9 subrip +apac libxevd subviewer +ape libzvbi_teletext subviewer1 +apng loco sunrast +aptx lscr svq1 +aptx_hd m101 svq3 +apv mace3 tak +arbc mace6 targa +argo magicyuv targa_y216 +ass mdec tdsc +asv1 media100 text +asv2 metasound theora +atrac1 microdvd thp +atrac3 mimic tiertexseqvideo +atrac3al misc4 tiff +atrac3p mjpeg tmv +atrac3pal mjpeg_cuvid truehd +atrac9 mjpeg_qsv truemotion1 +aura mjpegb truemotion2 +aura2 mlp truemotion2rt +av1 mmvideo truespeech +av1_amf mobiclip tscc +av1_cuvid motionpixels tscc2 +av1_qsv movtext tta +avrn mp1 twinvq +avrp mp1float txd +avs mp2 ulti +avui mp2float utvideo +bethsoftvid mp3 v210 +bfi mp3adu v210x +bink mp3adufloat v308 +binkaudio_dct mp3float v408 +binkaudio_rdft mp3on4 v410 +bintext mp3on4float vb +bitpacked mpc7 vble +bmp mpc8 vbn +bmv_audio mpeg1_cuvid vc1 +bmv_video mpeg1video vc1_cuvid +bonk mpeg2_cuvid vc1_qsv +brender_pix mpeg2_qsv vc1image +c93 mpeg2video vcr1 +cavs mpeg4 vmdaudio +cbd2_dpcm mpeg4_cuvid vmdvideo +ccaption mpegvideo vmix +cdgraphics mpl2 vmnc +cdtoons msa1 vnull +cdxl mscc vorbis +cfhd msmpeg4v1 vp3 +cinepak msmpeg4v2 vp4 +clearvideo msmpeg4v3 vp5 +cljr msnsiren vp6 +cllc msp2 vp6a +comfortnoise msrle vp6f +cook mss1 vp7 +cpia mss2 vp8 +cri msvideo1 vp8_cuvid +cscd mszh vp8_qsv +cyuv mts2 vp9 +dca mv30 vp9_amf +dds mvc1 vp9_cuvid +derf_dpcm mvc2 vp9_qsv +dfa mvdv vplayer +dfpwm mvha vqa +dirac mwsc vqc +dnxhd mxpeg vvc +dolby_e nellymoser vvc_qsv +dpx notchlc wady_dpcm +dsd_lsbf nuv wavarc +dsd_lsbf_planar on2avc wavpack +dsd_msbf opus wbmp +dsd_msbf_planar osq wcmv +dsicinaudio paf_audio webp +dsicinvideo paf_video webvtt +dss_sp pam wmalossless +dst pbm wmapro +dvaudio pcm_alaw wmav1 +dvbsub pcm_bluray wmav2 +dvdsub pcm_dvd wmavoice +dvvideo pcm_f16le wmv1 +dxa pcm_f24le wmv2 +dxtory pcm_f32be wmv3 +dxv pcm_f32le wmv3image +eac3 pcm_f64be wnv1 +eacmv pcm_f64le wrapped_avframe +eamad pcm_lxf ws_snd1 +eatgq pcm_mulaw xan_dpcm +eatgv pcm_s16be xan_wc3 +eatqi pcm_s16be_planar xan_wc4 +eightbps pcm_s16le xbin +eightsvx_exp pcm_s16le_planar xbm +eightsvx_fib pcm_s24be xface +escape124 pcm_s24daud xl +escape130 pcm_s24le xma1 +evrc pcm_s24le_planar xma2 +exr pcm_s32be xpm +fastaudio pcm_s32le xsub +ffv1 pcm_s32le_planar xwd +ffvhuff pcm_s64be y41p +ffwavesynth pcm_s64le ylc +fic pcm_s8 yop +fits pcm_s8_planar yuv4 +flac pcm_sga zero12v +flashsv pcm_u16be zerocodec +flashsv2 pcm_u16le zlib +flic pcm_u24be zmbv +flv pcm_u24le + +Enabled encoders: +a64multi hevc_nvenc pcm_s64be +a64multi5 hevc_qsv pcm_s64le +aac hevc_vaapi pcm_s8 +aac_mf hevc_vulkan pcm_s8_planar +ac3 huffyuv pcm_u16be +ac3_fixed jpeg2000 pcm_u16le +ac3_mf jpegls pcm_u24be +adpcm_adx libaom_av1 pcm_u24le +adpcm_argo libcodec2 pcm_u32be +adpcm_g722 libgsm pcm_u32le +adpcm_g726 libgsm_ms pcm_u8 +adpcm_g726le libilbc pcm_vidc +adpcm_ima_alp libjxl pcx +adpcm_ima_amv libjxl_anim pdv +adpcm_ima_apm liblc3 pfm +adpcm_ima_qt libmp3lame pgm +adpcm_ima_ssi liboapv pgmyuv +adpcm_ima_wav libopencore_amrnb phm +adpcm_ima_ws libopenjpeg png +adpcm_ms libopus ppm +adpcm_swf librav1e prores +adpcm_yamaha libshine prores_aw +alac libspeex prores_ks +alias_pix libsvtav1 prores_ks_vulkan +amv libsvtjpegxs qoi +anull libtheora qtrle +apng libtwolame r10k +aptx libvo_amrwbenc r210 +aptx_hd libvorbis ra_144 +ass libvpx_vp8 rawvideo +asv1 libvpx_vp9 roq +asv2 libvvenc roq_dpcm +av1_amf libwebp rpza +av1_d3d12va libwebp_anim rv10 +av1_mf libx264 rv20 +av1_nvenc libx264rgb s302m +av1_qsv libx265 sbc +av1_vaapi libxavs2 sgi +av1_vulkan libxeve smc +avrp libxvid snow +avui ljpeg speedhq +bitpacked magicyuv srt +bmp mjpeg ssa +cfhd mjpeg_qsv subrip +cinepak mjpeg_vaapi sunrast +cljr mlp svq1 +comfortnoise movtext targa +dca mp2 text +dfpwm mp2fixed tiff +dnxhd mp3_mf truehd +dpx mpeg1video tta +dvbsub mpeg2_qsv ttml +dvdsub mpeg2_vaapi utvideo +dvvideo mpeg2video v210 +dxv mpeg4 v308 +eac3 msmpeg4v2 v408 +exr msmpeg4v3 v410 +ffv1 msrle vbn +ffv1_vulkan msvideo1 vc2 +ffvhuff nellymoser vnull +fits opus vorbis +flac pam vp8_vaapi +flashsv pbm vp9_qsv +flashsv2 pcm_alaw vp9_vaapi +flv pcm_bluray wavpack +g723_1 pcm_dvd wbmp +gif pcm_f32be webvtt +h261 pcm_f32le wmav1 +h263 pcm_f64be wmav2 +h263p pcm_f64le wmv1 +h264_amf pcm_mulaw wmv2 +h264_d3d12va pcm_s16be wrapped_avframe +h264_mf pcm_s16be_planar xbm +h264_nvenc pcm_s16le xface +h264_qsv pcm_s16le_planar xsub +h264_vaapi pcm_s24be xwd +h264_vulkan pcm_s24daud y41p +hap pcm_s24le yuv4 +hdr pcm_s24le_planar zlib +hevc_amf pcm_s32be zmbv +hevc_d3d12va pcm_s32le +hevc_mf pcm_s32le_planar + +Enabled hwaccels: +av1_d3d11va hevc_dxva2 vc1_dxva2 +av1_d3d11va2 hevc_nvdec vc1_nvdec +av1_d3d12va hevc_vaapi vc1_vaapi +av1_dxva2 hevc_vulkan vp8_nvdec +av1_nvdec mjpeg_nvdec vp8_vaapi +av1_vaapi mjpeg_vaapi vp9_d3d11va +av1_vulkan mpeg1_nvdec vp9_d3d11va2 +dpx_vulkan mpeg2_d3d11va vp9_d3d12va +ffv1_vulkan mpeg2_d3d11va2 vp9_dxva2 +h263_vaapi mpeg2_d3d12va vp9_nvdec +h264_d3d11va mpeg2_dxva2 vp9_vaapi +h264_d3d11va2 mpeg2_nvdec vp9_vulkan +h264_d3d12va mpeg2_vaapi vvc_vaapi +h264_dxva2 mpeg4_nvdec wmv3_d3d11va +h264_nvdec mpeg4_vaapi wmv3_d3d11va2 +h264_vaapi prores_raw_vulkan wmv3_d3d12va +h264_vulkan prores_vulkan wmv3_dxva2 +hevc_d3d11va vc1_d3d11va wmv3_nvdec +hevc_d3d11va2 vc1_d3d11va2 wmv3_vaapi +hevc_d3d12va vc1_d3d12va + +Enabled parsers: +aac dvdsub mpegaudio +aac_latm evc mpegvideo +ac3 ffv1 opus +adx flac png +ahx ftr pnm +amr g723_1 prores +apv g729 prores_raw +av1 gif qoi +avs2 gsm rv34 +avs3 h261 sbc +bmp h263 sipr +cavsvideo h264 tak +cook hdr vc1 +cri hevc vorbis +dca ipu vp3 +dirac jpeg2000 vp8 +dnxhd jpegxl vp9 +dnxuc jpegxs vvc +dolby_e lcevc webp +dpx misc4 xbm +dvaudio mjpeg xma +dvbsub mlp xwd +dvd_nav mpeg4video + +Enabled demuxers: +aa ico pcm_f64be +aac idcin pcm_f64le +aax idf pcm_mulaw +ac3 iff pcm_s16be +ac4 ifv pcm_s16le +ace ilbc pcm_s24be +acm image2 pcm_s24le +act image2_alias_pix pcm_s32be +adf image2_brender_pix pcm_s32le +adp image2pipe pcm_s8 +ads image_bmp_pipe pcm_u16be +adx image_cri_pipe pcm_u16le +aea image_dds_pipe pcm_u24be +afc image_dpx_pipe pcm_u24le +aiff image_exr_pipe pcm_u32be +aix image_gem_pipe pcm_u32le +alp image_gif_pipe pcm_u8 +amr image_hdr_pipe pcm_vidc +amrnb image_j2k_pipe pdv +amrwb image_jpeg_pipe pjs +anm image_jpegls_pipe pmp +apac image_jpegxl_pipe pp_bnk +apc image_jpegxs_pipe pva +ape image_pam_pipe pvf +apm image_pbm_pipe qcp +apng image_pcx_pipe qoa +aptx image_pfm_pipe r3d +aptx_hd image_pgm_pipe rawvideo +apv image_pgmyuv_pipe rcwt +aqtitle image_pgx_pipe realtext +argo_asf image_phm_pipe redspark +argo_brp image_photocd_pipe rka +argo_cvg image_pictor_pipe rl2 +asf image_png_pipe rm +asf_o image_ppm_pipe roq +ass image_psd_pipe rpl +ast image_qdraw_pipe rsd +au image_qoi_pipe rso +av1 image_sgi_pipe rtp +avi image_sunrast_pipe rtsp +avisynth image_svg_pipe s337m +avr image_tiff_pipe sami +avs image_vbn_pipe sap +avs2 image_webp_pipe sbc +avs3 image_xbm_pipe sbg +bethsoftvid image_xpm_pipe scc +bfi image_xwd_pipe scd +bfstm imf sdns +bink ingenient sdp +binka ipmovie sdr2 +bintext ipu sds +bit ircam sdx +bitpacked iss segafilm +bmv iv8 ser +boa ivf sga +bonk ivr shorten +brstm jacosub siff +c93 jpegxl_anim simbiosis_imx +caf jv sln +cavsvideo kux smacker +cdg kvag smjpeg +cdxl laf smush +cine lc3 sol +codec2 libgme sox +codec2raw libmodplug spdif +concat libopenmpt srt +dash live_flv stl +data lmlm4 str +daud loas subviewer +dcstr lrc subviewer1 +derf luodat sup +dfa lvf svag +dfpwm lxf svs +dhav m4v swf +dirac matroska tak +dnxhd mca tedcaptions +dsf mcc thp +dsicin mgsts threedostr +dss microdvd tiertexseq +dts mjpeg tmv +dtshd mjpeg_2000 truehd +dv mlp tta +dvbsub mlv tty +dvbtxt mm txd +dvdvideo mmf ty +dxa mods usm +ea moflex v210 +ea_cdata mov v210x +eac3 mp3 vag +epaf mpc vc1 +evc mpc8 vc1t +ffmetadata mpegps vividas +filmstrip mpegts vivo +fits mpegtsraw vmd +flac mpegvideo vobsub +flic mpjpeg voc +flv mpl2 vpk +fourxm mpsub vplayer +frm msf vqf +fsb msnwc_tcp vvc +fwse msp w64 +g722 mtaf wady +g723_1 mtv wav +g726 musx wavarc +g726le mv wc3 +g728 mvi webm_dash_manifest +g729 mxf webvtt +gdv mxg wsaud +genh nc wsd +gif nistsphere wsvqa +gsm nsp wtv +gxf nsv wv +h261 nut wve +h263 nuv xa +h264 obu xbin +hca ogg xmd +hcom oma xmv +hevc osq xvag +hls paf xwma +hnm pcm_alaw yop +hxvs pcm_f32be yuv4mpegpipe +iamf pcm_f32le + +Enabled muxers: +a64 h263 pcm_s24be +ac3 h264 pcm_s24le +ac4 hash pcm_s32be +adts hds pcm_s32le +adx hevc pcm_s8 +aea hls pcm_u16be +aiff iamf pcm_u16le +alp ico pcm_u24be +amr ilbc pcm_u24le +amv image2 pcm_u32be +apm image2pipe pcm_u32le +apng ipod pcm_u8 +aptx ircam pcm_vidc +aptx_hd ismv pdv +apv ivf psp +argo_asf jacosub rawvideo +argo_cvg kvag rcwt +asf latm rm +asf_stream lc3 roq +ass lrc rso +ast m4v rtp +au matroska rtp_mpegts +avi matroska_audio rtsp +avif mcc sap +avm2 md5 sbc +avs2 microdvd scc +avs3 mjpeg segafilm +bit mkvtimestamp_v2 segment +caf mlp smjpeg +cavsvideo mmf smoothstreaming +chromaprint mov sox +codec2 mp2 spdif +codec2raw mp3 spx +crc mp4 srt +dash mpeg1system stream_segment +data mpeg1vcd streamhash +daud mpeg1video sup +dfpwm mpeg2dvd swf +dirac mpeg2svcd tee +dnxhd mpeg2video tg2 +dts mpeg2vob tgp +dv mpegts truehd +eac3 mpjpeg tta +evc mxf ttml +f4v mxf_d10 uncodedframecrc +ffmetadata mxf_opatom vc1 +fifo null vc1t +filmstrip nut voc +fits obu vvc +flac oga w64 +flv ogg wav +framecrc ogv webm +framehash oma webm_chunk +framemd5 opus webm_dash_manifest +g722 pcm_alaw webp +g723_1 pcm_f32be webvtt +g726 pcm_f32le whip +g726le pcm_f64be wsaud +gif pcm_f64le wtv +gsm pcm_mulaw wv +gxf pcm_s16be yuv4mpegpipe +h261 pcm_s16le + +Enabled protocols: +async http rtmp +bluray httpproxy rtmpe +cache https rtmps +concat icecast rtmpt +concatf ipfs_gateway rtmpte +crypto ipns_gateway rtmpts +data librist rtp +dtls libsrt srtp +fd libssh subfile +ffrtmpcrypt libzmq tcp +ffrtmphttp md5 tee +file mmsh tls +ftp mmst udp +gopher pipe udplite +gophers prompeg + +Enabled filters: +a3dscope deconvolve perms +aap dedot perspective +abench deesser phase +abitscope deflate photosensitivity +acompressor deflicker pixdesctest +acontrast deinterlace_d3d12 pixelize +acopy deinterlace_qsv pixscope +acrossfade deinterlace_vaapi pp7 +acrossover dejudder premultiply +acrusher delogo premultiply_dynamic +acue denoise_vaapi prewitt +addroi deshake prewitt_opencl +adeclick deshake_opencl procamp_vaapi +adeclip despill program_opencl +adecorrelate detelecine pseudocolor +adelay dialoguenhance psnr +adenorm dilation pullup +aderivative dilation_opencl qp +adrawgraph displace qrencode +adrc doubleweave qrencodesrc +adynamicequalizer drawbox quirc +adynamicsmooth drawbox_vaapi random +aecho drawgraph readeia608 +aemphasis drawgrid readvitc +aeval drawtext realtime +aevalsrc drawvg remap +aexciter drmeter remap_opencl +afade dynaudnorm removegrain +afdelaysrc earwax removelogo +afftdn ebur128 repeatfields +afftfilt edgedetect replaygain +afir elbg reverse +afireqsrc entropy rgbashift +afirsrc epx rgbtestsrc +aformat eq roberts +afreqshift equalizer roberts_opencl +afwtdn erosion rotate +agate erosion_opencl rubberband +agraphmonitor estdif sab +ahistogram exposure scale +aiir extractplanes scale2ref +aintegral extrastereo scale_cuda +ainterleave fade scale_d3d11 +alatency feedback scale_d3d12 +alimiter fftdnoiz scale_qsv +allpass fftfilt scale_vaapi +allrgb field scale_vulkan +allyuv fieldhint scdet +aloop fieldmatch scdet_vulkan +alphaextract fieldorder scharr +alphamerge fillborders scroll +amerge find_rect segment +ametadata firequalizer select +amf_capture flanger selectivecolor +amix flip_vulkan sendcmd +amovie flite separatefields +amplify floodfill setdar +amultiply format setfield +anequalizer fps setparams +anlmdn framepack setpts +anlmf framerate setrange +anlms framestep setsar +anoisesrc frc_amf settb +anull freezedetect sharpness_vaapi +anullsink freezeframes shear +anullsrc frei0r showcqt +apad frei0r_src showcwt +aperms fspp showfreqs +aphasemeter fsync showinfo +aphaser gblur showpalette +aphaseshift gblur_vulkan showspatial +apsnr geq showspectrum +apsyclip gfxcapture showspectrumpic +apulsator gradfun showvolume +arealtime gradients showwaves +aresample graphmonitor showwavespic +areverse grayworld shuffleframes +arls greyedge shufflepixels +arnndn guided shuffleplanes +asdr haas sidechaincompress +asegment haldclut sidechaingate +aselect haldclutsrc sidedata +asendcmd hdcd sierpinski +asetnsamples headphone signalstats +asetpts hflip signature +asetrate hflip_vulkan silencedetect +asettb highpass silenceremove +ashowinfo highshelf sinc +asidedata hilbert sine +asisdr histeq siti +asoftclip histogram smartblur +aspectralstats hqdn3d smptebars +asplit hqx smptehdbars +ass hstack sobel +astats hstack_qsv sobel_opencl +astreamselect hstack_vaapi sofalizer +asubboost hsvhold spectrumsynth +asubcut hsvkey speechnorm +asupercut hue split +asuperpass huesaturation spp +asuperstop hwdownload sr_amf +atadenoise hwmap ssim +atempo hwupload ssim360 +atilt hwupload_cuda stereo3d +atrim hysteresis stereotools +avectorscope iccdetect stereowiden +avgblur iccgen streamselect +avgblur_opencl identity subtitles +avgblur_vulkan idet super2xsai +avsynctest il superequalizer +axcorrelate inflate surround +azmq interlace swaprect +backgroundkey interlace_vulkan swapuv +bandpass interleave tblend +bandreject join telecine +bass kerndeint testsrc +bbox kirsch testsrc2 +bench ladspa thistogram +bilateral lagfun threshold +bilateral_cuda latency thumbnail +biquad lenscorrection thumbnail_cuda +bitplanenoise lensfun tile +blackdetect libplacebo tiltandshift +blackdetect_vulkan libvmaf tiltshelf +blackframe life tinterlace +blend limitdiff tlut2 +blend_vulkan limiter tmedian +blockdetect loop tmidequalizer +blurdetect loudnorm tmix +bm3d lowpass tonemap +boxblur lowshelf tonemap_opencl +boxblur_opencl lumakey tonemap_vaapi +bs2b lut tpad +bwdif lut1d transpose +bwdif_cuda lut2 transpose_cuda +bwdif_vulkan lut3d transpose_opencl +cas lutrgb transpose_vaapi +ccrepack lutyuv transpose_vulkan +cellauto mandelbrot treble +channelmap maskedclamp tremolo +channelsplit maskedmax trim +chorus maskedmerge unpremultiply +chromaber_vulkan maskedmin unsharp +chromahold maskedthreshold unsharp_opencl +chromakey maskfun untile +chromakey_cuda mcdeint uspp +chromanr mcompand v360 +chromashift median v360_vulkan +ciescope mergeplanes vaguedenoiser +codecview mestimate varblur +color mestimate_d3d12 vectorscope +color_vulkan metadata vflip +colorbalance midequalizer vflip_vulkan +colorchannelmixer minterpolate vfrdet +colorchart mix vibrance +colorcontrast monochrome vibrato +colorcorrect morpho vidstabdetect +colordetect movie vidstabtransform +colorhold mpdecimate vif +colorize mptestsrc vignette +colorkey msad virtualbass +colorkey_opencl multiply vmafmotion +colorlevels negate volume +colormap nlmeans volumedetect +colormatrix nlmeans_opencl vpp_amf +colorspace nlmeans_vulkan vpp_qsv +colorspace_cuda nnedi vstack +colorspectrum noformat vstack_qsv +colortemperature noise vstack_vaapi +compand normalize w3fdif +compensationdelay null waveform +concat nullsink weave +convolution nullsrc whisper +convolution_opencl openclsrc xbr +convolve oscilloscope xcorrelate +copy overlay xfade +corr overlay_cuda xfade_opencl +cover_rect overlay_opencl xfade_vulkan +crop overlay_qsv xmedian +cropdetect overlay_vaapi xpsnr +crossfeed overlay_vulkan xstack +crystalizer owdenoise xstack_qsv +cue pad xstack_vaapi +curves pad_cuda yadif +datascope pad_opencl yadif_cuda +dblur pad_vaapi yaepblur +dcshift pal100bars yuvtestsrc +dctdnoiz pal75bars zmq +ddagrab palettegen zoneplate +deband paletteuse zoompan +deblock pan zscale +decimate perlin + +Enabled bsfs: +aac_adtstoasc h264_metadata pcm_rechunk +ahx_to_mp2 h264_mp4toannexb pgs_frame_merge +apv_metadata h264_redundant_pps prores_metadata +av1_frame_merge hapqa_extract remove_extradata +av1_frame_split hevc_metadata setts +av1_metadata hevc_mp4toannexb showinfo +chomp imx_dump_header smpte436m_to_eia608 +dca_core lcevc_metadata text2movsub +dovi_rpu media100_to_mjpegb trace_headers +dts2pts mjpeg2jpeg truehd_core +dump_extradata mjpega_dump_header vp9_metadata +dv_error_marker mov2textsub vp9_raw_reorder +eac3_core mpeg2_metadata vp9_superframe +eia608_to_smpte436m mpeg4_unpack_bframes vp9_superframe_split +evc_frame_merge noise vvc_metadata +extract_extradata null vvc_mp4toannexb +filter_units opus_metadata + +Enabled indevs: +dshow lavfi openal +gdigrab libcdio vfwcap + +Enabled outdevs: +caca + +git-full external libraries' versions: + +AMF v1.5.2 +aom v3.13.3-439-g32c4161373 +aribcaption 1.1.1 +AviSynthPlus v3.7.5-303-g31b8b167 +bs2b 3.1.0 +cairo 1.18.5 +chromaprint 1.6.0 +codec2 1.2.0-108-g310777b1 +dav1d 1.5.3-42-g51b67010 +davs2 1.7-1-gb41cf11 +dvdnav 7.0.0-1-gcf11277 +dvdread 7.0.1-55-ge4d9a03 +ffnvcodec n13.0.19.0-3-g33a9ede +flite v2.2-55-g6c9f20d +frei0r v3.1.3-10-gdfc89ab +gsm 1.0.24 +ladspa-sdk 1.17 +lame 3.100 +lc3 1.1.3 +lcms2 2.16 +lensfun v0.3.95-1965-g01e64b74 +libcdio-paranoia 10.2 +libgme 0.6.6 +libilbc v3.0.4-346-g6adb26d4a4 +libjxl v0.11-snapshot-577-gc0667f8e +libopencore-amrnb 0.1.6 +libopencore-amrwb 0.1.6 +libplacebo v7.360.0-42-gc43baa7 +libsoxr 0.1.3 +libssh 0.12.0 +libtheora v1.2.0 +libwebp v1.6.0-179-ged0fa1c +openal-soft latest +openapv v0.2.1.3-fix-1-g27d4d71 +openmpt libopenmpt-0.6.28-16-gfe8c9f3f +opus v1.6.1-19-gf8f99516 +qrencode 4.1.1 +quirc 1.2 +rav1e p20250624-3-g564ae3b +rist 0.2.14 +rubberband v1.8.1 +SDL release-2.32.0-199-g4b69833bc +shaderc v2026.2-8-g7c5f360 +shine 3.1.1 +snappy 1.2.2 +speex Speex-1.2.1-51-g0589522 +srt v1.5.5-1-g8e68635 +SVT-AV1 v4.1.0-101-ge68533ea +SVT-JPEG-XS v0.9.0-50-gc36f29a +twolame 0.4.0 +uavs3d v1.1-50-g0e20d2c +VAAPI 2.24.0. +vidstab v1.1.1-24-g92bc0b0 +vmaf v3.1.0-119-g4e469601 +vo-amrwbenc 0.1.3 +vorbis v1.3.7-24-g68a7fc22 +VPL 2.16 +vpx v1.16.0-118-gf38b9deb0 +vulkan-loader v1.4.351-2-gd34e103 +vvenc v1.14.0-118-gb1bc3bd +whisper.cpp 1.8.4 +x264 v0.165.3223 +x265 4.2-6-g7b3d1f5 +xavs2 1.4 +xevd 0.5.0 +xeve 0.5.1 +xvid v1.3.7 +zeromq 4.3.5 +zimg release-3.0.6-218-gfa52dee +zvbi v0.2.44-4-g41477c9 + diff --git a/git/.gitconfig b/git/.gitconfig new file mode 100644 index 0000000000000000000000000000000000000000..7cedd07997b2e30132b1e82ab3f95f3d2d3bf9fb --- /dev/null +++ b/git/.gitconfig @@ -0,0 +1,5 @@ +[core] + longpaths = true + autocrlf = true +[init] + defaultBranch = main diff --git a/git/LICENSE.txt b/git/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..536e55524db72bd2acf175208aef4f3dfc148d42 --- /dev/null +++ b/git/LICENSE.txt @@ -0,0 +1,360 @@ + + Note that the only valid version of the GPL as far as this project + is concerned is _this_ particular version of the license (ie v2, not + v2.2 or v3.x or whatever), unless explicitly otherwise stated. + + HOWEVER, in order to allow a migration to GPLv3 if that seems like + a good idea, I also ask that people involved with the project make + their preferences known. In particular, if you trust me to make that + decision, you might note so in your copyright message, ie something + like + + This file is licensed under the GPL v2, or a later version + at the discretion of Linus. + + might avoid issues. But we can also just decide to synchronize and + contact all copyright holders on record if/when the occasion arises. + + Linus Torvalds + +---------------------------------------- + + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) 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 +this service 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 make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. 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. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +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 +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the 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 a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE 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. + + 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 +convey 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 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 Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision 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, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This 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. diff --git a/git/README.portable b/git/README.portable new file mode 100644 index 0000000000000000000000000000000000000000..7993fd6035fa36a38235040fc835aeb971bc16ae --- /dev/null +++ b/git/README.portable @@ -0,0 +1,106 @@ +README.portable +======================= + +This version of Git for Windows is portable, i.e. does not need to +be installed. It will run from any directory you place it in, even +from a USB thumbdrive. It will not write permanent entries into the +Windows registry. It does not need administrator privileges to "install". + + +Installation +------------ + +This package is contained in a 7-zip archive with a file name of the form +'PortableGit-.7z.exe'. It is a self-extracting archive: +you can (double-)click it and it will ask for the desired target directory +(which defaults to C:\Program Files\Git). You may change that as needed or +desired. Your user account needs write access to the selected directory. +(You can move that directory with all its contents to a different place or +computer at any time should you later desire so). + +*NOTE*: if you decide to unpack the archive using 7-Zip manually, you must +run the `post-install.bat` script. Git will not run correctly +otherwise. + +Functional differences to the non-portable Git for Windows +---------------------------------------------------------- + +This version does not offer you the convenient right-click context menu +entries "Git GUI Here" and "Git Bash Here", because these would require +to add entries into the Windows registry. + + +Warning +------- + +Since this portable package does not modify any Windows %path% +variables, it is not possible to run the git.exe and gitk.exe files +directly. Start the Git Bash or Git Cmd instead, or add the cmd/ folder +to your %path%. + + +How to start using PortableGit +------------------------------ + +If you are comfortable with a Unix-like shell, just launch 'git-bash.exe'. + +If not, just launch 'git-cmd.exe'. + +Alternatively, you can execute these commands to modify the %path% +variable temporarily: + + set gitdir=c:\portablegit + set path=%gitdir%\cmd;%path% + +Adjust the 'gitdir' according to your setup. As long as you do not +close the command window, you can now simply type "git" or "gitk" to +really call "c:\portablegit\cmd\git.exe" or "c:\portablegit\cmd\gitk.exe". + +By default, git-cmd and git-bash use the directory they were started from as +the working directory when run. You can override this by passing --cd-to-home +to them, which will set the user's home directory as the working directory (as +if Git for Windows was installed). + +In addition, if you set the HOME environment variable (either permanently or +for the current session only) you can make Git store and use the configuration +files in the directory specified in that variable. And if you specify +--cd-to-home, git-bash and git-cmd will use that as the working directory when +launched, too. For example: + + set HOME=%cd%/home + git --cd-to-home +will use the relative directory named home (%cd% specifies the current +directory). + +Quick start +----------- + +Start configuring git with your personal settings: + git config --global user.name "Joe Sixpack" + git config --global user.email joe.sixpack@g_mail.com + +Start using git: + git --help + + +How to change %path% permanently +-------------------------------- + +You may also want to make the modification to the %path% variable a +permanent one. The %path% variable may be changed: + +* either on a System level (for all users in the lower pane), if you are + an Administrator +* or for your own user account only (in the upper pane). + +To change the %path% variable permanently: + +* right-click "My Computer", +* select "Properties", +* open "Advanced", +* click "Environment Variables", +* highlight the "Path" variable, +* click "Edit" (either in upper or in lower pane), +* add your specific path to front of "Variable value" field, separated + by a semicolon from the existing entry. + diff --git a/git/post-install.bat b/git/post-install.bat new file mode 100644 index 0000000000000000000000000000000000000000..1f08dea4d5058e8ce1004099d97a9958a7de7b15 --- /dev/null +++ b/git/post-install.bat @@ -0,0 +1,53 @@ +@REM This script is intended to be run after installation of Git for Windows +@REM (including the portable version) + +@REM If run manually, it should be run via +@REM git-bash.exe --no-needs-console --hide --no-cd --command=post-install.bat +@REM to hide the console. + +@REM Change to the directory in which this script lives. +@REM https://technet.microsoft.com/en-us/library/bb490909.aspx says: +@REM ~dpI Expands I to a drive letter and path only. +@REM ~fI Expands I to a fully qualified path name. +@FOR /F "delims=" %%D IN ("%~dp0") DO @CD %%~fD + +@SET /A "version=0" & FOR /F "tokens=2 delims=[]" %%i IN ('"VER"') DO @( + @FOR /F "tokens=2 delims=. " %%v IN ("%%~i") DO @( + @SET /A "version=%%~v + 0" + ) +) + +@REM If this is a 32-bit Git for Windows, adjust the DLL address ranges. +@REM We cannot use %PROCESSOR_ARCHITECTURE% for this test because it is +@REM allowed to install a 32-bit Git for Windows into a 64-bit system. +@IF EXIST mingw32\bin\git.exe @( + @REM We need to rebase just to make sure that it still works even with + @REM 32-bit Windows 10 + @IF %version% GEQ 10 @( + @REM We copy `rebase.exe` because it links to `msys-2.0.dll` + @REM (and @REM thus prevents modifying it). It is okay to + @REM execute `rebase.exe`, though, because the DLL base address + @REM problems only really show when other processes are + @REM `fork()`ed and `rebase.exe` does no such thing. + @IF NOT EXIST bin\rebase.exe @( + @IF NOT EXIST bin @MKDIR bin + @COPY usr\bin\rebase.exe bin\rebase.exe + ) + @IF NOT EXIST bin\msys-2.0.dll @( + @COPY usr\bin\msys-2.0.dll bin\msys-2.0.dll + ) + @bin\rebase.exe -b 0x64000000 usr\bin\msys-2.0.dll + ) + + usr\bin\dash.exe -c '/usr/bin/dash usr/bin/rebaseall -p' +) + +@echo "running post-install" +@REM Run the post-install scripts +@usr\bin\bash.exe --norc -c "export PATH=/usr/bin:$PATH; export SYSCONFDIR=/etc; for p in $(export LC_COLLATE=C; echo /etc/post-install/*.post); do test -e \"$p\" && . \"$p\"; done" + +@REM Unset environment variables set by this script +@SET "version=" + +@REM Remove this script +@DEL post-install.bat diff --git a/git/usr/share/perl5/core_perl/App/Cpan.pm b/git/usr/share/perl5/core_perl/App/Cpan.pm new file mode 100644 index 0000000000000000000000000000000000000000..6358e82a03695c47779c168e17b5079ca26633f1 --- /dev/null +++ b/git/usr/share/perl5/core_perl/App/Cpan.pm @@ -0,0 +1,1719 @@ +package App::Cpan; + +use strict; +use warnings; +use vars qw($VERSION); + +use if $] < 5.008 => 'IO::Scalar'; + +$VERSION = '1.678'; + +=head1 NAME + +App::Cpan - easily interact with CPAN from the command line + +=head1 SYNOPSIS + + # with arguments and no switches, installs specified modules + cpan module_name [ module_name ... ] + + # with switches, installs modules with extra behavior + cpan [-cfFimtTw] module_name [ module_name ... ] + + # use local::lib + cpan -I module_name [ module_name ... ] + + # one time mirror override for faster mirrors + cpan -p ... + + # with just the dot, install from the distribution in the + # current directory + cpan . + + # without arguments, starts CPAN.pm shell + cpan + + # without arguments, but some switches + cpan [-ahpruvACDLOPX] + +=head1 DESCRIPTION + +This script provides a command interface (not a shell) to CPAN. At the +moment it uses CPAN.pm to do the work, but it is not a one-shot command +runner for CPAN.pm. + +=head2 Options + +=over 4 + +=item -a + +Creates a CPAN.pm autobundle with CPAN::Shell->autobundle. + +=item -A module [ module ... ] + +Shows the primary maintainers for the specified modules. + +=item -c module + +Runs a `make clean` in the specified module's directories. + +=item -C module [ module ... ] + +Show the F files for the specified modules + +=item -D module [ module ... ] + +Show the module details. This prints one line for each out-of-date module +(meaning, modules locally installed but have newer versions on CPAN). +Each line has three columns: module name, local version, and CPAN +version. + +=item -f + +Force the specified action, when it normally would have failed. Use this +to install a module even if its tests fail. When you use this option, +-i is not optional for installing a module when you need to force it: + + % cpan -f -i Module::Foo + +=item -F + +Turn off CPAN.pm's attempts to lock anything. You should be careful with +this since you might end up with multiple scripts trying to muck in the +same directory. This isn't so much of a concern if you're loading a special +config with C<-j>, and that config sets up its own work directories. + +=item -g module [ module ... ] + +Downloads to the current directory the latest distribution of the module. + +=item -G module [ module ... ] + +UNIMPLEMENTED + +Download to the current directory the latest distribution of the +modules, unpack each distribution, and create a git repository for each +distribution. + +If you want this feature, check out Yanick Champoux's C +distribution. + +=item -h + +Print a help message and exit. When you specify C<-h>, it ignores all +of the other options and arguments. + +=item -i module [ module ... ] + +Install the specified modules. With no other switches, this switch +is implied. + +=item -I + +Load C (think like C<-I> for loading lib paths). Too bad +C<-l> was already taken. + +=item -j Config.pm + +Load the file that has the CPAN configuration data. This should have the +same format as the standard F file, which defines +C<$CPAN::Config> as an anonymous hash. + +If the file does not exist, C dies. + +=item -J + +Dump the configuration in the same format that CPAN.pm uses. This is useful +for checking the configuration as well as using the dump as a starting point +for a new, custom configuration. + +=item -l + +List all installed modules with their versions + +=item -L author [ author ... ] + +List the modules by the specified authors. + +=item -m + +Make the specified modules. + +=item -M mirror1,mirror2,... + +A comma-separated list of mirrors to use for just this run. The C<-P> +option can find them for you automatically. + +=item -n + +Do a dry run, but don't actually install anything. (unimplemented) + +=item -O + +Show the out-of-date modules. + +=item -p + +Ping the configured mirrors and print a report + +=item -P + +Find the best mirrors you could be using and use them for the current +session. + +=item -r + +Recompiles dynamically loaded modules with CPAN::Shell->recompile. + +=item -s + +Drop in the CPAN.pm shell. This command does this automatically if you don't +specify any arguments. + +=item -t module [ module ... ] + +Run a `make test` on the specified modules. + +=item -T + +Do not test modules. Simply install them. + +=item -u + +Upgrade all installed modules. Blindly doing this can really break things, +so keep a backup. + +=item -v + +Print the script version and CPAN.pm version then exit. + +=item -V + +Print detailed information about the cpan client. + +=item -w + +UNIMPLEMENTED + +Turn on cpan warnings. This checks various things, like directory permissions, +and tells you about problems you might have. + +=item -x module [ module ... ] + +Find close matches to the named modules that you think you might have +mistyped. This requires the optional installation of Text::Levenshtein or +Text::Levenshtein::Damerau. + +=item -X + +Dump all the namespaces to standard output. + +=back + +=head2 Examples + + # print a help message + cpan -h + + # print the version numbers + cpan -v + + # create an autobundle + cpan -a + + # recompile modules + cpan -r + + # upgrade all installed modules + cpan -u + + # install modules ( sole -i is optional ) + cpan -i Netscape::Booksmarks Business::ISBN + + # force install modules ( must use -i ) + cpan -fi CGI::Minimal URI + + # install modules but without testing them + cpan -Ti CGI::Minimal URI + +=head2 Environment variables + +There are several components in CPAN.pm that use environment variables. +The build tools, L and L use some, +while others matter to the levels above them. Some of these are specified +by the Perl Toolchain Gang: + +Lancaster Consensus: L + +Oslo Consensus: L + +=over 4 + +=item NONINTERACTIVE_TESTING + +Assume no one is paying attention and skips prompts for distributions +that do that correctly. C sets this to C<1> unless it already +has a value (even if that value is false). + +=item PERL_MM_USE_DEFAULT + +Use the default answer for a prompted questions. C sets this +to C<1> unless it already has a value (even if that value is false). + +=item CPAN_OPTS + +As with C, a string of additional C options to +add to those you specify on the command line. + +=item CPANSCRIPT_LOGLEVEL + +The log level to use, with either the embedded, minimal logger or +L if it is installed. Possible values are the same as +the C levels: C, C, C, C, +C, and C. The default is C. + +=item GIT_COMMAND + +The path to the C binary to use for the Git features. The default +is C. + +=back + +=head2 Methods + +=over 4 + +=cut + +use autouse Carp => qw(carp croak cluck); +use CPAN 1.80 (); # needs no test +use Config; +use autouse Cwd => qw(cwd); +use autouse 'Data::Dumper' => qw(Dumper); +use File::Spec::Functions qw(catfile file_name_is_absolute rel2abs); +use File::Basename; +use Getopt::Std; + +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# Internal constants +use constant TRUE => 1; +use constant FALSE => 0; + + +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# The return values +use constant HEY_IT_WORKED => 0; +use constant I_DONT_KNOW_WHAT_HAPPENED => 1; # 0b0000_0001 +use constant ITS_NOT_MY_FAULT => 2; +use constant THE_PROGRAMMERS_AN_IDIOT => 4; +use constant A_MODULE_FAILED_TO_INSTALL => 8; + + +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# set up the order of options that we layer over CPAN::Shell +BEGIN { # most of this should be in methods +use vars qw( @META_OPTIONS $Default %CPAN_METHODS @CPAN_OPTIONS @option_order + %Method_table %Method_table_index ); + +@META_OPTIONS = qw( h v V I g G M: C A D O l L a r p P j: J w x X ); + +$Default = 'default'; + +%CPAN_METHODS = ( # map switches to method names in CPAN::Shell + $Default => 'install', + 'c' => 'clean', + 'f' => 'force', + 'i' => 'install', + 'm' => 'make', + 't' => 'test', + 'u' => 'upgrade', + 'T' => 'notest', + 's' => 'shell', + ); +@CPAN_OPTIONS = grep { $_ ne $Default } sort keys %CPAN_METHODS; + +@option_order = ( @META_OPTIONS, @CPAN_OPTIONS ); + + +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# map switches to the subroutines in this script, along with other information. +# use this stuff instead of hard-coded indices and values +sub NO_ARGS () { 0 } +sub ARGS () { 1 } +sub GOOD_EXIT () { 0 } + +%Method_table = ( +# key => [ sub ref, takes args?, exit value, description ] + + # options that do their thing first, then exit + h => [ \&_print_help, NO_ARGS, GOOD_EXIT, 'Printing help' ], + v => [ \&_print_version, NO_ARGS, GOOD_EXIT, 'Printing version' ], + V => [ \&_print_details, NO_ARGS, GOOD_EXIT, 'Printing detailed version' ], + X => [ \&_list_all_namespaces, NO_ARGS, GOOD_EXIT, 'Listing all namespaces' ], + + # options that affect other options + j => [ \&_load_config, ARGS, GOOD_EXIT, 'Use specified config file' ], + J => [ \&_dump_config, NO_ARGS, GOOD_EXIT, 'Dump configuration to stdout' ], + F => [ \&_lock_lobotomy, NO_ARGS, GOOD_EXIT, 'Turn off CPAN.pm lock files' ], + I => [ \&_load_local_lib, NO_ARGS, GOOD_EXIT, 'Loading local::lib' ], + M => [ \&_use_these_mirrors, ARGS, GOOD_EXIT, 'Setting per session mirrors' ], + P => [ \&_find_good_mirrors, NO_ARGS, GOOD_EXIT, 'Finding good mirrors' ], + w => [ \&_turn_on_warnings, NO_ARGS, GOOD_EXIT, 'Turning on warnings' ], + + # options that do their one thing + g => [ \&_download, ARGS, GOOD_EXIT, 'Download the latest distro' ], + G => [ \&_gitify, ARGS, GOOD_EXIT, 'Down and gitify the latest distro' ], + + C => [ \&_show_Changes, ARGS, GOOD_EXIT, 'Showing Changes file' ], + A => [ \&_show_Author, ARGS, GOOD_EXIT, 'Showing Author' ], + D => [ \&_show_Details, ARGS, GOOD_EXIT, 'Showing Details' ], + O => [ \&_show_out_of_date, NO_ARGS, GOOD_EXIT, 'Showing Out of date' ], + l => [ \&_list_all_mods, NO_ARGS, GOOD_EXIT, 'Listing all modules' ], + + L => [ \&_show_author_mods, ARGS, GOOD_EXIT, 'Showing author mods' ], + a => [ \&_create_autobundle, NO_ARGS, GOOD_EXIT, 'Creating autobundle' ], + p => [ \&_ping_mirrors, NO_ARGS, GOOD_EXIT, 'Pinging mirrors' ], + + r => [ \&_recompile, NO_ARGS, GOOD_EXIT, 'Recompiling' ], + u => [ \&_upgrade, NO_ARGS, GOOD_EXIT, 'Running `make test`' ], + 's' => [ \&_shell, NO_ARGS, GOOD_EXIT, 'Drop into the CPAN.pm shell' ], + + 'x' => [ \&_guess_namespace, ARGS, GOOD_EXIT, 'Guessing namespaces' ], + c => [ \&_default, ARGS, GOOD_EXIT, 'Running `make clean`' ], + f => [ \&_default, ARGS, GOOD_EXIT, 'Installing with force' ], + i => [ \&_default, ARGS, GOOD_EXIT, 'Running `make install`' ], + 'm' => [ \&_default, ARGS, GOOD_EXIT, 'Running `make`' ], + t => [ \&_default, ARGS, GOOD_EXIT, 'Running `make test`' ], + T => [ \&_default, ARGS, GOOD_EXIT, 'Installing with notest' ], + ); + +%Method_table_index = ( + code => 0, + takes_args => 1, + exit_value => 2, + description => 3, + ); +} + + +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# finally, do some argument processing + +sub _stupid_interface_hack_for_non_rtfmers + { + no warnings 'uninitialized'; + shift @ARGV if( $ARGV[0] eq 'install' and @ARGV > 1 ) + } + +sub _process_options + { + my %options; + + push @ARGV, grep $_, split /\s+/, $ENV{CPAN_OPTS} || ''; + + # if no arguments, just drop into the shell + if( 0 == @ARGV ) { CPAN::shell(); exit 0 } + elsif (Getopt::Std::getopts( + join( '', @option_order ), \%options )) + { + \%options; + } + else { exit 1 } +} + +sub _process_setup_options + { + my( $class, $options ) = @_; + + if( $options->{j} ) + { + $Method_table{j}[ $Method_table_index{code} ]->( $options->{j} ); + delete $options->{j}; + } + elsif ( ! $options->{h} ) { # h "ignores all of the other options and arguments" + # this is what CPAN.pm would do otherwise + local $CPAN::Be_Silent = 1; + CPAN::HandleConfig->load( + # be_silent => 1, deprecated + write_file => 0, + ); + } + + $class->_turn_off_testing if $options->{T}; + + foreach my $o ( qw(F I w P M) ) + { + next unless exists $options->{$o}; + $Method_table{$o}[ $Method_table_index{code} ]->( $options->{$o} ); + delete $options->{$o}; + } + + if( $options->{o} ) + { + my @pairs = map { [ split /=/, $_, 2 ] } split /,/, $options->{o}; + foreach my $pair ( @pairs ) + { + my( $setting, $value ) = @$pair; + $CPAN::Config->{$setting} = $value; + # $logger->debug( "Setting [$setting] to [$value]" ); + } + delete $options->{o}; + } + + my $option_count = grep { $options->{$_} } @option_order; + no warnings 'uninitialized'; + + # don't count options that imply installation + foreach my $opt ( qw(f T) ) { # don't count force or notest + $option_count -= $options->{$opt}; + } + + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + # if there are no options, set -i (this line fixes RT ticket 16915) + $options->{i}++ unless $option_count; + } + +sub _setup_environment { +# should we override or set defaults? If this were a true interactive +# session, we'd be in the CPAN shell. + +# https://github.com/Perl-Toolchain-Gang/toolchain-site/blob/master/lancaster-consensus.md + $ENV{NONINTERACTIVE_TESTING} = 1 unless defined $ENV{NONINTERACTIVE_TESTING}; + $ENV{PERL_MM_USE_DEFAULT} = 1 unless defined $ENV{PERL_MM_USE_DEFAULT}; + } + +=item run( ARGS ) + +Just do it. + +The C method returns 0 on success and a positive number on +failure. See the section on EXIT CODES for details on the values. + +=cut + +my $logger; + +sub run + { + my( $class, @args ) = @_; + local @ARGV = @args; + my $return_value = HEY_IT_WORKED; # assume that things will work + + $logger = $class->_init_logger; + $logger->debug( "Using logger from @{[ref $logger]}" ); + + $class->_hook_into_CPANpm_report; + $logger->debug( "Hooked into output" ); + + $class->_stupid_interface_hack_for_non_rtfmers; + $logger->debug( "Patched cargo culting" ); + + my $options = $class->_process_options; + $logger->debug( "Options are @{[Dumper($options)]}" ); + + $class->_process_setup_options( $options ); + + $class->_setup_environment( $options ); + + OPTION: foreach my $option ( @option_order ) + { + next unless $options->{$option}; + + my( $sub, $takes_args, $description ) = + map { $Method_table{$option}[ $Method_table_index{$_} ] } + qw( code takes_args description ); + + unless( ref $sub eq ref sub {} ) + { + $return_value = THE_PROGRAMMERS_AN_IDIOT; + last OPTION; + } + + $logger->info( "[$option] $description -- ignoring other arguments" ) + if( @ARGV && ! $takes_args ); + + $return_value = $sub->( \ @ARGV, $options ); + + last; + } + + return $return_value; + } + +my $LEVEL; +{ +package + Local::Null::Logger; # hide from PAUSE + +my @LOGLEVELS = qw(TRACE DEBUG INFO WARN ERROR FATAL); +$LEVEL = uc($ENV{CPANSCRIPT_LOGLEVEL} || 'INFO'); +my %LL = map { $LOGLEVELS[$_] => $_ } 0..$#LOGLEVELS; +unless (defined $LL{$LEVEL}){ + warn "Unsupported loglevel '$LEVEL', setting to INFO"; + $LEVEL = 'INFO'; +} +sub new { bless \ my $x, $_[0] } +sub AUTOLOAD { + my $autoload = our $AUTOLOAD; + $autoload =~ s/.*://; + return if $LL{uc $autoload} < $LL{$LEVEL}; + $CPAN::Frontend->mywarn(">($autoload): $_\n") + for split /[\r\n]+/, $_[1]; +} +sub DESTROY { 1 } +} + +# load a module without searching the default entry for the current +# directory +sub _safe_load_module { + my $name = shift; + + local @INC = @INC; + pop @INC if $INC[-1] eq '.'; + + eval "require $name; 1"; +} + +sub _init_logger + { + my $log4perl_loaded = _safe_load_module("Log::Log4perl"); + + unless( $log4perl_loaded ) + { + print STDOUT "Loading internal logger. Log::Log4perl recommended for better logging\n"; + $logger = Local::Null::Logger->new; + return $logger; + } + + Log::Log4perl::init( \ <<"HERE" ); +log4perl.rootLogger=$LEVEL, A1 +log4perl.appender.A1=Log::Log4perl::Appender::Screen +log4perl.appender.A1.layout=PatternLayout +log4perl.appender.A1.layout.ConversionPattern=%m%n +HERE + + $logger = Log::Log4perl->get_logger( 'App::Cpan' ); + } + +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + +sub _default + { + my( $args, $options ) = @_; + + my $switch = ''; + + # choose the option that we're going to use + # we'll deal with 'f' (force) later, so skip it + foreach my $option ( @CPAN_OPTIONS ) + { + next if ( $option eq 'f' or $option eq 'T' ); + next unless $options->{$option}; + $switch = $option; + last; + } + + # 1. with no switches, but arguments, use the default switch (install) + # 2. with no switches and no args, start the shell + # 3. With a switch but no args, die! These switches need arguments. + if( not $switch and @$args ) { $switch = $Default; } + elsif( not $switch and not @$args ) { return CPAN::shell() } + elsif( $switch and not @$args ) + { die "Nothing to $CPAN_METHODS{$switch}!\n"; } + + # Get and check the method from CPAN::Shell + my $method = $CPAN_METHODS{$switch}; + die "CPAN.pm cannot $method!\n" unless CPAN::Shell->can( $method ); + + # call the CPAN::Shell method, with force or notest if specified + my $action = do { + if( $options->{f} ) { sub { CPAN::Shell->force( $method, @_ ) } } + elsif( $options->{T} ) { sub { CPAN::Shell->notest( $method, @_ ) } } + else { sub { CPAN::Shell->$method( @_ ) } } + }; + + # How do I handle exit codes for multiple arguments? + my @errors = (); + + $options->{x} or _disable_guessers(); + + foreach my $arg ( @$args ) + { + # check the argument and perhaps capture typos + my $module = _expand_module( $arg ) or do { + $logger->error( "Skipping $arg because I couldn't find a matching namespace." ); + next; + }; + + _clear_cpanpm_output(); + $action->( $arg ); + + my $error = _cpanpm_output_indicates_failure(); + push @errors, $error if $error; + } + + return do { + if( @errors ) { $errors[0] } + else { HEY_IT_WORKED } + }; + + } + +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + +=for comment + +CPAN.pm sends all the good stuff either to STDOUT, or to a temp +file if $CPAN::Be_Silent is set. I have to intercept that output +so I can find out what happened. + +=cut + +BEGIN { +my $scalar = ''; + +sub _hook_into_CPANpm_report + { + no warnings 'redefine'; + + *CPAN::Shell::myprint = sub { + my($self,$what) = @_; + $scalar .= $what if defined $what; + $self->print_ornamented($what, + $CPAN::Config->{colorize_print}||'bold blue on_white', + ); + }; + + *CPAN::Shell::mywarn = sub { + my($self,$what) = @_; + $scalar .= $what if defined $what; + $self->print_ornamented($what, + $CPAN::Config->{colorize_warn}||'bold red on_white' + ); + }; + + } + +sub _clear_cpanpm_output { $scalar = '' } + +sub _get_cpanpm_output { $scalar } + +# These are lines I don't care about in CPAN.pm output. If I can +# filter out the informational noise, I have a better chance to +# catch the error signal +my @skip_lines = ( + qr/^\QWarning \(usually harmless\)/, + qr/\bwill not store persistent state\b/, + qr(//hint//), + qr/^\s+reports\s+/, + qr/^Try the command/, + qr/^\s+$/, + qr/^to find objects/, + qr/^\s*Database was generated on/, + qr/^Going to read/, + qr|^\s+i\s+/|, # the i /Foo::Whatever/ line when it doesn't know + ); + +sub _get_cpanpm_last_line + { + my $fh; + + if( $] < 5.008 ) { + $fh = IO::Scalar->new( \ $scalar ); + } + else { + eval q{ open $fh, '<', \\ $scalar; }; + } + + my @lines = <$fh>; + + # This is a bit ugly. Once we examine a line, we have to + # examine the line before it and go through all of the same + # regexes. I could do something fancy, but this works. + REGEXES: { + foreach my $regex ( @skip_lines ) + { + if( $lines[-1] =~ m/$regex/ ) + { + pop @lines; + redo REGEXES; # we have to go through all of them for every line! + } + } + } + + $logger->debug( "Last interesting line of CPAN.pm output is:\n\t$lines[-1]" ); + + $lines[-1]; + } +} + +BEGIN { +my $epic_fail_words = join '|', + qw( Error stop(?:ping)? problems force not unsupported + fail(?:ed)? Cannot\s+install ); + +sub _cpanpm_output_indicates_failure + { + my $last_line = _get_cpanpm_last_line(); + + my $result = $last_line =~ /\b(?:$epic_fail_words)\b/i; + return A_MODULE_FAILED_TO_INSTALL if $last_line =~ /\b(?:Cannot\s+install)\b/i; + + $result || (); + } +} + +sub _cpanpm_output_indicates_success + { + my $last_line = _get_cpanpm_last_line(); + + my $result = $last_line =~ /\b(?:\s+-- OK|PASS)\b/; + $result || (); + } + +sub _cpanpm_output_is_vague + { + return FALSE if + _cpanpm_output_indicates_failure() || + _cpanpm_output_indicates_success(); + + return TRUE; + } + +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +sub _turn_on_warnings { + carp "Warnings are implemented yet"; + return HEY_IT_WORKED; + } + +sub _turn_off_testing { + $logger->debug( 'Trusting test report history' ); + $CPAN::Config->{trust_test_report_history} = 1; + return HEY_IT_WORKED; + } + +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +sub _print_help + { + $logger->info( "Use perldoc to read the documentation" ); + my $HAVE_PERLDOC = eval { require Pod::Perldoc; 1; }; + if ($HAVE_PERLDOC) { + system qq{"$^X" -e "require Pod::Perldoc; Pod::Perldoc->run()" $0}; + exit; + } else { + warn "Please install Pod::Perldoc, maybe try 'cpan -i Pod::Perldoc'\n"; + return HEY_IT_WORKED; + } + } + +sub _print_version # -v + { + $logger->info( + "$0 script version $VERSION, CPAN.pm version " . CPAN->VERSION ); + + return HEY_IT_WORKED; + } + +sub _print_details # -V + { + _print_version(); + + _check_install_dirs(); + + $logger->info( '-' x 50 . "\nChecking configured mirrors..." ); + foreach my $mirror ( @{ $CPAN::Config->{urllist} } ) { + _print_ping_report( $mirror ); + } + + $logger->info( '-' x 50 . "\nChecking for faster mirrors..." ); + + { + require CPAN::Mirrors; + + if ( $CPAN::Config->{connect_to_internet_ok} ) { + $CPAN::Frontend->myprint(qq{Trying to fetch a mirror list from the Internet\n}); + eval { CPAN::FTP->localize('MIRRORED.BY',File::Spec->catfile($CPAN::Config->{keep_source_where},'MIRRORED.BY'),3,1) } + or $CPAN::Frontend->mywarn(<<'HERE'); +We failed to get a copy of the mirror list from the Internet. +You will need to provide CPAN mirror URLs yourself. +HERE + $CPAN::Frontend->myprint("\n"); + } + + my $mirrors = CPAN::Mirrors->new( _mirror_file() ); + my @continents = $mirrors->find_best_continents; + + my @mirrors = $mirrors->get_mirrors_by_continents( $continents[0] ); + my @timings = $mirrors->get_mirrors_timings( \@mirrors ); + + foreach my $timing ( @timings ) { + $logger->info( sprintf "%s (%0.2f ms)", + $timing->hostname, $timing->rtt ); + } + } + + return HEY_IT_WORKED; + } + +sub _check_install_dirs + { + my $makepl_arg = $CPAN::Config->{makepl_arg}; + my $mbuildpl_arg = $CPAN::Config->{mbuildpl_arg}; + + my @custom_dirs; + # PERL_MM_OPT + push @custom_dirs, + $makepl_arg =~ m/INSTALL_BASE\s*=\s*(\S+)/g, + $mbuildpl_arg =~ m/--install_base\s*=\s*(\S+)/g; + + if( @custom_dirs ) { + foreach my $dir ( @custom_dirs ) { + _print_inc_dir_report( $dir ); + } + } + + # XXX: also need to check makepl_args, etc + + my @checks = ( + [ 'core', [ grep $_, @Config{qw(installprivlib installarchlib)} ] ], + [ 'vendor', [ grep $_, @Config{qw(installvendorlib installvendorarch)} ] ], + [ 'site', [ grep $_, @Config{qw(installsitelib installsitearch)} ] ], + [ 'PERL5LIB', _split_paths( $ENV{PERL5LIB} ) ], + [ 'PERLLIB', _split_paths( $ENV{PERLLIB} ) ], + ); + + $logger->info( '-' x 50 . "\nChecking install dirs..." ); + foreach my $tuple ( @checks ) { + my( $label ) = $tuple->[0]; + + $logger->info( "Checking $label" ); + $logger->info( "\tno directories for $label" ) unless @{ $tuple->[1] }; + foreach my $dir ( @{ $tuple->[1] } ) { + _print_inc_dir_report( $dir ); + } + } + + } + +sub _split_paths + { + [ map { _expand_filename( $_ ) } split /$Config{path_sep}/, $_[0] || '' ]; + } + + +=pod + +Stolen from File::Path::Expand + +=cut + +sub _expand_filename + { + my( $path ) = @_; + no warnings 'uninitialized'; + $logger->debug( "Expanding path $path\n" ); + $path =~ s{\A~([^/]+)?}{ + _home_of( $1 || $> ) || "~$1" + }e; + return $path; + } + +sub _home_of + { + require User::pwent; + my( $user ) = @_; + my $ent = User::pwent::getpw($user) or return; + return $ent->dir; + } + +sub _get_default_inc + { + require Config; + + [ @Config::Config{ _vars() }, '.' ]; + } + +sub _vars { + qw( + installarchlib + installprivlib + installsitearch + installsitelib + ); + } + +sub _ping_mirrors { + my $urls = $CPAN::Config->{urllist}; + require URI; + + foreach my $url ( @$urls ) { + my( $obj ) = URI->new( $url ); + next unless _is_pingable_scheme( $obj ); + my $host = $obj->host; + _print_ping_report( $obj ); + } + + } + +sub _is_pingable_scheme { + my( $uri ) = @_; + + $uri->scheme eq 'file' + } + +sub _mirror_file { + my $file = do { + my $file = 'MIRRORED.BY'; + my $local_path = File::Spec->catfile( + $CPAN::Config->{keep_source_where}, $file ); + + if( -e $local_path ) { $local_path } + else { + require CPAN::FTP; + CPAN::FTP->localize( $file, $local_path, 3, 1 ); + $local_path; + } + }; + } + +sub _find_good_mirrors { + require CPAN::Mirrors; + + my $mirrors = CPAN::Mirrors->new( _mirror_file() ); + + my @mirrors = $mirrors->best_mirrors( + how_many => 5, + verbose => 1, + ); + + foreach my $mirror ( @mirrors ) { + next unless eval { $mirror->can( 'http' ) }; + _print_ping_report( $mirror->http ); + } + + $CPAN::Config->{urllist} = [ + map { $_->http } @mirrors + ]; + } + +sub _print_inc_dir_report + { + my( $dir ) = shift; + + my $writeable = -w $dir ? '+' : '!!! (not writeable)'; + $logger->info( "\t$writeable $dir" ); + return -w $dir; + } + +sub _print_ping_report + { + my( $mirror ) = @_; + + my $rtt = eval { _get_ping_report( $mirror ) }; + my $result = $rtt ? sprintf "+ (%4d ms)", $rtt * 1000 : '!'; + + $logger->info( + sprintf "\t%s %s", $result, $mirror + ); + } + +sub _get_ping_report + { + require URI; + my( $mirror ) = @_; + my( $url ) = ref $mirror ? $mirror : URI->new( $mirror ); #XXX + require Net::Ping; + + my $ping = Net::Ping->new( 'tcp', 1 ); + + if( $url->scheme eq 'file' ) { + return -e $url->file; + } + + my( $port ) = $url->port; + + return unless $port; + + if ( $ping->can('port_number') ) { + $ping->port_number($port); + } + else { + $ping->{'port_num'} = $port; + } + + $ping->hires(1) if $ping->can( 'hires' ); + my( $alive, $rtt ) = eval{ $ping->ping( $url->host ) }; + $alive ? $rtt : undef; + } + +sub _load_local_lib # -I + { + $logger->debug( "Loading local::lib" ); + + my $rc = _safe_load_module("local::lib"); + unless( $rc ) { + $logger->logdie( "Could not load local::lib" ); + } + + local::lib->import; + + return HEY_IT_WORKED; + } + +sub _use_these_mirrors # -M + { + $logger->debug( "Setting per session mirrors" ); + unless( $_[0] ) { + $logger->logdie( "The -M switch requires a comma-separated list of mirrors" ); + } + + $CPAN::Config->{urllist} = [ split /,/, $_[0] ]; + + $logger->debug( "Mirrors are @{$CPAN::Config->{urllist}}" ); + + } + +sub _create_autobundle + { + $logger->info( + "Creating autobundle in $CPAN::Config->{cpan_home}/Bundle" ); + + CPAN::Shell->autobundle; + + return HEY_IT_WORKED; + } + +sub _recompile + { + $logger->info( "Recompiling dynamically-loaded extensions" ); + + CPAN::Shell->recompile; + + return HEY_IT_WORKED; + } + +sub _upgrade + { + $logger->info( "Upgrading all modules" ); + + CPAN::Shell->upgrade(); + + return HEY_IT_WORKED; + } + +sub _shell + { + $logger->info( "Dropping into shell" ); + + CPAN::shell(); + + return HEY_IT_WORKED; + } + +sub _load_config # -j + { + my $argument = shift; + + my $file = file_name_is_absolute( $argument ) ? $argument : rel2abs( $argument ); + croak( "cpan config file [$file] for -j does not exist!\n" ) unless -e $file; + + # should I clear out any existing config here? + $CPAN::Config = {}; + delete $INC{'CPAN/Config.pm'}; + + my $rc = eval "require '$file'"; + + # CPAN::HandleConfig::require_myconfig_or_config looks for this + $INC{'CPAN/MyConfig.pm'} = 'fake out!'; + + # CPAN::HandleConfig::load looks for this + $CPAN::Config_loaded = 'fake out'; + + croak( "Could not load [$file]: $@\n") unless $rc; + + return HEY_IT_WORKED; + } + +sub _dump_config # -J + { + my $args = shift; + require Data::Dumper; + + my $fh = $args->[0] || \*STDOUT; + + local $Data::Dumper::Sortkeys = 1; + my $dd = Data::Dumper->new( + [$CPAN::Config], + ['$CPAN::Config'] + ); + + print $fh $dd->Dump, "\n1;\n__END__\n"; + + return HEY_IT_WORKED; + } + +sub _lock_lobotomy # -F + { + no warnings 'redefine'; + + *CPAN::_flock = sub { 1 }; + *CPAN::checklock = sub { 1 }; + + return HEY_IT_WORKED; + } + +sub _download + { + my $args = shift; + + local $CPAN::DEBUG = 1; + + my %paths; + + foreach my $arg ( @$args ) { + $logger->info( "Checking $arg" ); + + my $module = _expand_module( $arg ) or next; + my $path = $module->cpan_file; + + $logger->debug( "Inst file would be $path\n" ); + + $paths{$module} = _get_file( _make_path( $path ) ); + + $logger->info( "Downloaded [$arg] to [$paths{$arg}]" ); + } + + return \%paths; + } + +sub _make_path { join "/", qw(authors id), $_[0] } + +sub _get_file + { + my $path = shift; + + my $loaded = _safe_load_module("LWP::Simple"); + croak "You need LWP::Simple to use features that fetch files from CPAN\n" + unless $loaded; + + my $file = substr $path, rindex( $path, '/' ) + 1; + my $store_path = catfile( cwd(), $file ); + $logger->debug( "Store path is $store_path" ); + + foreach my $site ( @{ $CPAN::Config->{urllist} } ) + { + my $fetch_path = join "/", $site, $path; + $logger->debug( "Trying $fetch_path" ); + my $status_code = LWP::Simple::getstore( $fetch_path, $store_path ); + last if( 200 <= $status_code and $status_code <= 300 ); + $logger->warn( "Could not get [$fetch_path]: Status code $status_code" ); + } + + return $store_path; + } + +sub _gitify + { + my $args = shift; + + my $loaded = _safe_load_module("Archive::Extract"); + croak "You need Archive::Extract to use features that gitify distributions\n" + unless $loaded; + + my $starting_dir = cwd(); + + foreach my $arg ( @$args ) + { + $logger->info( "Checking $arg" ); + my $store_paths = _download( [ $arg ] ); + $logger->debug( "gitify Store path is $store_paths->{$arg}" ); + my $dirname = dirname( $store_paths->{$arg} ); + + my $ae = Archive::Extract->new( archive => $store_paths->{$arg} ); + $ae->extract( to => $dirname ); + + chdir $ae->extract_path; + + my $git = $ENV{GIT_COMMAND} || '/usr/local/bin/git'; + croak "Could not find $git" unless -e $git; + croak "$git is not executable" unless -x $git; + + # can we do this in Pure Perl? + system( $git, 'init' ); + system( $git, qw( add . ) ); + system( $git, qw( commit -a -m ), 'initial import' ); + } + + chdir $starting_dir; + + return HEY_IT_WORKED; + } + +sub _show_Changes + { + my $args = shift; + + foreach my $arg ( @$args ) + { + $logger->info( "Checking $arg\n" ); + + my $module = _expand_module( $arg ) or next; + + my $out = _get_cpanpm_output(); + + next unless eval { $module->inst_file }; + #next if $module->uptodate; + + ( my $id = $module->id() ) =~ s/::/\-/; + + my $url = "http://search.cpan.org/~" . lc( $module->userid ) . "/" . + $id . "-" . $module->cpan_version() . "/"; + + #print "URL: $url\n"; + _get_changes_file($url); + } + + return HEY_IT_WORKED; + } + +sub _get_changes_file + { + croak "Reading Changes files requires LWP::Simple and URI\n" + unless _safe_load_module("LWP::Simple") && _safe_load_module("URI"); + + my $url = shift; + + my $content = LWP::Simple::get( $url ); + $logger->info( "Got $url ..." ) if defined $content; + #print $content; + + my( $change_link ) = $content =~ m|Changes|gi; + + my $changes_url = URI->new_abs( $change_link, $url ); + $logger->debug( "Change link is: $changes_url" ); + + my $changes = LWP::Simple::get( $changes_url ); + + print $changes; + + return HEY_IT_WORKED; + } + +sub _show_Author + { + my $args = shift; + + foreach my $arg ( @$args ) + { + my $module = _expand_module( $arg ) or next; + + unless( $module ) + { + $logger->info( "Didn't find a $arg module, so no author!" ); + next; + } + + my $author = CPAN::Shell->expand( "Author", $module->userid ); + + next unless $module->userid; + + printf "%-25s %-8s %-25s %s\n", + $arg, $module->userid, $author->email, $author->name; + } + + return HEY_IT_WORKED; + } + +sub _show_Details + { + my $args = shift; + + foreach my $arg ( @$args ) + { + my $module = _expand_module( $arg ) or next; + my $author = CPAN::Shell->expand( "Author", $module->userid ); + + next unless $module->userid; + + print "$arg\n", "-" x 73, "\n\t"; + print join "\n\t", + $module->description ? $module->description : "(no description)", + $module->cpan_file ? $module->cpan_file : "(no cpanfile)", + $module->inst_file ? $module->inst_file :"(no installation file)" , + 'Installed: ' . ($module->inst_version ? $module->inst_version : "not installed"), + 'CPAN: ' . $module->cpan_version . ' ' . + ($module->uptodate ? "" : "Not ") . "up to date", + $author->fullname . " (" . $module->userid . ")", + $author->email; + print "\n\n"; + + } + + return HEY_IT_WORKED; + } + +BEGIN { +my $modules; +sub _get_all_namespaces + { + return $modules if $modules; + $modules = [ map { $_->id } CPAN::Shell->expand( "Module", "/./" ) ]; + } +} + +sub _show_out_of_date + { + my $modules = _get_all_namespaces(); + + printf "%-40s %6s %6s\n", "Module Name", "Local", "CPAN"; + print "-" x 73, "\n"; + + foreach my $module ( @$modules ) + { + next unless $module = _expand_module($module); + next unless $module->inst_file; + next if $module->uptodate; + printf "%-40s %.4f %.4f\n", + $module->id, + $module->inst_version ? $module->inst_version : '', + $module->cpan_version; + } + + return HEY_IT_WORKED; + } + +sub _show_author_mods + { + my $args = shift; + + my %hash = map { lc $_, 1 } @$args; + + my $modules = _get_all_namespaces(); + + foreach my $module ( @$modules ) { + next unless exists $hash{ lc $module->userid }; + print $module->id, "\n"; + } + + return HEY_IT_WORKED; + } + +sub _list_all_mods # -l + { + require File::Find; + + my $args = shift; + + + my $fh = \*STDOUT; + + INC: foreach my $inc ( @INC ) + { + my( $wanted, $reporter ) = _generator(); + File::Find::find( { wanted => $wanted }, $inc ); + + my $count = 0; + FILE: foreach my $file ( @{ $reporter->() } ) + { + my $version = _parse_version_safely( $file ); + + my $module_name = _path_to_module( $inc, $file ); + next FILE unless defined $module_name; + + print $fh "$module_name\t$version\n"; + + #last if $count++ > 5; + } + } + + return HEY_IT_WORKED; + } + +sub _generator + { + my @files = (); + + sub { push @files, + File::Spec->canonpath( $File::Find::name ) + if m/\A\w+\.pm\z/ }, + sub { \@files }, + } + +sub _parse_version_safely # stolen from PAUSE's mldistwatch, but refactored + { + my( $file ) = @_; + + local $/ = "\n"; + local $_; # don't mess with the $_ in the map calling this + + return unless open FILE, "<$file"; + + my $in_pod = 0; + my $version; + while( ) + { + chomp; + $in_pod = /^=(?!cut)/ ? 1 : /^=cut/ ? 0 : $in_pod; + next if $in_pod || /^\s*#/; + + next unless /([\$*])(([\w\:\']*)\bVERSION)\b.*\=/; + my( $sigil, $var ) = ( $1, $2 ); + + $version = _eval_version( $_, $sigil, $var ); + last; + } + close FILE; + + return 'undef' unless defined $version; + + return $version; + } + +sub _eval_version + { + my( $line, $sigil, $var ) = @_; + + # split package line to hide from PAUSE + my $eval = qq{ + package + ExtUtils::MakeMaker::_version; + + local $sigil$var; + \$$var=undef; do { + $line + }; \$$var + }; + + my $version = do { + local $^W = 0; + no strict; + eval( $eval ); + }; + + return $version; + } + +sub _path_to_module + { + my( $inc, $path ) = @_; + return if length $path < length $inc; + + my $module_path = substr( $path, length $inc ); + $module_path =~ s/\.pm\z//; + + # XXX: this is cheating and doesn't handle everything right + my @dirs = grep { ! /\W/ } File::Spec->splitdir( $module_path ); + shift @dirs; + + my $module_name = join "::", @dirs; + + return $module_name; + } + + +sub _expand_module + { + my( $module ) = @_; + + my $expanded = CPAN::Shell->expandany( $module ); + return $expanded if $expanded; + $expanded = CPAN::Shell->expand( "Module", $module ); + unless( defined $expanded ) { + $logger->error( "Could not expand [$module]. Check the module name." ); + my $threshold = ( + grep { int } + sort { length $a <=> length $b } + length($module)/4, 4 + )[0]; + + my $guesses = _guess_at_module_name( $module, $threshold ); + if( defined $guesses and @$guesses ) { + $logger->info( "Perhaps you meant one of these:" ); + foreach my $guess ( @$guesses ) { + $logger->info( "\t$guess" ); + } + } + return; + } + + return $expanded; + } + +my $guessers = [ + [ qw( Text::Levenshtein::XS distance 7 1 ) ], + [ qw( Text::Levenshtein::Damerau::XS xs_edistance 7 1 ) ], + + [ qw( Text::Levenshtein distance 7 1 ) ], + [ qw( Text::Levenshtein::Damerau::PP pp_edistance 7 1 ) ], + + ]; + +sub _disable_guessers + { + $_->[-1] = 0 for @$guessers; + } + +# for -x +sub _guess_namespace + { + my $args = shift; + + foreach my $arg ( @$args ) + { + $logger->debug( "Checking $arg" ); + my $guesses = _guess_at_module_name( $arg ); + + foreach my $guess ( @$guesses ) { + print $guess, "\n"; + } + } + + return HEY_IT_WORKED; + } + +sub _list_all_namespaces { + my $modules = _get_all_namespaces(); + + foreach my $module ( @$modules ) { + print $module, "\n"; + } + } + +BEGIN { +my $distance; +my $_threshold; +my $can_guess; +my $shown_help = 0; +sub _guess_at_module_name + { + my( $target, $threshold ) = @_; + + unless( defined $distance ) { + foreach my $try ( @$guessers ) { + $can_guess = eval "require $try->[0]; 1" or next; + + $try->[-1] or next; # disabled + no strict 'refs'; + $distance = \&{ join "::", @$try[0,1] }; + $threshold ||= $try->[2]; + } + } + $_threshold ||= $threshold; + + unless( $distance ) { + unless( $shown_help ) { + my $modules = join ", ", map { $_->[0] } @$guessers; + substr $modules, rindex( $modules, ',' ), 1, ', and'; + + # Should this be colorized? + if( $can_guess ) { + $logger->info( "I can suggest names if you provide the -x option on invocation." ); + } + else { + $logger->info( "I can suggest names if you install one of $modules" ); + $logger->info( "and you provide the -x option on invocation." ); + } + $shown_help++; + } + return; + } + + my $modules = _get_all_namespaces(); + $logger->info( "Checking " . @$modules . " namespaces for close match suggestions" ); + + my %guesses; + foreach my $guess ( @$modules ) { + my $distance = $distance->( $target, $guess ); + next if $distance > $_threshold; + $guesses{$guess} = $distance; + } + + my @guesses = sort { $guesses{$a} <=> $guesses{$b} } keys %guesses; + return [ grep { defined } @guesses[0..9] ]; + } +} + +1; + +=back + +=head1 EXIT VALUES + +The script exits with zero if it thinks that everything worked, or a +positive number if it thinks that something failed. Note, however, that +in some cases it has to divine a failure by the output of things it does +not control. For now, the exit codes are vague: + + 1 An unknown error + + 2 The was an external problem + + 4 There was an internal problem with the script + + 8 A module failed to install + +=head1 TO DO + +* There is initial support for Log4perl if it is available, but I +haven't gone through everything to make the NullLogger work out +correctly if Log4perl is not installed. + +* When I capture CPAN.pm output, I need to check for errors and +report them to the user. + +* Warnings switch + +* Check then exit + +=head1 BUGS + +* none noted + +=head1 SEE ALSO + +L, L + +=head1 SOURCE AVAILABILITY + +This code is in Github in the CPAN.pm repository: + + https://github.com/andk/cpanpm + +The source used to be tracked separately in another GitHub repo, +but the canonical source is now in the above repo. + +=head1 CREDITS + +Japheth Cleaver added the bits to allow a forced install (C<-f>). + +Jim Brandt suggested and provided the initial implementation for the +up-to-date and Changes features. + +Adam Kennedy pointed out that C causes problems on Windows +where this script ends up with a .bat extension + +David Golden helps integrate this into the C repos. + +Jim Keenan fixed up various issues with _download + +=head1 AUTHOR + +brian d foy, C<< >> + +=head1 COPYRIGHT + +Copyright (c) 2001-2021, brian d foy, All Rights Reserved. + +You may redistribute this under the same terms as Perl itself. + +=cut + +# Local Variables: +# mode: cperl +# indent-tabs-mode: t +# cperl-indent-level: 8 +# cperl-continued-statement-offset: 8 +# End: diff --git a/git/usr/share/perl5/core_perl/App/Prove.pm b/git/usr/share/perl5/core_perl/App/Prove.pm new file mode 100644 index 0000000000000000000000000000000000000000..56079d5836faef635b440cd96aff494732b1e10c --- /dev/null +++ b/git/usr/share/perl5/core_perl/App/Prove.pm @@ -0,0 +1,817 @@ +package App::Prove; + +use strict; +use warnings; + +use TAP::Harness::Env; +use Text::ParseWords qw(shellwords); +use File::Spec; +use Getopt::Long; +use App::Prove::State; +use Carp; + +use base 'TAP::Object'; + +=head1 NAME + +App::Prove - Implements the C command. + +=head1 VERSION + +Version 3.50 + +=cut + +our $VERSION = '3.50'; + +=head1 DESCRIPTION + +L provides a command, C, which runs a TAP based +test suite and prints a report. The C command is a minimal +wrapper around an instance of this module. + +=head1 SYNOPSIS + + use App::Prove; + + my $app = App::Prove->new; + $app->process_args(@ARGV); + $app->run; + +=cut + +use constant IS_WIN32 => ( $^O =~ /^(MS)?Win32$/ ); +use constant IS_VMS => $^O eq 'VMS'; +use constant IS_UNIXY => !( IS_VMS || IS_WIN32 ); + +use constant STATE_FILE => IS_UNIXY ? '.prove' : '_prove'; +use constant RC_FILE => IS_UNIXY ? '.proverc' : '_proverc'; + +use constant PLUGINS => 'App::Prove::Plugin'; + +my @ATTR; + +BEGIN { + @ATTR = qw( + archive argv blib show_count color directives exec failures comments + formatter harness includes modules plugins jobs lib merge parse quiet + really_quiet recurse backwards shuffle taint_fail taint_warn timer + verbose warnings_fail warnings_warn show_help show_man show_version + state_class test_args state dry extensions ignore_exit rules state_manager + normalize sources tapversion trap + statefile + ); + __PACKAGE__->mk_methods(@ATTR); +} + +=head1 METHODS + +=head2 Class Methods + +=head3 C + +Create a new C. Optionally a hash ref of attribute +initializers may be passed. + +=cut + +# new() implementation supplied by TAP::Object + +sub _initialize { + my $self = shift; + my $args = shift || {}; + + my @is_array = qw( + argv rc_opts includes modules state plugins rules sources + ); + + # setup defaults: + for my $key (@is_array) { + $self->{$key} = []; + } + + for my $attr (@ATTR) { + if ( exists $args->{$attr} ) { + + # TODO: Some validation here + $self->{$attr} = $args->{$attr}; + } + } + + $self->state_class('App::Prove::State'); + return $self; +} + +=head3 C + +Getter/setter for the name of the class used for maintaining state. This +class should either subclass from C or provide an identical +interface. + +=head3 C + +Getter/setter for the instance of the C. + +=cut + +=head3 C + + $prove->add_rc_file('myproj/.proverc'); + +Called before C to prepend the contents of an rc file to +the options. + +=cut + +sub add_rc_file { + my ( $self, $rc_file ) = @_; + + local *RC; + open RC, "<$rc_file" or croak "Can't read $rc_file ($!)"; + while ( defined( my $line = ) ) { + push @{ $self->{rc_opts} }, + grep { defined and not /^#/ } + $line =~ m{ ' ([^']*) ' | " ([^"]*) " | (\#.*) | (\S+) }xg; + } + close RC; +} + +=head3 C + + $prove->process_args(@args); + +Processes the command-line arguments. Attributes will be set +appropriately. Any filenames may be found in the C attribute. + +Dies on invalid arguments. + +=cut + +sub process_args { + my $self = shift; + + my @rc = RC_FILE; + unshift @rc, glob '~/' . RC_FILE if IS_UNIXY; + + # Preprocess meta-args. + my @args; + while ( defined( my $arg = shift ) ) { + if ( $arg eq '--norc' ) { + @rc = (); + } + elsif ( $arg eq '--rc' ) { + defined( my $rc = shift ) + or croak "Missing argument to --rc"; + push @rc, $rc; + } + elsif ( $arg =~ m{^--rc=(.+)$} ) { + push @rc, $1; + } + else { + push @args, $arg; + } + } + + # Everything after the arisdottle '::' gets passed as args to + # test programs. + if ( defined( my $stop_at = _first_pos( '::', @args ) ) ) { + my @test_args = splice @args, $stop_at; + shift @test_args; + $self->{test_args} = \@test_args; + } + + # Grab options from RC files + $self->add_rc_file($_) for grep -f, @rc; + unshift @args, @{ $self->{rc_opts} }; + + if ( my @bad = map {"-$_"} grep {/^-(man|help)$/} @args ) { + die "Long options should be written with two dashes: ", + join( ', ', @bad ), "\n"; + } + + # And finally... + + { + local @ARGV = @args; + Getopt::Long::Configure(qw(no_ignore_case bundling pass_through)); + + # Don't add coderefs to GetOptions + GetOptions( + 'v|verbose' => \$self->{verbose}, + 'f|failures' => \$self->{failures}, + 'o|comments' => \$self->{comments}, + 'l|lib' => \$self->{lib}, + 'b|blib' => \$self->{blib}, + 's|shuffle' => \$self->{shuffle}, + 'color!' => \$self->{color}, + 'colour!' => \$self->{color}, + 'count!' => \$self->{show_count}, + 'c' => \$self->{color}, + 'D|dry' => \$self->{dry}, + 'ext=s@' => sub { + my ( $opt, $val ) = @_; + + # Workaround for Getopt::Long 2.25 handling of + # multivalue options + push @{ $self->{extensions} ||= [] }, $val; + }, + 'harness=s' => \$self->{harness}, + 'ignore-exit' => \$self->{ignore_exit}, + 'source=s@' => $self->{sources}, + 'formatter=s' => \$self->{formatter}, + 'r|recurse' => \$self->{recurse}, + 'reverse' => \$self->{backwards}, + 'p|parse' => \$self->{parse}, + 'q|quiet' => \$self->{quiet}, + 'Q|QUIET' => \$self->{really_quiet}, + 'e|exec=s' => \$self->{exec}, + 'm|merge' => \$self->{merge}, + 'I=s@' => $self->{includes}, + 'M=s@' => $self->{modules}, + 'P=s@' => $self->{plugins}, + 'state=s@' => $self->{state}, + 'statefile=s' => \$self->{statefile}, + 'directives' => \$self->{directives}, + 'h|help|?' => \$self->{show_help}, + 'H|man' => \$self->{show_man}, + 'V|version' => \$self->{show_version}, + 'a|archive=s' => \$self->{archive}, + 'j|jobs=i' => \$self->{jobs}, + 'timer' => \$self->{timer}, + 'T' => \$self->{taint_fail}, + 't' => \$self->{taint_warn}, + 'W' => \$self->{warnings_fail}, + 'w' => \$self->{warnings_warn}, + 'normalize' => \$self->{normalize}, + 'rules=s@' => $self->{rules}, + 'tapversion=s' => \$self->{tapversion}, + 'trap' => \$self->{trap}, + ) or croak('Unable to continue'); + + # Stash the remainder of argv for later + $self->{argv} = [@ARGV]; + } + + return; +} + +sub _first_pos { + my $want = shift; + for ( 0 .. $#_ ) { + return $_ if $_[$_] eq $want; + } + return; +} + +sub _help { + my ( $self, $verbosity ) = @_; + + eval('use Pod::Usage 1.12 ()'); + if ( my $err = $@ ) { + die 'Please install Pod::Usage for the --help option ' + . '(or try `perldoc prove`.)' + . "\n ($@)"; + } + + Pod::Usage::pod2usage( { -verbose => $verbosity } ); + + return; +} + +sub _color_default { + my $self = shift; + + return -t STDOUT && !$ENV{HARNESS_NOTTY}; +} + +sub _get_args { + my $self = shift; + + my %args; + + $args{trap} = 1 if $self->trap; + + if ( defined $self->color ? $self->color : $self->_color_default ) { + $args{color} = 1; + } + if ( !defined $self->show_count ) { + $args{show_count} = 1; + } + else { + $args{show_count} = $self->show_count; + } + + if ( $self->archive ) { + $self->require_harness( archive => 'TAP::Harness::Archive' ); + $args{archive} = $self->archive; + } + + if ( my $jobs = $self->jobs ) { + $args{jobs} = $jobs; + } + + if ( my $harness_opt = $self->harness ) { + $self->require_harness( harness => $harness_opt ); + } + + if ( my $formatter = $self->formatter ) { + $args{formatter_class} = $formatter; + } + + for my $handler ( @{ $self->sources } ) { + my ( $name, $config ) = $self->_parse_source($handler); + $args{sources}->{$name} = $config; + } + + if ( $self->ignore_exit ) { + $args{ignore_exit} = 1; + } + + if ( $self->taint_fail && $self->taint_warn ) { + die '-t and -T are mutually exclusive'; + } + + if ( $self->warnings_fail && $self->warnings_warn ) { + die '-w and -W are mutually exclusive'; + } + + for my $a (qw( lib switches )) { + my $method = "_get_$a"; + my $val = $self->$method(); + $args{$a} = $val if defined $val; + } + + # Handle verbose, quiet, really_quiet flags + my %verb_map = ( verbose => 1, quiet => -1, really_quiet => -2, ); + + my @verb_adj = map { $self->$_() ? $verb_map{$_} : () } + keys %verb_map; + + die "Only one of verbose, quiet or really_quiet should be specified\n" + if @verb_adj > 1; + + $args{verbosity} = shift @verb_adj if @verb_adj; + + for my $a (qw( merge failures comments timer directives normalize )) { + $args{$a} = 1 if $self->$a(); + } + + $args{errors} = 1 if $self->parse; + + # defined but zero-length exec runs test files as binaries + $args{exec} = [ split( /\s+/, $self->exec ) ] + if ( defined( $self->exec ) ); + + $args{version} = $self->tapversion if defined( $self->tapversion ); + + if ( defined( my $test_args = $self->test_args ) ) { + $args{test_args} = $test_args; + } + + if ( @{ $self->rules } ) { + my @rules; + for ( @{ $self->rules } ) { + if (/^par=(.*)/) { + push @rules, $1; + } + elsif (/^seq=(.*)/) { + push @rules, { seq => $1 }; + } + } + $args{rules} = { par => [@rules] }; + } + $args{harness_class} = $self->{harness_class} if $self->{harness_class}; + + return \%args; +} + +sub _find_module { + my ( $self, $class, @search ) = @_; + + croak "Bad module name $class" + unless $class =~ /^ \w+ (?: :: \w+ ) *$/x; + + for my $pfx (@search) { + my $name = join( '::', $pfx, $class ); + eval "require $name"; + return $name unless $@; + } + + eval "require $class"; + return $class unless $@; + return; +} + +sub _load_extension { + my ( $self, $name, @search ) = @_; + + my @args = (); + if ( $name =~ /^(.*?)=(.*)/ ) { + $name = $1; + @args = split( /,/, $2 ); + } + + if ( my $class = $self->_find_module( $name, @search ) ) { + if ( $class->can('load') ) { + $class->load( { app_prove => $self, args => [@args] } ); + } + } + else { + croak "Can't load module $name"; + } +} + +sub _load_extensions { + my ( $self, $ext, @search ) = @_; + $self->_load_extension( $_, @search ) for @$ext; +} + +sub _parse_source { + my ( $self, $handler ) = @_; + + # Load any options. + ( my $opt_name = lc $handler ) =~ s/::/-/g; + local @ARGV = @{ $self->{argv} }; + my %config; + Getopt::Long::GetOptions( + "$opt_name-option=s%" => sub { + my ( $name, $k, $v ) = @_; + if ( $v =~ /(? $v; + } + else { + $config{$k} = $v; + } + } + } + ); + $self->{argv} = \@ARGV; + return ( $handler, \%config ); +} + +=head3 C + +Perform whatever actions the command line args specified. The C +command line tool consists of the following code: + + use App::Prove; + + my $app = App::Prove->new; + $app->process_args(@ARGV); + exit( $app->run ? 0 : 1 ); # if you need the exit code + +=cut + +sub run { + my $self = shift; + + unless ( $self->state_manager ) { + $self->state_manager( + $self->state_class->new( { store => $self->statefile || STATE_FILE } ) ); + } + + if ( $self->show_help ) { + $self->_help(1); + } + elsif ( $self->show_man ) { + $self->_help(2); + } + elsif ( $self->show_version ) { + $self->print_version; + } + elsif ( $self->dry ) { + print "$_\n" for $self->_get_tests; + } + else { + + $self->_load_extensions( $self->modules ); + $self->_load_extensions( $self->plugins, PLUGINS ); + + local $ENV{TEST_VERBOSE} = 1 if $self->verbose; + + return $self->_runtests( $self->_get_args, $self->_get_tests ); + } + + return 1; +} + +sub _get_tests { + my $self = shift; + + my $state = $self->state_manager; + my $ext = $self->extensions; + $state->extensions($ext) if defined $ext; + if ( defined( my $state_switch = $self->state ) ) { + $state->apply_switch(@$state_switch); + } + + my @tests = $state->get_tests( $self->recurse, @{ $self->argv } ); + + $self->_shuffle(@tests) if $self->shuffle; + @tests = reverse @tests if $self->backwards; + + return @tests; +} + +sub _runtests { + my ( $self, $args, @tests ) = @_; + my $harness = TAP::Harness::Env->create($args); + + my $state = $self->state_manager; + + $harness->callback( + after_test => sub { + $state->observe_test(@_); + } + ); + + $harness->callback( + after_runtests => sub { + $state->commit(@_); + } + ); + + my $aggregator = $harness->runtests(@tests); + + return !$aggregator->has_errors; +} + +sub _get_switches { + my $self = shift; + my @switches; + + # notes that -T or -t must be at the front of the switches! + if ( $self->taint_fail ) { + push @switches, '-T'; + } + elsif ( $self->taint_warn ) { + push @switches, '-t'; + } + if ( $self->warnings_fail ) { + push @switches, '-W'; + } + elsif ( $self->warnings_warn ) { + push @switches, '-w'; + } + + return @switches ? \@switches : (); +} + +sub _get_lib { + my $self = shift; + my @libs; + if ( $self->lib ) { + push @libs, 'lib'; + } + if ( $self->blib ) { + push @libs, 'blib/lib', 'blib/arch'; + } + if ( @{ $self->includes } ) { + push @libs, @{ $self->includes }; + } + + #24926 + @libs = map { File::Spec->rel2abs($_) } @libs; + + # Huh? + return @libs ? \@libs : (); +} + +sub _shuffle { + my $self = shift; + + # Fisher-Yates shuffle + my $i = @_; + while ($i) { + my $j = rand $i--; + @_[ $i, $j ] = @_[ $j, $i ]; + } + return; +} + +=head3 C + +Load a harness replacement class. + + $prove->require_harness($for => $class_name); + +=cut + +sub require_harness { + my ( $self, $for, $class ) = @_; + + my ($class_name) = $class =~ /^(\w+(?:::\w+)*)/; + + # Emulate Perl's -MModule=arg1,arg2 behaviour + $class =~ s!^(\w+(?:::\w+)*)=(.*)$!$1 split(/,/,q{$2})!; + + eval("use $class;"); + die "$class_name is required to use the --$for feature: $@" if $@; + + $self->{harness_class} = $class_name; + + return; +} + +=head3 C + +Display the version numbers of the loaded L and the +current Perl. + +=cut + +sub print_version { + my $self = shift; + require TAP::Harness; + printf( + "TAP::Harness v%s and Perl v%vd\n", + $TAP::Harness::VERSION, $^V + ); + + return; +} + +1; + +# vim:ts=4:sw=4:et:sta + +__END__ + +=head2 Attributes + +After command line parsing the following attributes reflect the values +of the corresponding command line switches. They may be altered before +calling C. + +=over + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=item C + +=back + +=head1 PLUGINS + +C provides support for 3rd-party plugins. These are currently +loaded at run-time, I arguments have been parsed (so you can not +change the way arguments are processed, sorry), typically with the +C<< -PI >> switch, eg: + + prove -PMyPlugin + +This will search for a module named C, or failing +that, C. If the plugin can't be found, C will complain & exit. + +You can pass an argument to your plugin by appending an C<=> after the plugin +name, eg C<-PMyPlugin=foo>. You can pass multiple arguments using commas: + + prove -PMyPlugin=foo,bar,baz + +These are passed in to your plugin's C class method (if it has one), +along with a reference to the C object that is invoking your plugin: + + sub load { + my ($class, $p) = @_; + + my @args = @{ $p->{args} }; + # @args will contain ( 'foo', 'bar', 'baz' ) + $p->{app_prove}->do_something; + ... + } + +=head2 Sample Plugin + +Here's a sample plugin, for your reference: + + package App::Prove::Plugin::Foo; + + # Sample plugin, try running with: + # prove -PFoo=bar -r -j3 + # prove -PFoo -Q + # prove -PFoo=bar,My::Formatter + + use strict; + use warnings; + + sub load { + my ($class, $p) = @_; + my @args = @{ $p->{args} }; + my $app = $p->{app_prove}; + + print "loading plugin: $class, args: ", join(', ', @args ), "\n"; + + # turn on verbosity + $app->verbose( 1 ); + + # set the formatter? + $app->formatter( $args[1] ) if @args > 1; + + # print some of App::Prove's state: + for my $attr (qw( jobs quiet really_quiet recurse verbose )) { + my $val = $app->$attr; + $val = 'undef' unless defined( $val ); + print "$attr: $val\n"; + } + + return 1; + } + + 1; + +=head1 SEE ALSO + +L, L + +=cut diff --git a/git/usr/share/perl5/core_perl/Archive/Tar.pm b/git/usr/share/perl5/core_perl/Archive/Tar.pm new file mode 100644 index 0000000000000000000000000000000000000000..2df0931e8a5e1609ad42bc6434f767a1652247af --- /dev/null +++ b/git/usr/share/perl5/core_perl/Archive/Tar.pm @@ -0,0 +1,2450 @@ +### the gnu tar specification: +### https://www.gnu.org/software/tar/manual/tar.html +### +### and the pax format spec, which tar derives from: +### https://www.opengroup.org/onlinepubs/007904975/utilities/pax.html + +package Archive::Tar; +require 5.005_03; + +use Cwd; +use IO::Zlib; +use IO::File; +use Carp qw(carp croak); +use File::Spec (); +use File::Spec::Unix (); +use File::Path (); + +use Archive::Tar::File; +use Archive::Tar::Constant; + +require Exporter; + +use strict; +use vars qw[$DEBUG $error $VERSION $WARN $FOLLOW_SYMLINK $CHOWN $CHMOD + $DO_NOT_USE_PREFIX $HAS_PERLIO $HAS_IO_STRING $SAME_PERMISSIONS + $INSECURE_EXTRACT_MODE $ZERO_PAD_NUMBERS @ISA @EXPORT $RESOLVE_SYMLINK + $EXTRACT_BLOCK_SIZE + ]; + +@ISA = qw[Exporter]; +@EXPORT = qw[ COMPRESS_GZIP COMPRESS_BZIP COMPRESS_XZ ]; +$DEBUG = 0; +$WARN = 1; +$FOLLOW_SYMLINK = 0; +$VERSION = "3.04"; +$CHOWN = 1; +$CHMOD = 1; +$SAME_PERMISSIONS = $> == 0 ? 1 : 0; +$DO_NOT_USE_PREFIX = 0; +$INSECURE_EXTRACT_MODE = 0; +$ZERO_PAD_NUMBERS = 0; +$RESOLVE_SYMLINK = $ENV{'PERL5_AT_RESOLVE_SYMLINK'} || 'speed'; +$EXTRACT_BLOCK_SIZE = 1024 * 1024 * 1024; + +BEGIN { + use Config; + $HAS_PERLIO = $Config::Config{useperlio}; + + ### try and load IO::String anyway, so you can dynamically + ### switch between perlio and IO::String + $HAS_IO_STRING = eval { + require IO::String; + IO::String->import; + 1; + } || 0; +} + +=head1 NAME + +Archive::Tar - module for manipulations of tar archives + +=head1 SYNOPSIS + + use Archive::Tar; + my $tar = Archive::Tar->new; + + $tar->read('origin.tgz'); + $tar->extract(); + + $tar->add_files('file/foo.pl', 'docs/README'); + $tar->add_data('file/baz.txt', 'This is the contents now'); + + $tar->rename('oldname', 'new/file/name'); + $tar->chown('/', 'root'); + $tar->chown('/', 'root:root'); + $tar->chmod('/tmp', '1777'); + + $tar->write('files.tar'); # plain tar + $tar->write('files.tgz', COMPRESS_GZIP); # gzip compressed + $tar->write('files.tbz', COMPRESS_BZIP); # bzip2 compressed + $tar->write('files.txz', COMPRESS_XZ); # xz compressed + +=head1 DESCRIPTION + +Archive::Tar provides an object oriented mechanism for handling tar +files. It provides class methods for quick and easy files handling +while also allowing for the creation of tar file objects for custom +manipulation. If you have the IO::Zlib module installed, +Archive::Tar will also support compressed or gzipped tar files. + +An object of class Archive::Tar represents a .tar(.gz) archive full +of files and things. + +=head1 Object Methods + +=head2 Archive::Tar->new( [$file, $compressed] ) + +Returns a new Tar object. If given any arguments, C calls the +C method automatically, passing on the arguments provided to +the C method. + +If C is invoked with arguments and the C method fails +for any reason, C returns undef. + +=cut + +my $tmpl = { + _data => [ ], + _file => 'Unknown', +}; + +### install get/set accessors for this object. +for my $key ( keys %$tmpl ) { + no strict 'refs'; + *{__PACKAGE__."::$key"} = sub { + my $self = shift; + $self->{$key} = $_[0] if @_; + return $self->{$key}; + } +} + +sub new { + my $class = shift; + $class = ref $class if ref $class; + + ### copying $tmpl here since a shallow copy makes it use the + ### same aref, causing for files to remain in memory always. + my $obj = bless { _data => [ ], _file => 'Unknown', _error => '' }, $class; + + if (@_) { + unless ( $obj->read( @_ ) ) { + $obj->_error(qq[No data could be read from file]); + return; + } + } + + return $obj; +} + +=head2 $tar->read ( $filename|$handle, [$compressed, {opt => 'val'}] ) + +Read the given tar file into memory. +The first argument can either be the name of a file or a reference to +an already open filehandle (or an IO::Zlib object if it's compressed) + +The C will I any previous content in C<$tar>! + +The second argument may be considered optional, but remains for +backwards compatibility. Archive::Tar now looks at the file +magic to determine what class should be used to open the file +and will transparently Do The Right Thing. + +Archive::Tar will warn if you try to pass a bzip2 / xz compressed file and the +IO::Uncompress::Bunzip2 / IO::Uncompress::UnXz are not available and simply return. + +Note that you can currently B pass a C compressed +filehandle, which is not opened with C, a C compressed +filehandle, which is not opened with C, a C compressed +filehandle, which is not opened with C, nor a string +containing the full archive information (either compressed or +uncompressed). These are worth while features, but not currently +implemented. See the C section. + +The third argument can be a hash reference with options. Note that +all options are case-sensitive. + +=over 4 + +=item limit + +Do not read more than C files. This is useful if you have +very big archives, and are only interested in the first few files. + +=item filter + +Can be set to a regular expression. Only files with names that match +the expression will be read. + +=item md5 + +Set to 1 and the md5sum of files will be returned (instead of file data) + my $iter = Archive::Tar->iter( $file, 1, {md5 => 1} ); + while( my $f = $iter->() ) { + print $f->data . "\t" . $f->full_path . $/; + } + +=item extract + +If set to true, immediately extract entries when reading them. This +gives you the same memory break as the C function. +Note however that entries will not be read into memory, but written +straight to disk. This means no C objects are +created for you to inspect. + +=back + +All files are stored internally as C objects. +Please consult the L documentation for details. + +Returns the number of files read in scalar context, and a list of +C objects in list context. + +=cut + +sub read { + my $self = shift; + my $file = shift; + my $gzip = shift || 0; + my $opts = shift || {}; + + unless( defined $file ) { + $self->_error( qq[No file to read from!] ); + return; + } else { + $self->_file( $file ); + } + + my $handle = $self->_get_handle($file, $gzip, READ_ONLY->( ZLIB ) ) + or return; + + my $data = $self->_read_tar( $handle, $opts ) or return; + + $self->_data( $data ); + + return wantarray ? @$data : scalar @$data; +} + +sub _get_handle { + my $self = shift; + my $file = shift; return unless defined $file; + my $compress = shift || 0; + my $mode = shift || READ_ONLY->( ZLIB ); # default to read only + + ### Check if file is a file handle or IO glob + if ( ref $file ) { + return $file if eval{ *$file{IO} }; + return $file if eval{ $file->isa(q{IO::Handle}) }; + $file = q{}.$file; + } + + ### get a FH opened to the right class, so we can use it transparently + ### throughout the program + my $fh; + { ### reading magic only makes sense if we're opening a file for + ### reading. otherwise, just use what the user requested. + my $magic = ''; + if( MODE_READ->($mode) ) { + open my $tmp, $file or do { + $self->_error( qq[Could not open '$file' for reading: $!] ); + return; + }; + + ### read the first 6 bytes of the file to figure out which class to + ### use to open the file. + sysread( $tmp, $magic, 6 ); + close $tmp; + } + + ### is it xz? + ### if you asked specifically for xz compression, or if we're in + ### read mode and the magic numbers add up, use xz + if( XZ and ( + ($compress eq COMPRESS_XZ) or + ( MODE_READ->($mode) and $magic =~ XZ_MAGIC_NUM ) + ) + ) { + if( MODE_READ->($mode) ) { + $fh = IO::Uncompress::UnXz->new( $file ) or do { + $self->_error( qq[Could not read '$file': ] . + $IO::Uncompress::UnXz::UnXzError + ); + return; + }; + } else { + $fh = IO::Compress::Xz->new( $file ) or do { + $self->_error( qq[Could not write to '$file': ] . + $IO::Compress::Xz::XzError + ); + return; + }; + } + + ### is it bzip? + ### if you asked specifically for bzip compression, or if we're in + ### read mode and the magic numbers add up, use bzip + } elsif( BZIP and ( + ($compress eq COMPRESS_BZIP) or + ( MODE_READ->($mode) and $magic =~ BZIP_MAGIC_NUM ) + ) + ) { + + ### different reader/writer modules, different error vars... sigh + if( MODE_READ->($mode) ) { + $fh = IO::Uncompress::Bunzip2->new( $file, MultiStream => 1 ) or do { + $self->_error( qq[Could not read '$file': ] . + $IO::Uncompress::Bunzip2::Bunzip2Error + ); + return; + }; + + } else { + $fh = IO::Compress::Bzip2->new( $file ) or do { + $self->_error( qq[Could not write to '$file': ] . + $IO::Compress::Bzip2::Bzip2Error + ); + return; + }; + } + + ### is it gzip? + ### if you asked for compression, if you wanted to read or the gzip + ### magic number is present (redundant with read) + } elsif( ZLIB and ( + $compress or MODE_READ->($mode) or $magic =~ GZIP_MAGIC_NUM + ) + ) { + $fh = IO::Zlib->new; + + unless( $fh->open( $file, $mode ) ) { + $self->_error(qq[Could not create filehandle for '$file': $!]); + return; + } + + ### is it plain tar? + } else { + $fh = IO::File->new; + + unless( $fh->open( $file, $mode ) ) { + $self->_error(qq[Could not create filehandle for '$file': $!]); + return; + } + + ### enable bin mode on tar archives + binmode $fh; + } + } + + return $fh; +} + + +sub _read_tar { + my $self = shift; + my $handle = shift or return; + my $opts = shift || {}; + + my $count = $opts->{limit} || 0; + my $filter = $opts->{filter}; + my $md5 = $opts->{md5} || 0; # cdrake + my $filter_cb = $opts->{filter_cb}; + my $extract = $opts->{extract} || 0; + + ### set a cap on the amount of files to extract ### + my $limit = 0; + $limit = 1 if $count > 0; + + my $tarfile = [ ]; + my $chunk; + my $read = 0; + my $real_name; # to set the name of a file when + # we're encountering @longlink + my $data; + + LOOP: + while( $handle->read( $chunk, HEAD ) ) { + ### IO::Zlib doesn't support this yet + my $offset; + if ( ref($handle) ne 'IO::Zlib' ) { + local $@; + $offset = eval { tell $handle } || 'unknown'; + $@ = ''; + } + else { + $offset = 'unknown'; + } + + unless( $read++ ) { + my $gzip = GZIP_MAGIC_NUM; + if( $chunk =~ /$gzip/ ) { + $self->_error( qq[Cannot read compressed format in tar-mode] ); + return; + } + + ### size is < HEAD, which means a corrupted file, as the minimum + ### length is _at least_ HEAD + if (length $chunk != HEAD) { + $self->_error( qq[Cannot read enough bytes from the tarfile] ); + return; + } + } + + ### if we can't read in all bytes... ### + last if length $chunk != HEAD; + + ### Apparently this should really be two blocks of 512 zeroes, + ### but GNU tar sometimes gets it wrong. See comment in the + ### source code (tar.c) to GNU cpio. + next if $chunk eq TAR_END; + + ### according to the posix spec, the last 12 bytes of the header are + ### null bytes, to pad it to a 512 byte block. That means if these + ### bytes are NOT null bytes, it's a corrupt header. See: + ### www.koders.com/c/fidCE473AD3D9F835D690259D60AD5654591D91D5BA.aspx + ### line 111 + { my $nulls = join '', "\0" x 12; + unless( $nulls eq substr( $chunk, 500, 12 ) ) { + $self->_error( qq[Invalid header block at offset $offset] ); + next LOOP; + } + } + + ### pass the realname, so we can set it 'proper' right away + ### some of the heuristics are done on the name, so important + ### to set it ASAP + my $entry; + { my %extra_args = (); + $extra_args{'name'} = $$real_name if defined $real_name; + + unless( $entry = Archive::Tar::File->new( chunk => $chunk, + %extra_args ) + ) { + $self->_error( qq[Couldn't read chunk at offset $offset] ); + next LOOP; + } + } + + ### ignore labels: + ### https://www.gnu.org/software/tar/manual/html_chapter/Media.html#SEC159 + next if $entry->is_label; + + if( length $entry->type and ($entry->is_file || $entry->is_longlink) ) { + + if ( $entry->is_file && !$entry->validate ) { + ### sometimes the chunk is rather fux0r3d and a whole 512 + ### bytes ends up in the ->name area. + ### clean it up, if need be + my $name = $entry->name; + $name = substr($name, 0, 100) if length $name > 100; + $name =~ s/\n/ /g; + + $self->_error( $name . qq[: checksum error] ); + next LOOP; + } + + my $block = BLOCK_SIZE->( $entry->size ); + + $data = $entry->get_content_by_ref; + + my $skip = 0; + my $ctx; # cdrake + ### skip this entry if we're filtering + + if($md5) { # cdrake + $ctx = Digest::MD5->new; # cdrake + $skip=5; # cdrake + + } elsif ($filter && $entry->name !~ $filter) { + $skip = 1; + + } elsif ($filter_cb && ! $filter_cb->($entry)) { + $skip = 2; + + ### skip this entry if it's a pax header. This is a special file added + ### by, among others, git-generated tarballs. It holds comments and is + ### not meant for extracting. See #38932: pax_global_header extracted + } elsif ( $entry->name eq PAX_HEADER or $entry->type =~ /^(x|g)$/ ) { + $skip = 3; + } + + if ($skip) { + # + # Since we're skipping, do not allocate memory for the + # whole file. Read it 64 BLOCKS at a time. Do not + # complete the skip yet because maybe what we read is a + # longlink and it won't get skipped after all + # + my $amt = $block; + my $fsz=$entry->size; # cdrake + while ($amt > 0) { + $$data = ''; + my $this = 64 * BLOCK; + $this = $amt if $this > $amt; + if( $handle->read( $$data, $this ) < $this ) { + $self->_error( qq[Read error on tarfile (missing data) ']. + $entry->full_path ."' at offset $offset" ); + next LOOP; + } + $amt -= $this; + $fsz -= $this; # cdrake + substr ($$data, $fsz) = "" if ($fsz<0); # remove external junk prior to md5 # cdrake + $ctx->add($$data) if($skip==5); # cdrake + } + $$data = $ctx->hexdigest if($skip==5 && !$entry->is_longlink && !$entry->is_unknown && !$entry->is_label ) ; # cdrake + } else { + + ### just read everything into memory + ### can't do lazy loading since IO::Zlib doesn't support 'seek' + ### this is because Compress::Zlib doesn't support it =/ + ### this reads in the whole data in one read() call. + if ( $handle->read( $$data, $block ) < $block ) { + $self->_error( qq[Read error on tarfile (missing data) ']. + $entry->full_path ."' at offset $offset" ); + next LOOP; + } + ### throw away trailing garbage ### + substr ($$data, $entry->size) = "" if defined $$data; + } + + ### part II of the @LongLink munging -- need to do /after/ + ### the checksum check. + if( $entry->is_longlink ) { + ### weird thing in tarfiles -- if the file is actually a + ### @LongLink, the data part seems to have a trailing ^@ + ### (unprintable) char. to display, pipe output through less. + ### but that doesn't *always* happen.. so check if the last + ### character is a control character, and if so remove it + ### at any rate, we better remove that character here, or tests + ### like 'eq' and hash lookups based on names will SO not work + ### remove it by calculating the proper size, and then + ### tossing out everything that's longer than that size. + + ### count number of nulls + my $nulls = $$data =~ tr/\0/\0/; + + ### cut data + size by that many bytes + $entry->size( $entry->size - $nulls ); + substr ($$data, $entry->size) = ""; + } + } + + ### clean up of the entries.. posix tar /apparently/ has some + ### weird 'feature' that allows for filenames > 255 characters + ### they'll put a header in with as name '././@LongLink' and the + ### contents will be the name of the /next/ file in the archive + ### pretty crappy and kludgy if you ask me + + ### set the name for the next entry if this is a @LongLink; + ### this is one ugly hack =/ but needed for direct extraction + if( $entry->is_longlink ) { + $real_name = $data; + next LOOP; + } elsif ( defined $real_name ) { + $entry->name( $$real_name ); + $entry->prefix(''); + undef $real_name; + } + + if ($filter && $entry->name !~ $filter) { + next LOOP; + + } elsif ($filter_cb && ! $filter_cb->($entry)) { + next LOOP; + + ### skip this entry if it's a pax header. This is a special file added + ### by, among others, git-generated tarballs. It holds comments and is + ### not meant for extracting. See #38932: pax_global_header extracted + } elsif ( $entry->name eq PAX_HEADER or $entry->type =~ /^(x|g)$/ ) { + next LOOP; + } + + if ( $extract && !$entry->is_longlink + && !$entry->is_unknown + && !$entry->is_label ) { + $self->_extract_file( $entry ) or return; + } + + ### Guard against tarfiles with garbage at the end + last LOOP if $entry->name eq ''; + + ### push only the name on the rv if we're extracting + ### -- for extract_archive + push @$tarfile, ($extract ? $entry->name : $entry); + + if( $limit ) { + $count-- unless $entry->is_longlink || $entry->is_dir; + last LOOP unless $count; + } + } continue { + undef $data; + } + + return $tarfile; +} + +=head2 $tar->contains_file( $filename ) + +Check if the archive contains a certain file. +It will return true if the file is in the archive, false otherwise. + +Note however, that this function does an exact match using C +on the full path. So it cannot compensate for case-insensitive file- +systems or compare 2 paths to see if they would point to the same +underlying file. + +=cut + +sub contains_file { + my $self = shift; + my $full = shift; + + return unless defined $full; + + ### don't warn if the entry isn't there.. that's what this function + ### is for after all. + local $WARN = 0; + return 1 if $self->_find_entry($full); + return; +} + +=head2 $tar->extract( [@filenames] ) + +Write files whose names are equivalent to any of the names in +C<@filenames> to disk, creating subdirectories as necessary. This +might not work too well under VMS. +Under MacPerl, the file's modification time will be converted to the +MacOS zero of time, and appropriate conversions will be done to the +path. However, the length of each element of the path is not +inspected to see whether it's longer than MacOS currently allows (32 +characters). + +If C is called without a list of file names, the entire +contents of the archive are extracted. + +Returns a list of filenames extracted. + +=cut + +sub extract { + my $self = shift; + my @args = @_; + my @files; + my $hashmap; + + # use the speed optimization for all extracted files + local($self->{cwd}) = cwd() unless $self->{cwd}; + + ### you requested the extraction of only certain files + if( @args ) { + for my $file ( @args ) { + + ### it's already an object? + if( UNIVERSAL::isa( $file, 'Archive::Tar::File' ) ) { + push @files, $file; + next; + + ### go find it then + } else { + + # create hash-map once to speed up lookup + $hashmap = $hashmap || { + map { $_->full_path, $_ } @{$self->_data} + }; + + if (exists $hashmap->{$file}) { + ### we found the file you're looking for + push @files, $hashmap->{$file}; + } else { + return $self->_error( + qq[Could not find '$file' in archive] ); + } + } + } + + ### just grab all the file items + } else { + @files = $self->get_files; + } + + ### nothing found? that's an error + unless( scalar @files ) { + $self->_error( qq[No files found for ] . $self->_file ); + return; + } + + ### now extract them + for my $entry ( @files ) { + unless( $self->_extract_file( $entry ) ) { + $self->_error(q[Could not extract ']. $entry->full_path .q['] ); + return; + } + } + + return @files; +} + +=head2 $tar->extract_file( $file, [$extract_path] ) + +Write an entry, whose name is equivalent to the file name provided to +disk. Optionally takes a second parameter, which is the full native +path (including filename) the entry will be written to. + +For example: + + $tar->extract_file( 'name/in/archive', 'name/i/want/to/give/it' ); + + $tar->extract_file( $at_file_object, 'name/i/want/to/give/it' ); + +Returns true on success, false on failure. + +=cut + +sub extract_file { + my $self = shift; + my $file = shift; return unless defined $file; + my $alt = shift; + + my $entry = $self->_find_entry( $file ) + or $self->_error( qq[Could not find an entry for '$file'] ), return; + + return $self->_extract_file( $entry, $alt ); +} + +sub _extract_file { + my $self = shift; + my $entry = shift or return; + my $alt = shift; + + ### you wanted an alternate extraction location ### + my $name = defined $alt ? $alt : $entry->full_path; + + ### splitpath takes a bool at the end to indicate + ### that it's splitting a dir + my ($vol,$dirs,$file); + if ( defined $alt ) { # It's a local-OS path + ($vol,$dirs,$file) = File::Spec->splitpath( $alt, + $entry->is_dir ); + } else { + ($vol,$dirs,$file) = File::Spec::Unix->splitpath( $name, + $entry->is_dir ); + } + + my $dir; + ### is $name an absolute path? ### + if( $vol || File::Spec->file_name_is_absolute( $dirs ) ) { + + ### absolute names are not allowed to be in tarballs under + ### strict mode, so only allow it if a user tells us to do it + if( not defined $alt and not $INSECURE_EXTRACT_MODE ) { + $self->_error( + q[Entry ']. $entry->full_path .q[' is an absolute path. ]. + q[Not extracting absolute paths under SECURE EXTRACT MODE] + ); + return; + } + + ### user asked us to, it's fine. + $dir = File::Spec->catpath( $vol, $dirs, "" ); + + ### it's a relative path ### + } else { + my $cwd = (ref $self and defined $self->{cwd}) + ? $self->{cwd} + : cwd(); + + my @dirs = defined $alt + ? File::Spec->splitdir( $dirs ) # It's a local-OS path + : File::Spec::Unix->splitdir( $dirs ); # it's UNIX-style, likely + # straight from the tarball + + if( not defined $alt and + not $INSECURE_EXTRACT_MODE + ) { + + ### paths that leave the current directory are not allowed under + ### strict mode, so only allow it if a user tells us to do this. + if( grep { $_ eq '..' } @dirs ) { + + $self->_error( + q[Entry ']. $entry->full_path .q[' is attempting to leave ]. + q[the current working directory. Not extracting under ]. + q[SECURE EXTRACT MODE] + ); + return; + } + + ### the archive may be asking us to extract into a symlink. This + ### is not sane and a possible security issue, as outlined here: + ### https://rt.cpan.org/Ticket/Display.html?id=30380 + ### https://bugzilla.redhat.com/show_bug.cgi?id=295021 + ### https://issues.rpath.com/browse/RPL-1716 + my $full_path = $cwd; + for my $d ( @dirs ) { + $full_path = File::Spec->catdir( $full_path, $d ); + + ### we've already checked this one, and it's safe. Move on. + next if ref $self and $self->{_link_cache}->{$full_path}; + + if( -l $full_path ) { + my $to = readlink $full_path; + my $diag = "symlinked directory ($full_path => $to)"; + + $self->_error( + q[Entry ']. $entry->full_path .q[' is attempting to ]. + qq[extract to a $diag. This is considered a security ]. + q[vulnerability and not allowed under SECURE EXTRACT ]. + q[MODE] + ); + return; + } + + ### XXX keep a cache if possible, so the stats become cheaper: + $self->{_link_cache}->{$full_path} = 1 if ref $self; + } + } + + ### '.' is the directory delimiter on VMS, which has to be escaped + ### or changed to '_' on vms. vmsify is used, because older versions + ### of vmspath do not handle this properly. + ### Must not add a '/' to an empty directory though. + map { length() ? VMS::Filespec::vmsify($_.'/') : $_ } @dirs if ON_VMS; + + my ($cwd_vol,$cwd_dir,$cwd_file) + = File::Spec->splitpath( $cwd ); + my @cwd = File::Spec->splitdir( $cwd_dir ); + push @cwd, $cwd_file if length $cwd_file; + + ### We need to pass '' as the last element to catpath. Craig Berry + ### explains why (msgid ): + ### The root problem is that splitpath on UNIX always returns the + ### final path element as a file even if it is a directory, and of + ### course there is no way it can know the difference without checking + ### against the filesystem, which it is documented as not doing. When + ### you turn around and call catpath, on VMS you have to know which bits + ### are directory bits and which bits are file bits. In this case we + ### know the result should be a directory. I had thought you could omit + ### the file argument to catpath in such a case, but apparently on UNIX + ### you can't. + $dir = File::Spec->catpath( + $cwd_vol, File::Spec->catdir( @cwd, @dirs ), '' + ); + + ### catdir() returns undef if the path is longer than 255 chars on + ### older VMS systems. + unless ( defined $dir ) { + $^W && $self->_error( qq[Could not compose a path for '$dirs'\n] ); + return; + } + + } + + if( -e $dir && !-d _ ) { + $^W && $self->_error( qq['$dir' exists, but it's not a directory!\n] ); + return; + } + + unless ( -d _ ) { + eval { File::Path::mkpath( $dir, 0, 0777 ) }; + if( $@ ) { + my $fp = $entry->full_path; + $self->_error(qq[Could not create directory '$dir' for '$fp': $@]); + return; + } + + ### XXX chown here? that might not be the same as in the archive + ### as we're only chown'ing to the owner of the file we're extracting + ### not to the owner of the directory itself, which may or may not + ### be another entry in the archive + ### Answer: no, gnu tar doesn't do it either, it'd be the wrong + ### way to go. + #if( $CHOWN && CAN_CHOWN ) { + # chown $entry->uid, $entry->gid, $dir or + # $self->_error( qq[Could not set uid/gid on '$dir'] ); + #} + } + + ### we're done if we just needed to create a dir ### + return 1 if $entry->is_dir; + + my $full = File::Spec->catfile( $dir, $file ); + + if( $entry->is_unknown ) { + $self->_error( qq[Unknown file type for file '$full'] ); + return; + } + + ### If a file system already contains a block device with the same name as + ### the being extracted regular file, we would write the file's content + ### to the block device. So remove the existing file (block device) now. + ### If an archive contains multiple same-named entries, the last one + ### should replace the previous ones. So remove the old file now. + ### If the old entry is a symlink to a file outside of the CWD, the new + ### entry would create a file there. This is CVE-2018-12015 + ### . + if (-l $full || -e _) { + if (!unlink $full) { + $self->_error( qq[Could not remove old file '$full': $!] ); + return; + } + } + if( length $entry->type && $entry->is_file ) { + my $fh = IO::File->new; + $fh->open( $full, '>' ) or ( + $self->_error( qq[Could not open file '$full': $!] ), + return + ); + + if( $entry->size ) { + binmode $fh; + my $offset = 0; + my $content = $entry->get_content_by_ref(); + while ($offset < $entry->size) { + my $written + = syswrite $fh, $$content, $EXTRACT_BLOCK_SIZE, $offset; + if (defined $written) { + $offset += $written; + } else { + $self->_error( qq[Could not write data to '$full': $!] ); + return; + } + } + } + + close $fh or ( + $self->_error( qq[Could not close file '$full'] ), + return + ); + + } else { + $self->_make_special_file( $entry, $full ) or return; + } + + ### only update the timestamp if it's not a symlink; that will change the + ### timestamp of the original. This addresses bug #33669: Could not update + ### timestamp warning on symlinks + if( not -l $full ) { + utime time, $entry->mtime - TIME_OFFSET, $full or + $self->_error( qq[Could not update timestamp] ); + } + + if( $CHOWN && CAN_CHOWN->() and not -l $full ) { + CORE::chown( $entry->uid, $entry->gid, $full ) or + $self->_error( qq[Could not set uid/gid on '$full'] ); + } + + ### only chmod if we're allowed to, but never chmod symlinks, since they'll + ### change the perms on the file they're linking too... + if( $CHMOD and not -l $full ) { + my $mode = $entry->mode; + unless ($SAME_PERMISSIONS) { + $mode &= ~(oct(7000) | umask); + } + CORE::chmod( $mode, $full ) or + $self->_error( qq[Could not chown '$full' to ] . $entry->mode ); + } + + return 1; +} + +sub _make_special_file { + my $self = shift; + my $entry = shift or return; + my $file = shift; return unless defined $file; + + my $err; + + if( $entry->is_symlink ) { + my $fail; + if( ON_UNIX ) { + symlink( $entry->linkname, $file ) or $fail++; + + } else { + $self->_extract_special_file_as_plain_file( $entry, $file ) + or $fail++; + } + + $err = qq[Making symbolic link '$file' to '] . + $entry->linkname .q[' failed] if $fail; + + } elsif ( $entry->is_hardlink ) { + my $fail; + if( ON_UNIX ) { + link( $entry->linkname, $file ) or $fail++; + + } else { + $self->_extract_special_file_as_plain_file( $entry, $file ) + or $fail++; + } + + $err = qq[Making hard link from '] . $entry->linkname . + qq[' to '$file' failed] if $fail; + + } elsif ( $entry->is_fifo ) { + ON_UNIX && !system('mknod', $file, 'p') or + $err = qq[Making fifo ']. $entry->name .qq[' failed]; + + } elsif ( $entry->is_blockdev or $entry->is_chardev ) { + my $mode = $entry->is_blockdev ? 'b' : 'c'; + + ON_UNIX && !system('mknod', $file, $mode, + $entry->devmajor, $entry->devminor) or + $err = qq[Making block device ']. $entry->name .qq[' (maj=] . + $entry->devmajor . qq[ min=] . $entry->devminor . + qq[) failed.]; + + } elsif ( $entry->is_socket ) { + ### the original doesn't do anything special for sockets.... ### + 1; + } + + return $err ? $self->_error( $err ) : 1; +} + +### don't know how to make symlinks, let's just extract the file as +### a plain file +sub _extract_special_file_as_plain_file { + my $self = shift; + my $entry = shift or return; + my $file = shift; return unless defined $file; + + my $err; + TRY: { + my $orig = $self->_find_entry( $entry->linkname, $entry ); + + unless( $orig ) { + $err = qq[Could not find file '] . $entry->linkname . + qq[' in memory.]; + last TRY; + } + + ### clone the entry, make it appear as a normal file ### + my $clone = $orig->clone; + $clone->_downgrade_to_plainfile; + $self->_extract_file( $clone, $file ) or last TRY; + + return 1; + } + + return $self->_error($err); +} + +=head2 $tar->list_files( [\@properties] ) + +Returns a list of the names of all the files in the archive. + +If C is passed an array reference as its first argument +it returns a list of hash references containing the requested +properties of each file. The following list of properties is +supported: name, size, mtime (last modified date), mode, uid, gid, +linkname, uname, gname, devmajor, devminor, prefix. + +Passing an array reference containing only one element, 'name', is +special cased to return a list of names rather than a list of hash +references, making it equivalent to calling C without +arguments. + +=cut + +sub list_files { + my $self = shift; + my $aref = shift || [ ]; + + unless( $self->_data ) { + $self->read() or return; + } + + if( @$aref == 0 or ( @$aref == 1 and $aref->[0] eq 'name' ) ) { + return map { $_->full_path } @{$self->_data}; + } else { + + #my @rv; + #for my $obj ( @{$self->_data} ) { + # push @rv, { map { $_ => $obj->$_() } @$aref }; + #} + #return @rv; + + ### this does the same as the above.. just needs a +{ } + ### to make sure perl doesn't confuse it for a block + return map { my $o=$_; + +{ map { $_ => $o->$_() } @$aref } + } @{$self->_data}; + } +} + +sub _find_entry { + my $self = shift; + my $file = shift; + + unless( defined $file ) { + $self->_error( qq[No file specified] ); + return; + } + + ### it's an object already + return $file if UNIVERSAL::isa( $file, 'Archive::Tar::File' ); + +seach_entry: + if($self->_data){ + for my $entry ( @{$self->_data} ) { + my $path = $entry->full_path; + return $entry if $path eq $file; + } + } + + if($Archive::Tar::RESOLVE_SYMLINK!~/none/){ + if(my $link_entry = shift()){#fallback mode when symlinks are using relative notations ( ../a/./b/text.bin ) + $file = _symlinks_resolver( $link_entry->name, $file ); + goto seach_entry if $self->_data; + + #this will be slower than never, but won't failed! + + my $iterargs = $link_entry->{'_archive'}; + if($Archive::Tar::RESOLVE_SYMLINK=~/speed/ && @$iterargs==3){ + #faster but whole archive will be read in memory + #read whole archive and share data + my $archive = Archive::Tar->new; + $archive->read( @$iterargs ); + push @$iterargs, $archive; #take a trace for destruction + if($archive->_data){ + $self->_data( $archive->_data ); + goto seach_entry; + } + }#faster + + {#slower but lower memory usage + # $iterargs = [$filename, $compressed, $opts]; + my $next = Archive::Tar->iter( @$iterargs ); + while(my $e = $next->()){ + if($e->full_path eq $file){ + undef $next; + return $e; + } + } + }#slower + } + } + + $self->_error( qq[No such file in archive: '$file'] ); + return; +} + +=head2 $tar->get_files( [@filenames] ) + +Returns the C objects matching the filenames +provided. If no filename list was passed, all C +objects in the current Tar object are returned. + +Please refer to the C documentation on how to +handle these objects. + +=cut + +sub get_files { + my $self = shift; + + return @{ $self->_data } unless @_; + + my @list; + for my $file ( @_ ) { + push @list, grep { defined } $self->_find_entry( $file ); + } + + return @list; +} + +=head2 $tar->get_content( $file ) + +Return the content of the named file. + +=cut + +sub get_content { + my $self = shift; + my $entry = $self->_find_entry( shift ) or return; + + return $entry->data; +} + +=head2 $tar->replace_content( $file, $content ) + +Make the string $content be the content for the file named $file. + +=cut + +sub replace_content { + my $self = shift; + my $entry = $self->_find_entry( shift ) or return; + + return $entry->replace_content( shift ); +} + +=head2 $tar->rename( $file, $new_name ) + +Rename the file of the in-memory archive to $new_name. + +Note that you must specify a Unix path for $new_name, since per tar +standard, all files in the archive must be Unix paths. + +Returns true on success and false on failure. + +=cut + +sub rename { + my $self = shift; + my $file = shift; return unless defined $file; + my $new = shift; return unless defined $new; + + my $entry = $self->_find_entry( $file ) or return; + + return $entry->rename( $new ); +} + +=head2 $tar->chmod( $file, $mode ) + +Change mode of $file to $mode. + +Returns true on success and false on failure. + +=cut + +sub chmod { + my $self = shift; + my $file = shift; return unless defined $file; + my $mode = shift; return unless defined $mode && $mode =~ /^[0-7]{1,4}$/; + my @args = ("$mode"); + + my $entry = $self->_find_entry( $file ) or return; + my $x = $entry->chmod( @args ); + return $x; +} + +=head2 $tar->chown( $file, $uname [, $gname] ) + +Change owner $file to $uname and $gname. + +Returns true on success and false on failure. + +=cut + +sub chown { + my $self = shift; + my $file = shift; return unless defined $file; + my $uname = shift; return unless defined $uname; + my @args = ($uname); + push(@args, shift); + + my $entry = $self->_find_entry( $file ) or return; + my $x = $entry->chown( @args ); + return $x; +} + +=head2 $tar->remove (@filenamelist) + +Removes any entries with names matching any of the given filenames +from the in-memory archive. Returns a list of C +objects that remain. + +=cut + +sub remove { + my $self = shift; + my @list = @_; + + my %seen = map { $_->full_path => $_ } @{$self->_data}; + delete $seen{ $_ } for @list; + + $self->_data( [values %seen] ); + + return values %seen; +} + +=head2 $tar->clear + +C clears the current in-memory archive. This effectively gives +you a 'blank' object, ready to be filled again. Note that C +only has effect on the object, not the underlying tarfile. + +=cut + +sub clear { + my $self = shift or return; + + $self->_data( [] ); + $self->_file( '' ); + + return 1; +} + + +=head2 $tar->write ( [$file, $compressed, $prefix] ) + +Write the in-memory archive to disk. The first argument can either +be the name of a file or a reference to an already open filehandle (a +GLOB reference). + +The second argument is used to indicate compression. You can +compress using C, C or C. If you pass a digit, it's assumed +to be the C compression level (between 1 and 9), but the use of +constants is preferred: + + # write a gzip compressed file + $tar->write( 'out.tgz', COMPRESS_GZIP ); + + # write a bzip compressed file + $tar->write( 'out.tbz', COMPRESS_BZIP ); + + # write a xz compressed file + $tar->write( 'out.txz', COMPRESS_XZ ); + +Note that when you pass in a filehandle, the compression argument +is ignored, as all files are printed verbatim to your filehandle. +If you wish to enable compression with filehandles, use an +C, C or C filehandle instead. + +The third argument is an optional prefix. All files will be tucked +away in the directory you specify as prefix. So if you have files +'a' and 'b' in your archive, and you specify 'foo' as prefix, they +will be written to the archive as 'foo/a' and 'foo/b'. + +If no arguments are given, C returns the entire formatted +archive as a string, which could be useful if you'd like to stuff the +archive into a socket or a pipe to gzip or something. + + +=cut + +sub write { + my $self = shift; + my $file = shift; $file = '' unless defined $file; + my $gzip = shift || 0; + my $ext_prefix = shift; $ext_prefix = '' unless defined $ext_prefix; + my $dummy = ''; + + ### only need a handle if we have a file to print to ### + my $handle = length($file) + ? ( $self->_get_handle($file, $gzip, WRITE_ONLY->($gzip) ) + or return ) + : $HAS_PERLIO ? do { open my $h, '>', \$dummy; $h } + : $HAS_IO_STRING ? IO::String->new + : __PACKAGE__->no_string_support(); + + ### Addresses: #41798: Nonempty $\ when writing a TAR file produces a + ### corrupt TAR file. Must clear out $\ to make sure no garbage is + ### printed to the archive + local $\; + + for my $entry ( @{$self->_data} ) { + ### entries to be written to the tarfile ### + my @write_me; + + ### only now will we change the object to reflect the current state + ### of the name and prefix fields -- this needs to be limited to + ### write() only! + my $clone = $entry->clone; + + + ### so, if you don't want use to use the prefix, we'll stuff + ### everything in the name field instead + if( $DO_NOT_USE_PREFIX ) { + + ### you might have an extended prefix, if so, set it in the clone + ### XXX is ::Unix right? + $clone->name( length $ext_prefix + ? File::Spec::Unix->catdir( $ext_prefix, + $clone->full_path) + : $clone->full_path ); + $clone->prefix( '' ); + + ### otherwise, we'll have to set it properly -- prefix part in the + ### prefix and name part in the name field. + } else { + + ### split them here, not before! + my ($prefix,$name) = $clone->_prefix_and_file( $clone->full_path ); + + ### you might have an extended prefix, if so, set it in the clone + ### XXX is ::Unix right? + $prefix = File::Spec::Unix->catdir( $ext_prefix, $prefix ) + if length $ext_prefix; + + $clone->prefix( $prefix ); + $clone->name( $name ); + } + + ### names are too long, and will get truncated if we don't add a + ### '@LongLink' file... + my $make_longlink = ( length($clone->name) > NAME_LENGTH or + length($clone->prefix) > PREFIX_LENGTH + ) || 0; + + ### perhaps we need to make a longlink file? + if( $make_longlink ) { + my $longlink = Archive::Tar::File->new( + data => LONGLINK_NAME, + $clone->full_path, + { type => LONGLINK } + ); + + unless( $longlink ) { + $self->_error( qq[Could not create 'LongLink' entry for ] . + qq[oversize file '] . $clone->full_path ."'" ); + return; + }; + + push @write_me, $longlink; + } + + push @write_me, $clone; + + ### write the one, optionally 2 a::t::file objects to the handle + for my $clone (@write_me) { + + ### if the file is a symlink, there are 2 options: + ### either we leave the symlink intact, but then we don't write any + ### data OR we follow the symlink, which means we actually make a + ### copy. if we do the latter, we have to change the TYPE of the + ### clone to 'FILE' + my $link_ok = $clone->is_symlink && $Archive::Tar::FOLLOW_SYMLINK; + my $data_ok = !$clone->is_symlink && $clone->has_content; + + ### downgrade to a 'normal' file if it's a symlink we're going to + ### treat as a regular file + $clone->_downgrade_to_plainfile if $link_ok; + + ### get the header for this block + my $header = $self->_format_tar_entry( $clone ); + unless( $header ) { + $self->_error(q[Could not format header for: ] . + $clone->full_path ); + return; + } + + unless( print $handle $header ) { + $self->_error(q[Could not write header for: ] . + $clone->full_path); + return; + } + + if( $link_ok or $data_ok ) { + unless( print $handle $clone->data ) { + $self->_error(q[Could not write data for: ] . + $clone->full_path); + return; + } + + ### pad the end of the clone if required ### + print $handle TAR_PAD->( $clone->size ) if $clone->size % BLOCK + } + + } ### done writing these entries + } + + ### write the end markers ### + print $handle TAR_END x 2 or + return $self->_error( qq[Could not write tar end markers] ); + + ### did you want it written to a file, or returned as a string? ### + my $rv = length($file) ? 1 + : $HAS_PERLIO ? $dummy + : do { seek $handle, 0, 0; local $/; <$handle> }; + + ### make sure to close the handle if we created it + if ( $file ne $handle ) { + unless( close $handle ) { + $self->_error( qq[Could not write tar] ); + return; + } + } + + return $rv; +} + +sub _format_tar_entry { + my $self = shift; + my $entry = shift or return; + my $ext_prefix = shift; $ext_prefix = '' unless defined $ext_prefix; + my $no_prefix = shift || 0; + + my $file = $entry->name; + my $prefix = $entry->prefix; $prefix = '' unless defined $prefix; + + ### remove the prefix from the file name + ### not sure if this is still needed --kane + ### no it's not -- Archive::Tar::File->_new_from_file will take care of + ### this for us. Even worse, this would break if we tried to add a file + ### like x/x. + #if( length $prefix ) { + # $file =~ s/^$match//; + #} + + $prefix = File::Spec::Unix->catdir($ext_prefix, $prefix) + if length $ext_prefix; + + ### not sure why this is... ### + my $l = PREFIX_LENGTH; # is ambiguous otherwise... + substr ($prefix, 0, -$l) = "" if length $prefix >= PREFIX_LENGTH; + + my $f1 = "%06o"; my $f2 = $ZERO_PAD_NUMBERS ? "%011o" : "%11o"; + + ### this might be optimizable with a 'changed' flag in the file objects ### + my $tar = pack ( + PACK, + $file, + + (map { sprintf( $f1, $entry->$_() ) } qw[mode uid gid]), + (map { sprintf( $f2, $entry->$_() ) } qw[size mtime]), + + "", # checksum field - space padded a bit down + + (map { $entry->$_() } qw[type linkname magic]), + + $entry->version || TAR_VERSION, + + (map { $entry->$_() } qw[uname gname]), + (map { sprintf( $f1, $entry->$_() ) } qw[devmajor devminor]), + + ($no_prefix ? '' : $prefix) + ); + + ### add the checksum ### + my $checksum_fmt = $ZERO_PAD_NUMBERS ? "%06o\0" : "%06o\0"; + substr($tar,148,7) = sprintf("%6o\0", unpack("%16C*",$tar)); + + return $tar; +} + +=head2 $tar->add_files( @filenamelist ) + +Takes a list of filenames and adds them to the in-memory archive. + +The path to the file is automatically converted to a Unix like +equivalent for use in the archive, and, if on MacOS, the file's +modification time is converted from the MacOS epoch to the Unix epoch. +So tar archives created on MacOS with B can be read +both with I on Unix and applications like I or +I on MacOS. + +Be aware that the file's type/creator and resource fork will be lost, +which is usually what you want in cross-platform archives. + +Instead of a filename, you can also pass it an existing C +object from, for example, another archive. The object will be clone, and +effectively be a copy of the original, not an alias. + +Returns a list of C objects that were just added. + +=cut + +sub add_files { + my $self = shift; + my @files = @_ or return; + + my @rv; + for my $file ( @files ) { + + ### you passed an Archive::Tar::File object + ### clone it so we don't accidentally have a reference to + ### an object from another archive + if( UNIVERSAL::isa( $file,'Archive::Tar::File' ) ) { + push @rv, $file->clone; + next; + } + + eval { + if( utf8::is_utf8( $file )) { + utf8::encode( $file ); + } + }; + + unless( -e $file || -l $file ) { + $self->_error( qq[No such file: '$file'] ); + next; + } + + my $obj = Archive::Tar::File->new( file => $file ); + unless( $obj ) { + $self->_error( qq[Unable to add file: '$file'] ); + next; + } + + push @rv, $obj; + } + + push @{$self->{_data}}, @rv; + + return @rv; +} + +=head2 $tar->add_data ( $filename, $data, [$opthashref] ) + +Takes a filename, a scalar full of data and optionally a reference to +a hash with specific options. + +Will add a file to the in-memory archive, with name C<$filename> and +content C<$data>. Specific properties can be set using C<$opthashref>. +The following list of properties is supported: name, size, mtime +(last modified date), mode, uid, gid, linkname, uname, gname, +devmajor, devminor, prefix, type. (On MacOS, the file's path and +modification times are converted to Unix equivalents.) + +Valid values for the file type are the following constants defined by +Archive::Tar::Constant: + +=over 4 + +=item FILE + +Regular file. + +=item HARDLINK + +=item SYMLINK + +Hard and symbolic ("soft") links; linkname should specify target. + +=item CHARDEV + +=item BLOCKDEV + +Character and block devices. devmajor and devminor should specify the major +and minor device numbers. + +=item DIR + +Directory. + +=item FIFO + +FIFO (named pipe). + +=item SOCKET + +Socket. + +=back + +Returns the C object that was just added, or +C on failure. + +=cut + +sub add_data { + my $self = shift; + my ($file, $data, $opt) = @_; + + my $obj = Archive::Tar::File->new( data => $file, $data, $opt ); + unless( $obj ) { + $self->_error( qq[Unable to add file: '$file'] ); + return; + } + + push @{$self->{_data}}, $obj; + + return $obj; +} + +=head2 $tar->error( [$BOOL] ) + +Returns the current error string (usually, the last error reported). +If a true value was specified, it will give the C +equivalent of the error, in effect giving you a stacktrace. + +For backwards compatibility, this error is also available as +C<$Archive::Tar::error> although it is much recommended you use the +method call instead. + +=cut + +{ + $error = ''; + my $longmess; + + sub _error { + my $self = shift; + my $msg = $error = shift; + $longmess = Carp::longmess($error); + if (ref $self) { + $self->{_error} = $error; + $self->{_longmess} = $longmess; + } + + ### set Archive::Tar::WARN to 0 to disable printing + ### of errors + if( $WARN ) { + carp $DEBUG ? $longmess : $msg; + } + + return; + } + + sub error { + my $self = shift; + if (ref $self) { + return shift() ? $self->{_longmess} : $self->{_error}; + } else { + return shift() ? $longmess : $error; + } + } +} + +=head2 $tar->setcwd( $cwd ); + +C needs to know the current directory, and it will run +C I time it extracts a I entry from the +tarfile and saves it in the file system. (As of version 1.30, however, +C will use the speed optimization described below +automatically, so it's only relevant if you're using C). + +Since C doesn't change the current directory internally +while it is extracting the items in a tarball, all calls to C +can be avoided if we can guarantee that the current directory doesn't +get changed externally. + +To use this performance boost, set the current directory via + + use Cwd; + $tar->setcwd( cwd() ); + +once before calling a function like C and +C will use the current directory setting from then on +and won't call C internally. + +To switch back to the default behaviour, use + + $tar->setcwd( undef ); + +and C will call C internally again. + +If you're using C's C method, C will +be called for you. + +=cut + +sub setcwd { + my $self = shift; + my $cwd = shift; + + $self->{cwd} = $cwd; +} + +=head1 Class Methods + +=head2 Archive::Tar->create_archive($file, $compressed, @filelist) + +Creates a tar file from the list of files provided. The first +argument can either be the name of the tar file to create or a +reference to an open file handle (e.g. a GLOB reference). + +The second argument is used to indicate compression. You can +compress using C, C or C. If you pass a digit, it's assumed +to be the C compression level (between 1 and 9), but the use of +constants is preferred: + + # write a gzip compressed file + Archive::Tar->create_archive( 'out.tgz', COMPRESS_GZIP, @filelist ); + + # write a bzip compressed file + Archive::Tar->create_archive( 'out.tbz', COMPRESS_BZIP, @filelist ); + + # write a xz compressed file + Archive::Tar->create_archive( 'out.txz', COMPRESS_XZ, @filelist ); + +Note that when you pass in a filehandle, the compression argument +is ignored, as all files are printed verbatim to your filehandle. +If you wish to enable compression with filehandles, use an +C, C or C filehandle instead. + +The remaining arguments list the files to be included in the tar file. +These files must all exist. Any files which don't exist or can't be +read are silently ignored. + +If the archive creation fails for any reason, C will +return false. Please use the C method to find the cause of the +failure. + +Note that this method does not write C as it were; it +still reads all the files into memory before writing out the archive. +Consult the FAQ below if this is a problem. + +=cut + +sub create_archive { + my $class = shift; + + my $file = shift; return unless defined $file; + my $gzip = shift || 0; + my @files = @_; + + unless( @files ) { + return $class->_error( qq[Cowardly refusing to create empty archive!] ); + } + + my $tar = $class->new; + $tar->add_files( @files ); + return $tar->write( $file, $gzip ); +} + +=head2 Archive::Tar->iter( $filename, [ $compressed, {opt => $val} ] ) + +Returns an iterator function that reads the tar file without loading +it all in memory. Each time the function is called it will return the +next file in the tarball. The files are returned as +C objects. The iterator function returns the +empty list once it has exhausted the files contained. + +The second argument can be a hash reference with options, which are +identical to the arguments passed to C. + +Example usage: + + my $next = Archive::Tar->iter( "example.tar.gz", 1, {filter => qr/\.pm$/} ); + + while( my $f = $next->() ) { + print $f->name, "\n"; + + $f->extract or warn "Extraction failed"; + + # .... + } + +=cut + + +sub iter { + my $class = shift; + my $filename = shift; + return unless defined $filename; + my $compressed = shift || 0; + my $opts = shift || {}; + + ### get a handle to read from. + my $handle = $class->_get_handle( + $filename, + $compressed, + READ_ONLY->( ZLIB ) + ) or return; + + my @data; + my $CONSTRUCT_ARGS = [ $filename, $compressed, $opts ]; + return sub { + return shift(@data) if @data; # more than one file returned? + return unless $handle; # handle exhausted? + + ### read data, should only return file + my $tarfile = $class->_read_tar($handle, { %$opts, limit => 1 }); + @data = @$tarfile if ref $tarfile && ref $tarfile eq 'ARRAY'; + if($Archive::Tar::RESOLVE_SYMLINK!~/none/){ + foreach(@data){ + #may refine this heuristic for ON_UNIX? + if($_->linkname){ + #is there a better slot to store/share it ? + $_->{'_archive'} = $CONSTRUCT_ARGS; + } + } + } + + ### return one piece of data + return shift(@data) if @data; + + ### data is exhausted, free the filehandle + undef $handle; + if(@$CONSTRUCT_ARGS == 4){ + #free archive in memory + undef $CONSTRUCT_ARGS->[-1]; + } + return; + }; +} + +=head2 Archive::Tar->list_archive($file, $compressed, [\@properties]) + +Returns a list of the names of all the files in the archive. The +first argument can either be the name of the tar file to list or a +reference to an open file handle (e.g. a GLOB reference). + +If C is passed an array reference as its third +argument it returns a list of hash references containing the requested +properties of each file. The following list of properties is +supported: full_path, name, size, mtime (last modified date), mode, +uid, gid, linkname, uname, gname, devmajor, devminor, prefix, type. + +See C for details about supported properties. + +Passing an array reference containing only one element, 'name', is +special cased to return a list of names rather than a list of hash +references. + +=cut + +sub list_archive { + my $class = shift; + my $file = shift; return unless defined $file; + my $gzip = shift || 0; + + my $tar = $class->new($file, $gzip); + return unless $tar; + + return $tar->list_files( @_ ); +} + +=head2 Archive::Tar->extract_archive($file, $compressed) + +Extracts the contents of the tar file. The first argument can either +be the name of the tar file to create or a reference to an open file +handle (e.g. a GLOB reference). All relative paths in the tar file will +be created underneath the current working directory. + +C will return a list of files it extracted. +If the archive extraction fails for any reason, C +will return false. Please use the C method to find the cause +of the failure. + +=cut + +sub extract_archive { + my $class = shift; + my $file = shift; return unless defined $file; + my $gzip = shift || 0; + + my $tar = $class->new( ) or return; + + return $tar->read( $file, $gzip, { extract => 1 } ); +} + +=head2 $bool = Archive::Tar->has_io_string + +Returns true if we currently have C support loaded. + +Either C or C support is needed to support writing +stringified archives. Currently, C is the preferred method, if +available. + +See the C section to see how to change this preference. + +=cut + +sub has_io_string { return $HAS_IO_STRING; } + +=head2 $bool = Archive::Tar->has_perlio + +Returns true if we currently have C support loaded. + +This requires C or higher, compiled with C + +Either C or C support is needed to support writing +stringified archives. Currently, C is the preferred method, if +available. + +See the C section to see how to change this preference. + +=cut + +sub has_perlio { return $HAS_PERLIO; } + +=head2 $bool = Archive::Tar->has_zlib_support + +Returns true if C can extract C compressed archives + +=cut + +sub has_zlib_support { return ZLIB } + +=head2 $bool = Archive::Tar->has_bzip2_support + +Returns true if C can extract C compressed archives + +=cut + +sub has_bzip2_support { return BZIP } + +=head2 $bool = Archive::Tar->has_xz_support + +Returns true if C can extract C compressed archives + +=cut + +sub has_xz_support { return XZ } + +=head2 Archive::Tar->can_handle_compressed_files + +A simple checking routine, which will return true if C +is able to uncompress compressed archives on the fly with C, +C and C or false if not both are installed. + +You can use this as a shortcut to determine whether C +will do what you think before passing compressed archives to its +C method. + +=cut + +sub can_handle_compressed_files { return ZLIB && BZIP ? 1 : 0 } + +sub no_string_support { + croak("You have to install IO::String to support writing archives to strings"); +} + +sub _symlinks_resolver{ + my ($src, $trg) = @_; + my @src = split /[\/\\]/, $src; + my @trg = split /[\/\\]/, $trg; + pop @src; #strip out current object name + if(@trg and $trg[0] eq ''){ + shift @trg; + #restart path from scratch + @src = ( ); + } + foreach my $part ( @trg ){ + next if $part eq '.'; #ignore current + if($part eq '..'){ + #got to parent + pop @src; + } + else{ + #append it + push @src, $part; + } + } + my $path = join('/', @src); + warn "_symlinks_resolver('$src','$trg') = $path" if $DEBUG; + return $path; +} + +1; + +__END__ + +=head1 GLOBAL VARIABLES + +=head2 $Archive::Tar::FOLLOW_SYMLINK + +Set this variable to C<1> to make C effectively make a +copy of the file when extracting. Default is C<0>, which +means the symlink stays intact. Of course, you will have to pack the +file linked to as well. + +This option is checked when you write out the tarfile using C +or C. + +This works just like C's C<-h> option. + +=head2 $Archive::Tar::CHOWN + +By default, C will try to C your files if it is +able to. In some cases, this may not be desired. In that case, set +this variable to C<0> to disable C-ing, even if it were +possible. + +The default is C<1>. + +=head2 $Archive::Tar::CHMOD + +By default, C will try to C your files to +whatever mode was specified for the particular file in the archive. +In some cases, this may not be desired. In that case, set this +variable to C<0> to disable C-ing. + +The default is C<1>. + +=head2 $Archive::Tar::SAME_PERMISSIONS + +When, C<$Archive::Tar::CHMOD> is enabled, this setting controls whether +the permissions on files from the archive are used without modification +of if they are filtered by removing any setid bits and applying the +current umask. + +The default is C<1> for the root user and C<0> for normal users. + +=head2 $Archive::Tar::DO_NOT_USE_PREFIX + +By default, C will try to put paths that are over +100 characters in the C field of your tar header, as +defined per POSIX-standard. However, some (older) tar programs +do not implement this spec. To retain compatibility with these older +or non-POSIX compliant versions, you can set the C<$DO_NOT_USE_PREFIX> +variable to a true value, and C will use an alternate +way of dealing with paths over 100 characters by using the +C feature. + +Note that clients who do not support the C +feature will not be able to read these archives. Such clients include +tars on C, C and C. + +The default is C<0>. + +=head2 $Archive::Tar::DEBUG + +Set this variable to C<1> to always get the C output +of the warnings, instead of the regular C. This is the same +message you would get by doing: + + $tar->error(1); + +Defaults to C<0>. + +=head2 $Archive::Tar::WARN + +Set this variable to C<0> if you do not want any warnings printed. +Personally I recommend against doing this, but people asked for the +option. Also, be advised that this is of course not threadsafe. + +Defaults to C<1>. + +=head2 $Archive::Tar::error + +Holds the last reported error. Kept for historical reasons, but its +use is very much discouraged. Use the C method instead: + + warn $tar->error unless $tar->extract; + +Note that in older versions of this module, the C method +would return an effectively global value even when called an instance +method as above. This has since been fixed, and multiple instances of +C now have separate error strings. + +=head2 $Archive::Tar::INSECURE_EXTRACT_MODE + +This variable indicates whether C should allow +files to be extracted outside their current working directory. + +Allowing this could have security implications, as a malicious +tar archive could alter or replace any file the extracting user +has permissions to. Therefor, the default is to not allow +insecure extractions. + +If you trust the archive, or have other reasons to allow the +archive to write files outside your current working directory, +set this variable to C. + +Note that this is a backwards incompatible change from version +C<1.36> and before. + +=head2 $Archive::Tar::HAS_PERLIO + +This variable holds a boolean indicating if we currently have +C support loaded. This will be enabled for any perl +greater than C<5.8> compiled with C. + +If you feel strongly about disabling it, set this variable to +C. Note that you will then need C installed +to support writing stringified archives. + +Don't change this variable unless you B know what you're +doing. + +=head2 $Archive::Tar::HAS_IO_STRING + +This variable holds a boolean indicating if we currently have +C support loaded. This will be enabled for any perl +that has a loadable C module. + +If you feel strongly about disabling it, set this variable to +C. Note that you will then need C support from +your perl to be able to write stringified archives. + +Don't change this variable unless you B know what you're +doing. + +=head2 $Archive::Tar::ZERO_PAD_NUMBERS + +This variable holds a boolean indicating if we will create +zero padded numbers for C, C and C. +The default is C<0>, indicating that we will create space padded +numbers. Added for compatibility with C implementations. + +=head2 Tuning the way RESOLVE_SYMLINK will works + +You can tune the behaviour by setting the $Archive::Tar::RESOLVE_SYMLINK variable, +or $ENV{PERL5_AT_RESOLVE_SYMLINK} before loading the module Archive::Tar. + +Values can be one of the following: + +=over 4 + +=item none + +Disable this mechanism and failed as it was in previous version (<1.88) + +=item speed (default) + +If you prefer speed +this will read again the whole archive using read() so all entries +will be available + +=item memory + +If you prefer memory + +=back + +Limitation: It won't work for terminal, pipe or sockets or every non seekable +source. + +=head2 $Archive::Tar::EXTRACT_BLOCK_SIZE + +This variable holds an integer with the block size that should be used when +writing files during extraction. It defaults to 1 GiB. Please note that this +cannot be arbitrarily large since some operating systems limit the number of +bytes that can be written in one call to C, so if this is too large, +extraction may fail with an error. + +=cut + +=head1 FAQ + +=over 4 + +=item What's the minimum perl version required to run Archive::Tar? + +You will need perl version 5.005_03 or newer. + +=item Isn't Archive::Tar slow? + +Yes it is. It's pure perl, so it's a lot slower then your C +However, it's very portable. If speed is an issue, consider using +C instead. + +=item Isn't Archive::Tar heavier on memory than /bin/tar? + +Yes it is, see previous answer. Since C and therefore +C doesn't support C on their filehandles, there is little +choice but to read the archive into memory. +This is ok if you want to do in-memory manipulation of the archive. + +If you just want to extract, use the C class method +instead. It will optimize and write to disk immediately. + +Another option is to use the C class method to iterate over +the files in the tarball without reading them all in memory at once. + +=item Can you lazy-load data instead? + +In some cases, yes. You can use the C class method to iterate +over the files in the tarball without reading them all in memory at once. + +=item How much memory will an X kb tar file need? + +Probably more than X kb, since it will all be read into memory. If +this is a problem, and you don't need to do in memory manipulation +of the archive, consider using the C class method, or C +instead. + +=item What do you do with unsupported filetypes in an archive? + +C has a few filetypes that aren't supported on other platforms, +like C. If we encounter a C or C we'll just +try to make a copy of the original file, rather than throwing an error. + +This does require you to read the entire archive in to memory first, +since otherwise we wouldn't know what data to fill the copy with. +(This means that you cannot use the class methods, including C +on archives that have incompatible filetypes and still expect things +to work). + +For other filetypes, like C and C we'll warn that +the extraction of this particular item didn't work. + +=item I'm using WinZip, or some other non-POSIX client, and files are not being extracted properly! + +By default, C is in a completely POSIX-compatible +mode, which uses the POSIX-specification of C to store files. +For paths greater than 100 characters, this is done using the +C. Non-POSIX-compatible clients may not support +this part of the specification, and may only support the C functionality. To facilitate those clients, you can set the +C<$Archive::Tar::DO_NOT_USE_PREFIX> variable to C. See the +C section for details on this variable. + +Note that GNU tar earlier than version 1.14 does not cope well with +the C. If you use such a version, consider setting +the C<$Archive::Tar::DO_NOT_USE_PREFIX> variable to C. + +=item How do I extract only files that have property X from an archive? + +Sometimes, you might not wish to extract a complete archive, just +the files that are relevant to you, based on some criteria. + +You can do this by filtering a list of C objects +based on your criteria. For example, to extract only files that have +the string C in their title, you would use: + + $tar->extract( + grep { $_->full_path =~ /foo/ } $tar->get_files + ); + +This way, you can filter on any attribute of the files in the archive. +Consult the C documentation on how to use these +objects. + +=item How do I access .tar.Z files? + +The C module can optionally use C (via +the C module) to access tar files that have been compressed +with C. Unfortunately tar files compressed with the Unix C +utility cannot be read by C and so cannot be directly +accesses by C. + +If the C or C programs are available, you can use +one of these workarounds to read C<.tar.Z> files from C + +Firstly with C + + use Archive::Tar; + + open F, "uncompress -c $filename |"; + my $tar = Archive::Tar->new(*F); + ... + +and this with C + + use Archive::Tar; + + open F, "gunzip -c $filename |"; + my $tar = Archive::Tar->new(*F); + ... + +Similarly, if the C program is available, you can use this to +write a C<.tar.Z> file + + use Archive::Tar; + use IO::File; + + my $fh = IO::File->new( "| compress -c >$filename" ); + my $tar = Archive::Tar->new(); + ... + $tar->write($fh); + $fh->close ; + +=item How do I handle Unicode strings? + +C uses byte semantics for any files it reads from or writes +to disk. This is not a problem if you only deal with files and never +look at their content or work solely with byte strings. But if you use +Unicode strings with character semantics, some additional steps need +to be taken. + +For example, if you add a Unicode string like + + # Problem + $tar->add_data('file.txt', "Euro: \x{20AC}"); + +then there will be a problem later when the tarfile gets written out +to disk via C<< $tar->write() >>: + + Wide character in print at .../Archive/Tar.pm line 1014. + +The data was added as a Unicode string and when writing it out to disk, +the C<:utf8> line discipline wasn't set by C, so Perl +tried to convert the string to ISO-8859 and failed. The written file +now contains garbage. + +For this reason, Unicode strings need to be converted to UTF-8-encoded +bytestrings before they are handed off to C: + + use Encode; + my $data = "Accented character: \x{20AC}"; + $data = encode('utf8', $data); + + $tar->add_data('file.txt', $data); + +A opposite problem occurs if you extract a UTF8-encoded file from a +tarball. Using C on the C object +will return its content as a bytestring, not as a Unicode string. + +If you want it to be a Unicode string (because you want character +semantics with operations like regular expression matching), you need +to decode the UTF8-encoded content and have Perl convert it into +a Unicode string: + + use Encode; + my $data = $tar->get_content(); + + # Make it a Unicode string + $data = decode('utf8', $data); + +There is no easy way to provide this functionality in C, +because a tarball can contain many files, and each of which could be +encoded in a different way. + +=back + +=head1 CAVEATS + +The AIX tar does not fill all unused space in the tar archive with 0x00. +This sometimes leads to warning messages from C. + + Invalid header block at offset nnn + +A fix for that problem is scheduled to be released in the following levels +of AIX, all of which should be coming out in the 4th quarter of 2009: + + AIX 5.3 TL7 SP10 + AIX 5.3 TL8 SP8 + AIX 5.3 TL9 SP5 + AIX 5.3 TL10 SP2 + + AIX 6.1 TL0 SP11 + AIX 6.1 TL1 SP7 + AIX 6.1 TL2 SP6 + AIX 6.1 TL3 SP3 + +The IBM APAR number for this problem is IZ50240 (Reported component ID: +5765G0300 / AIX 5.3). It is possible to get an ifix for that problem. +If you need an ifix please contact your local IBM AIX support. + +=head1 TODO + +=over 4 + +=item Check if passed in handles are open for read/write + +Currently I don't know of any portable pure perl way to do this. +Suggestions welcome. + +=item Allow archives to be passed in as string + +Currently, we only allow opened filehandles or filenames, but +not strings. The internals would need some reworking to facilitate +stringified archives. + +=item Facilitate processing an opened filehandle of a compressed archive + +Currently, we only support this if the filehandle is an IO::Zlib object. +Environments, like apache, will present you with an opened filehandle +to an uploaded file, which might be a compressed archive. + +=back + +=head1 SEE ALSO + +=over 4 + +=item The GNU tar specification + +L + +=item The PAX format specification + +The specification which tar derives from; L + +=back + +=head1 AUTHOR + +This module by Jos Boumans Ekane@cpan.orgE. + +Please reports bugs to Ebug-archive-tar@rt.cpan.orgE. + +=head1 ACKNOWLEDGEMENTS + +Thanks to Sean Burke, Chris Nandor, Chip Salzenberg, Tim Heaney, Gisle Aas, +Rainer Tammer and especially Andrew Savige for their help and suggestions. + +=head1 COPYRIGHT + +This module is copyright (c) 2002 - 2009 Jos Boumans +Ekane@cpan.orgE. All rights reserved. + +This library is free software; you may redistribute and/or modify +it under the same terms as Perl itself. + +=cut diff --git a/git/usr/share/perl5/core_perl/Attribute/Handlers.pm b/git/usr/share/perl5/core_perl/Attribute/Handlers.pm new file mode 100644 index 0000000000000000000000000000000000000000..861ea2f8d59f3b5ddcbe3bd7c7541cf004d86718 --- /dev/null +++ b/git/usr/share/perl5/core_perl/Attribute/Handlers.pm @@ -0,0 +1,987 @@ +package Attribute::Handlers; +use 5.006; +use Carp; +use warnings; +use strict; +our $AUTOLOAD; +our $VERSION = '1.03'; # remember to update version in POD! +# $DB::single=1; +my $debug= $ENV{DEBUG_ATTRIBUTE_HANDLERS} || 0; +my %symcache; +sub findsym { + my ($pkg, $ref, $type) = @_; + return $symcache{$pkg,$ref} if $symcache{$pkg,$ref}; + $type ||= ref($ref); + no strict 'refs'; + my $symtab = \%{$pkg."::"}; + for ( keys %$symtab ) { for my $sym ( $$symtab{$_} ) { + if (ref $sym && $sym == $ref) { + return $symcache{$pkg,$ref} = \*{"$pkg:\:$_"}; + } + use strict; + next unless ref ( \$sym ) eq 'GLOB'; + return $symcache{$pkg,$ref} = \$sym + if *{$sym}{$type} && *{$sym}{$type} == $ref; + }} +} + +my %validtype = ( + VAR => [qw[SCALAR ARRAY HASH]], + ANY => [qw[SCALAR ARRAY HASH CODE]], + "" => [qw[SCALAR ARRAY HASH CODE]], + SCALAR => [qw[SCALAR]], + ARRAY => [qw[ARRAY]], + HASH => [qw[HASH]], + CODE => [qw[CODE]], +); +my %lastattr; +my @declarations; +my %raw; +my %phase; +my %sigil = (SCALAR=>'$', ARRAY=>'@', HASH=>'%'); +my $global_phase = 0; +my %global_phases = ( + BEGIN => 0, + CHECK => 1, + INIT => 2, + END => 3, +); +my @global_phases = qw(BEGIN CHECK INIT END); + +sub _usage_AH_ { + croak "Usage: use $_[0] autotie => {AttrName => TieClassName,...}"; +} + +my $qual_id = qr/^[_a-z]\w*(::[_a-z]\w*)*$/i; + +sub import { + my $class = shift @_; + return unless $class eq "Attribute::Handlers"; + while (@_) { + my $cmd = shift; + if ($cmd =~ /^autotie((?:ref)?)$/) { + my $tiedata = ($1 ? '$ref, ' : '') . '@$data'; + my $mapping = shift; + _usage_AH_ $class unless ref($mapping) eq 'HASH'; + while (my($attr, $tieclass) = each %$mapping) { + $tieclass =~ s/^([_a-z]\w*(::[_a-z]\w*)*)(.*)/$1/is; + my $args = $3||'()'; + _usage_AH_ $class unless $attr =~ $qual_id + && $tieclass =~ $qual_id + && eval "use base q\0$tieclass\0; 1"; + if ($tieclass->isa('Exporter')) { + local $Exporter::ExportLevel = 2; + $tieclass->import(eval $args); + } + my $code = qq{ + : ATTR(VAR) { + my (\$ref, \$data) = \@_[2,4]; + my \$was_arrayref = ref \$data eq 'ARRAY'; + \$data = [ \$data ] unless \$was_arrayref; + my \$type = ref(\$ref)||"value (".(\$ref||"").")"; + (\$type eq 'SCALAR')? tie \$\$ref,'$tieclass',$tiedata + :(\$type eq 'ARRAY') ? tie \@\$ref,'$tieclass',$tiedata + :(\$type eq 'HASH') ? tie \%\$ref,'$tieclass',$tiedata + : die "Can't autotie a \$type\n" + } + }; + + if ($attr =~ /\A__CALLER__::/) { + no strict 'refs'; + my $add_import = caller; + my $next = defined &{ $add_import . '::import' } && \&{ $add_import . '::import' }; + *{ $add_import . '::import' } = sub { + my $caller = caller; + my $full_attr = $attr; + $full_attr =~ s/__CALLER__/$caller/; + eval qq{ sub $full_attr $code 1; } + or die "Internal error: $@"; + + goto &$next + if $next; + my $uni = defined &UNIVERSAL::import && \&UNIVERSAL::import; + for my $isa (@{ $add_import . '::ISA' }) { + if (my $import = $isa->can('import')) { + goto &$import + if $import != $uni; + } + } + goto &$uni + if $uni; + }; + } + else { + $attr = caller()."::".$attr unless $attr =~ /::/; + eval qq{ sub $attr $code 1; } + or die "Internal error: $@"; + } + } + } + else { + croak "Can't understand $_"; + } + } +} + +# On older perls, code attribute handlers run before the sub gets placed +# in its package. Since the :ATTR handlers need to know the name of the +# sub they're applied to, the name lookup (via findsym) needs to be +# delayed: we do it immediately before we might need to find attribute +# handlers from their name. However, on newer perls (which fix some +# problems relating to attribute application), a sub gets placed in its +# package before its attributes are processed. In this case, the +# delayed name lookup might be too late, because the sub we're looking +# for might have already been replaced. So we need to detect which way +# round this perl does things, and time the name lookup accordingly. +BEGIN { + my $delayed; + sub Attribute::Handlers::_TEST_::MODIFY_CODE_ATTRIBUTES { + $delayed = \&Attribute::Handlers::_TEST_::t != $_[1]; + return (); + } + sub Attribute::Handlers::_TEST_::t :T { } + *_delayed_name_resolution = sub() { $delayed }; + undef &Attribute::Handlers::_TEST_::MODIFY_CODE_ATTRIBUTES; + undef &Attribute::Handlers::_TEST_::t; +} + +sub _resolve_lastattr { + return unless $lastattr{ref}; + my $sym = findsym @lastattr{'pkg','ref'} + or die "Internal error: $lastattr{pkg} symbol went missing"; + my $name = *{$sym}{NAME}; + warn "Declaration of $name attribute in package $lastattr{pkg} may clash with future reserved word\n" + if $^W and $name !~ /[A-Z]/; + foreach ( @{$validtype{$lastattr{type}}} ) { + no strict 'refs'; + *{"$lastattr{pkg}::_ATTR_${_}_${name}"} = $lastattr{ref}; + } + %lastattr = (); +} + +sub AUTOLOAD { + return if $AUTOLOAD =~ /::DESTROY$/; + my ($class) = $AUTOLOAD =~ m/(.*)::/g; + $AUTOLOAD =~ m/_ATTR_(.*?)_(.*)/ or + croak "Can't locate class method '$AUTOLOAD' via package '$class'"; + croak "Attribute handler '$2' doesn't handle $1 attributes"; +} + +my $builtin = $] ge '5.027000' + ? qr/lvalue|method|shared/ + : qr/lvalue|method|locked|shared|unique/; + +sub _gen_handler_AH_() { + return sub { + _resolve_lastattr if _delayed_name_resolution; + my ($pkg, $ref, @attrs) = @_; + my (undef, $filename, $linenum) = caller 2; + foreach (@attrs) { + my ($attr, $data) = /^([a-z_]\w*)(?:[(](.*)[)])?$/is or next; + if ($attr eq 'ATTR') { + no strict 'refs'; + $data ||= "ANY"; + $raw{$ref} = $data =~ s/\s*,?\s*RAWDATA\s*,?\s*//; + $phase{$ref}{BEGIN} = 1 + if $data =~ s/\s*,?\s*(BEGIN)\s*,?\s*//; + $phase{$ref}{INIT} = 1 + if $data =~ s/\s*,?\s*(INIT)\s*,?\s*//; + $phase{$ref}{END} = 1 + if $data =~ s/\s*,?\s*(END)\s*,?\s*//; + $phase{$ref}{CHECK} = 1 + if $data =~ s/\s*,?\s*(CHECK)\s*,?\s*// + || ! keys %{$phase{$ref}}; + # Added for cleanup to not pollute next call. + (%lastattr = ()), + croak "Can't have two ATTR specifiers on one subroutine" + if keys %lastattr; + croak "Bad attribute type: ATTR($data)" + unless $validtype{$data}; + %lastattr=(pkg=>$pkg,ref=>$ref,type=>$data); + _resolve_lastattr unless _delayed_name_resolution; + } + else { + my $type = ref $ref; + my $handler = $pkg->can("_ATTR_${type}_${attr}"); + next unless $handler; + my $decl = [$pkg, $ref, $attr, $data, + $raw{$handler}, $phase{$handler}, $filename, $linenum]; + foreach my $gphase (@global_phases) { + _apply_handler_AH_($decl,$gphase) + if $global_phases{$gphase} <= $global_phase; + } + if ($global_phase != 0) { + # if _gen_handler_AH_ is being called after + # CHECK it's for a lexical, so make sure + # it didn't want to run anything later + + local $Carp::CarpLevel = 2; + carp "Won't be able to apply END handler" + if $phase{$handler}{END}; + } + else { + push @declarations, $decl + } + } + $_ = undef; + } + return grep {defined && !/$builtin/} @attrs; + } +} + +{ + no strict 'refs'; + *{"Attribute::Handlers::UNIVERSAL::MODIFY_${_}_ATTRIBUTES"} = + _gen_handler_AH_ foreach @{$validtype{ANY}}; +} +push @UNIVERSAL::ISA, 'Attribute::Handlers::UNIVERSAL' + unless grep /^Attribute::Handlers::UNIVERSAL$/, @UNIVERSAL::ISA; + +sub _apply_handler_AH_ { + my ($declaration, $phase) = @_; + my ($pkg, $ref, $attr, $data, $raw, $handlerphase, $filename, $linenum) = @$declaration; + return unless $handlerphase->{$phase}; + print STDERR "Handling $attr on $ref in $phase with [$data]\n" + if $debug; + my $type = ref $ref; + my $handler = "_ATTR_${type}_${attr}"; + my $sym = findsym($pkg, $ref); + $sym ||= $type eq 'CODE' ? 'ANON' : 'LEXICAL'; + no warnings; + if (!$raw && defined($data)) { + if ($data ne '') { + # keeping the minimum amount of code inside the eval string + # makes debugging perl internals issues with this logic easier. + my $code= "package $pkg; my \$ref= [$data]; \$data= \$ref; 1"; + print STDERR "Evaling: '$code'\n" + if $debug; + local $SIG{__WARN__} = sub{ die }; + no strict; + no warnings; + # Note in production we do not need to use the return value from + # the eval or even consult $@ after the eval - if the evaled code + # compiles and runs successfully then it will update $data with + # the compiled form, if it fails then $data stays unchanged. The + # return value and $@ are only used for debugging purposes. + # IOW we could just replace the following with eval($code); + eval($code) or do { + print STDERR "Eval failed: $@" + if $debug; + }; + } + else { $data = undef } + } + + # now call the handler with the $data decoded (maybe) + $pkg->$handler($sym, + (ref $sym eq 'GLOB' ? *{$sym}{ref $ref}||$ref : $ref), + $attr, + $data, + $phase, + $filename, + $linenum, + ); + return 1; +} + +{ + no warnings 'void'; + CHECK { + $global_phase++; + _resolve_lastattr if _delayed_name_resolution; + foreach my $decl (@declarations) { + _apply_handler_AH_($decl, 'CHECK'); + } + } + + INIT { + $global_phase++; + foreach my $decl (@declarations) { + _apply_handler_AH_($decl, 'INIT'); + } + } +} + +END { + $global_phase++; + foreach my $decl (@declarations) { + _apply_handler_AH_($decl, 'END'); + } +} + +1; +__END__ + +=head1 NAME + +Attribute::Handlers - Simpler definition of attribute handlers + +=head1 VERSION + +This document describes version 1.03 of Attribute::Handlers. + +=head1 SYNOPSIS + + package MyClass; + require 5.006; + use Attribute::Handlers; + no warnings 'redefine'; + + + sub Good : ATTR(SCALAR) { + my ($package, $symbol, $referent, $attr, $data) = @_; + + # Invoked for any scalar variable with a :Good attribute, + # provided the variable was declared in MyClass (or + # a derived class) or typed to MyClass. + + # Do whatever to $referent here (executed in CHECK phase). + ... + } + + sub Bad : ATTR(SCALAR) { + # Invoked for any scalar variable with a :Bad attribute, + # provided the variable was declared in MyClass (or + # a derived class) or typed to MyClass. + ... + } + + sub Good : ATTR(ARRAY) { + # Invoked for any array variable with a :Good attribute, + # provided the variable was declared in MyClass (or + # a derived class) or typed to MyClass. + ... + } + + sub Good : ATTR(HASH) { + # Invoked for any hash variable with a :Good attribute, + # provided the variable was declared in MyClass (or + # a derived class) or typed to MyClass. + ... + } + + sub Ugly : ATTR(CODE) { + # Invoked for any subroutine declared in MyClass (or a + # derived class) with an :Ugly attribute. + ... + } + + sub Omni : ATTR { + # Invoked for any scalar, array, hash, or subroutine + # with an :Omni attribute, provided the variable or + # subroutine was declared in MyClass (or a derived class) + # or the variable was typed to MyClass. + # Use ref($_[2]) to determine what kind of referent it was. + ... + } + + + use Attribute::Handlers autotie => { Cycle => Tie::Cycle }; + + my $next : Cycle(['A'..'Z']); + + +=head1 DESCRIPTION + +This module, when inherited by a package, allows that package's class to +define attribute handler subroutines for specific attributes. Variables +and subroutines subsequently defined in that package, or in packages +derived from that package may be given attributes with the same names as +the attribute handler subroutines, which will then be called in one of +the compilation phases (i.e. in a C, C, C, or C +block). (C blocks don't correspond to a global compilation +phase, so they can't be specified here.) + +To create a handler, define it as a subroutine with the same name as +the desired attribute, and declare the subroutine itself with the +attribute C<:ATTR>. For example: + + package LoudDecl; + use Attribute::Handlers; + + sub Loud :ATTR { + my ($package, $symbol, $referent, $attr, $data, $phase, + $filename, $linenum) = @_; + print STDERR + ref($referent), " ", + *{$symbol}{NAME}, " ", + "($referent) ", "was just declared ", + "and ascribed the ${attr} attribute ", + "with data ($data)\n", + "in phase $phase\n", + "in file $filename at line $linenum\n"; + } + +This creates a handler for the attribute C<:Loud> in the class LoudDecl. +Thereafter, any subroutine declared with a C<:Loud> attribute in the class +LoudDecl: + + package LoudDecl; + + sub foo: Loud {...} + +causes the above handler to be invoked, and passed: + +=over + +=item [0] + +the name of the package into which it was declared; + +=item [1] + +a reference to the symbol table entry (typeglob) containing the subroutine; + +=item [2] + +a reference to the subroutine; + +=item [3] + +the name of the attribute; + +=item [4] + +any data associated with that attribute; + +=item [5] + +the name of the phase in which the handler is being invoked; + +=item [6] + +the filename in which the handler is being invoked; + +=item [7] + +the line number in this file. + +=back + +Likewise, declaring any variables with the C<:Loud> attribute within the +package: + + package LoudDecl; + + my $foo :Loud; + my @foo :Loud; + my %foo :Loud; + +will cause the handler to be called with a similar argument list (except, +of course, that C<$_[2]> will be a reference to the variable). + +The package name argument will typically be the name of the class into +which the subroutine was declared, but it may also be the name of a derived +class (since handlers are inherited). + +If a lexical variable is given an attribute, there is no symbol table to +which it belongs, so the symbol table argument (C<$_[1]>) is set to the +string C<'LEXICAL'> in that case. Likewise, ascribing an attribute to +an anonymous subroutine results in a symbol table argument of C<'ANON'>. + +The data argument passes in the value (if any) associated with the +attribute. For example, if C<&foo> had been declared: + + sub foo :Loud("turn it up to 11, man!") {...} + +then a reference to an array containing the string +C<"turn it up to 11, man!"> would be passed as the last argument. + +Attribute::Handlers makes strenuous efforts to convert +the data argument (C<$_[4]>) to a usable form before passing it to +the handler (but see L<"Non-interpretive attribute handlers">). +If those efforts succeed, the interpreted data is passed in an array +reference; if they fail, the raw data is passed as a string. +For example, all of these: + + sub foo :Loud(till=>ears=>are=>bleeding) {...} + sub foo :Loud(qw/till ears are bleeding/) {...} + sub foo :Loud(qw/till, ears, are, bleeding/) {...} + sub foo :Loud(till,ears,are,bleeding) {...} + +causes it to pass C<['till','ears','are','bleeding']> as the handler's +data argument. While: + + sub foo :Loud(['till','ears','are','bleeding']) {...} + +causes it to pass C<[ ['till','ears','are','bleeding'] ]>; the array +reference specified in the data being passed inside the standard +array reference indicating successful interpretation. + +However, if the data can't be parsed as valid Perl, then +it is passed as an uninterpreted string. For example: + + sub foo :Loud(my,ears,are,bleeding) {...} + sub foo :Loud(qw/my ears are bleeding) {...} + +cause the strings C<'my,ears,are,bleeding'> and +C<'qw/my ears are bleeding'> respectively to be passed as the +data argument. + +If no value is associated with the attribute, C is passed. + +=head2 Typed lexicals + +Regardless of the package in which it is declared, if a lexical variable is +ascribed an attribute, the handler that is invoked is the one belonging to +the package to which it is typed. For example, the following declarations: + + package OtherClass; + + my LoudDecl $loudobj : Loud; + my LoudDecl @loudobjs : Loud; + my LoudDecl %loudobjex : Loud; + +causes the LoudDecl::Loud handler to be invoked (even if OtherClass also +defines a handler for C<:Loud> attributes). + + +=head2 Type-specific attribute handlers + +If an attribute handler is declared and the C<:ATTR> specifier is +given the name of a built-in type (C, C, C, or C), +the handler is only applied to declarations of that type. For example, +the following definition: + + package LoudDecl; + + sub RealLoud :ATTR(SCALAR) { print "Yeeeeow!" } + +creates an attribute handler that applies only to scalars: + + + package Painful; + use base LoudDecl; + + my $metal : RealLoud; # invokes &LoudDecl::RealLoud + my @metal : RealLoud; # error: unknown attribute + my %metal : RealLoud; # error: unknown attribute + sub metal : RealLoud {...} # error: unknown attribute + +You can, of course, declare separate handlers for these types as well +(but you'll need to specify C to do it quietly): + + package LoudDecl; + use Attribute::Handlers; + no warnings 'redefine'; + + sub RealLoud :ATTR(SCALAR) { print "Yeeeeow!" } + sub RealLoud :ATTR(ARRAY) { print "Urrrrrrrrrr!" } + sub RealLoud :ATTR(HASH) { print "Arrrrrgggghhhhhh!" } + sub RealLoud :ATTR(CODE) { croak "Real loud sub torpedoed" } + +You can also explicitly indicate that a single handler is meant to be +used for all types of referents like so: + + package LoudDecl; + use Attribute::Handlers; + + sub SeriousLoud :ATTR(ANY) { warn "Hearing loss imminent" } + +(I.e. C is a synonym for C<:ATTR>). + + +=head2 Non-interpretive attribute handlers + +Occasionally the strenuous efforts Attribute::Handlers makes to convert +the data argument (C<$_[4]>) to a usable form before passing it to +the handler get in the way. + +You can turn off that eagerness-to-help by declaring +an attribute handler with the keyword C. For example: + + sub Raw : ATTR(RAWDATA) {...} + sub Nekkid : ATTR(SCALAR,RAWDATA) {...} + sub Au::Naturale : ATTR(RAWDATA,ANY) {...} + +Then the handler makes absolutely no attempt to interpret the data it +receives and simply passes it as a string: + + my $power : Raw(1..100); # handlers receives "1..100" + +=head2 Phase-specific attribute handlers + +By default, attribute handlers are called at the end of the compilation +phase (in a C block). This seems to be optimal in most cases because +most things that can be defined are defined by that point but nothing has +been executed. + +However, it is possible to set up attribute handlers that are called at +other points in the program's compilation or execution, by explicitly +stating the phase (or phases) in which you wish the attribute handler to +be called. For example: + + sub Early :ATTR(SCALAR,BEGIN) {...} + sub Normal :ATTR(SCALAR,CHECK) {...} + sub Late :ATTR(SCALAR,INIT) {...} + sub Final :ATTR(SCALAR,END) {...} + sub Bookends :ATTR(SCALAR,BEGIN,END) {...} + +As the last example indicates, a handler may be set up to be (re)called in +two or more phases. The phase name is passed as the handler's final argument. + +Note that attribute handlers that are scheduled for the C phase +are handled as soon as the attribute is detected (i.e. before any +subsequently defined C blocks are executed). + + +=head2 Attributes as C interfaces + +Attributes make an excellent and intuitive interface through which to tie +variables. For example: + + use Attribute::Handlers; + use Tie::Cycle; + + sub UNIVERSAL::Cycle : ATTR(SCALAR) { + my ($package, $symbol, $referent, $attr, $data, $phase) = @_; + $data = [ $data ] unless ref $data eq 'ARRAY'; + tie $$referent, 'Tie::Cycle', $data; + } + + # and thereafter... + + package main; + + my $next : Cycle('A'..'Z'); # $next is now a tied variable + + while (<>) { + print $next; + } + +Note that, because the C attribute receives its arguments in the +C<$data> variable, if the attribute is given a list of arguments, C<$data> +will consist of a single array reference; otherwise, it will consist of the +single argument directly. Since Tie::Cycle requires its cycling values to +be passed as an array reference, this means that we need to wrap +non-array-reference arguments in an array constructor: + + $data = [ $data ] unless ref $data eq 'ARRAY'; + +Typically, however, things are the other way around: the tieable class expects +its arguments as a flattened list, so the attribute looks like: + + sub UNIVERSAL::Cycle : ATTR(SCALAR) { + my ($package, $symbol, $referent, $attr, $data, $phase) = @_; + my @data = ref $data eq 'ARRAY' ? @$data : $data; + tie $$referent, 'Tie::Whatever', @data; + } + + +This software pattern is so widely applicable that Attribute::Handlers +provides a way to automate it: specifying C<'autotie'> in the +C statement. So, the cycling example, +could also be written: + + use Attribute::Handlers autotie => { Cycle => 'Tie::Cycle' }; + + # and thereafter... + + package main; + + my $next : Cycle(['A'..'Z']); # $next is now a tied variable + + while (<>) { + print $next; + } + +Note that we now have to pass the cycling values as an array reference, +since the C mechanism passes C a list of arguments as a list +(as in the Tie::Whatever example), I as an array reference (as in +the original Tie::Cycle example at the start of this section). + +The argument after C<'autotie'> is a reference to a hash in which each key is +the name of an attribute to be created, and each value is the class to which +variables ascribed that attribute should be tied. + +Note that there is no longer any need to import the Tie::Cycle module -- +Attribute::Handlers takes care of that automagically. You can even pass +arguments to the module's C subroutine, by appending them to the +class name. For example: + + use Attribute::Handlers + autotie => { Dir => 'Tie::Dir qw(DIR_UNLINK)' }; + +If the attribute name is unqualified, the attribute is installed in the +current package. Otherwise it is installed in the qualifier's package: + + package Here; + + use Attribute::Handlers autotie => { + Other::Good => Tie::SecureHash, # tie attr installed in Other:: + Bad => Tie::Taxes, # tie attr installed in Here:: + UNIVERSAL::Ugly => Software::Patent # tie attr installed everywhere + }; + +Autoties are most commonly used in the module to which they actually tie, +and need to export their attributes to any module that calls them. To +facilitate this, Attribute::Handlers recognizes a special "pseudo-class" -- +C<__CALLER__>, which may be specified as the qualifier of an attribute: + + package Tie::Me::Kangaroo::Down::Sport; + + use Attribute::Handlers autotie => + { '__CALLER__::Roo' => __PACKAGE__ }; + +This causes Attribute::Handlers to define the C attribute in the package +that imports the Tie::Me::Kangaroo::Down::Sport module. + +Note that it is important to quote the __CALLER__::Roo identifier because +a bug in perl 5.8 will refuse to parse it and cause an unknown error. + +=head3 Passing the tied object to C + +Occasionally it is important to pass a reference to the object being tied +to the TIESCALAR, TIEHASH, etc. that ties it. + +The C mechanism supports this too. The following code: + + use Attribute::Handlers autotieref => { Selfish => Tie::Selfish }; + my $var : Selfish(@args); + +has the same effect as: + + tie my $var, 'Tie::Selfish', @args; + +But when C<"autotieref"> is used instead of C<"autotie">: + + use Attribute::Handlers autotieref => { Selfish => Tie::Selfish }; + my $var : Selfish(@args); + +the effect is to pass the C call an extra reference to the variable +being tied: + + tie my $var, 'Tie::Selfish', \$var, @args; + + + +=head1 EXAMPLES + +If the class shown in L were placed in the MyClass.pm +module, then the following code: + + package main; + use MyClass; + + my MyClass $slr :Good :Bad(1**1-1) :Omni(-vorous); + + package SomeOtherClass; + use base MyClass; + + sub tent { 'acle' } + + sub fn :Ugly(sister) :Omni('po',tent()) {...} + my @arr :Good :Omni(s/cie/nt/); + my %hsh :Good(q/bye/) :Omni(q/bus/); + + +would cause the following handlers to be invoked: + + # my MyClass $slr :Good :Bad(1**1-1) :Omni(-vorous); + + MyClass::Good:ATTR(SCALAR)( 'MyClass', # class + 'LEXICAL', # no typeglob + \$slr, # referent + 'Good', # attr name + undef # no attr data + 'CHECK', # compiler phase + ); + + MyClass::Bad:ATTR(SCALAR)( 'MyClass', # class + 'LEXICAL', # no typeglob + \$slr, # referent + 'Bad', # attr name + 0 # eval'd attr data + 'CHECK', # compiler phase + ); + + MyClass::Omni:ATTR(SCALAR)( 'MyClass', # class + 'LEXICAL', # no typeglob + \$slr, # referent + 'Omni', # attr name + '-vorous' # eval'd attr data + 'CHECK', # compiler phase + ); + + + # sub fn :Ugly(sister) :Omni('po',tent()) {...} + + MyClass::UGLY:ATTR(CODE)( 'SomeOtherClass', # class + \*SomeOtherClass::fn, # typeglob + \&SomeOtherClass::fn, # referent + 'Ugly', # attr name + 'sister' # eval'd attr data + 'CHECK', # compiler phase + ); + + MyClass::Omni:ATTR(CODE)( 'SomeOtherClass', # class + \*SomeOtherClass::fn, # typeglob + \&SomeOtherClass::fn, # referent + 'Omni', # attr name + ['po','acle'] # eval'd attr data + 'CHECK', # compiler phase + ); + + + # my @arr :Good :Omni(s/cie/nt/); + + MyClass::Good:ATTR(ARRAY)( 'SomeOtherClass', # class + 'LEXICAL', # no typeglob + \@arr, # referent + 'Good', # attr name + undef # no attr data + 'CHECK', # compiler phase + ); + + MyClass::Omni:ATTR(ARRAY)( 'SomeOtherClass', # class + 'LEXICAL', # no typeglob + \@arr, # referent + 'Omni', # attr name + "" # eval'd attr data + 'CHECK', # compiler phase + ); + + + # my %hsh :Good(q/bye) :Omni(q/bus/); + + MyClass::Good:ATTR(HASH)( 'SomeOtherClass', # class + 'LEXICAL', # no typeglob + \%hsh, # referent + 'Good', # attr name + 'q/bye' # raw attr data + 'CHECK', # compiler phase + ); + + MyClass::Omni:ATTR(HASH)( 'SomeOtherClass', # class + 'LEXICAL', # no typeglob + \%hsh, # referent + 'Omni', # attr name + 'bus' # eval'd attr data + 'CHECK', # compiler phase + ); + + +Installing handlers into UNIVERSAL, makes them...err..universal. +For example: + + package Descriptions; + use Attribute::Handlers; + + my %name; + sub name { return $name{$_[2]}||*{$_[1]}{NAME} } + + sub UNIVERSAL::Name :ATTR { + $name{$_[2]} = $_[4]; + } + + sub UNIVERSAL::Purpose :ATTR { + print STDERR "Purpose of ", &name, " is $_[4]\n"; + } + + sub UNIVERSAL::Unit :ATTR { + print STDERR &name, " measured in $_[4]\n"; + } + +Let's you write: + + use Descriptions; + + my $capacity : Name(capacity) + : Purpose(to store max storage capacity for files) + : Unit(Gb); + + + package Other; + + sub foo : Purpose(to foo all data before barring it) { } + + # etc. + +=head1 UTILITY FUNCTIONS + +This module offers a single utility function, C. + +=over 4 + +=item findsym + + my $symbol = Attribute::Handlers::findsym($package, $referent); + +The function looks in the symbol table of C<$package> for the typeglob for +C<$referent>, which is a reference to a variable or subroutine (SCALAR, ARRAY, +HASH, or CODE). If it finds the typeglob, it returns it. Otherwise, it returns +undef. Note that C memoizes the typeglobs it has previously +successfully found, so subsequent calls with the same arguments should be +much faster. + +=back + +=head1 DIAGNOSTICS + +=over + +=item C + +An attribute handler was specified with an C<:ATTR(I)>, but the +type of referent it was defined to handle wasn't one of the five permitted: +C, C, C, C, or C. + +=item C + +A handler for attributes of the specified name I defined, but not +for the specified type of declaration. Typically encountered when trying +to apply a C attribute handler to a subroutine, or a C +attribute handler to some other type of variable. + +=item C + +A handler for an attributes with an all-lowercase name was declared. An +attribute with an all-lowercase name might have a meaning to Perl +itself some day, even though most don't yet. Use a mixed-case attribute +name, instead. + +=item C + +You just can't, okay? +Instead, put all the specifications together with commas between them +in a single C)>. + +=item C + +You can only declare autoties for types C<"SCALAR">, C<"ARRAY">, and +C<"HASH">. They're the only things (apart from typeglobs -- which are +not declarable) that Perl can tie. + +=item C + +Something is rotten in the state of the program. An attributed +subroutine ceased to exist between the point it was declared and the point +at which its attribute handler(s) would have been called. + +=item C + +You have defined an END handler for an attribute that is being applied +to a lexical variable. Since the variable may not be available during END +this won't happen. + +=back + +=head1 AUTHOR + +Damian Conway (damian@conway.org). The maintainer of this module is now Rafael +Garcia-Suarez (rgarciasuarez@gmail.com). + +Maintainer of the CPAN release is Steffen Mueller (smueller@cpan.org). +Contact him with technical difficulties with respect to the packaging of the +CPAN module. + +=head1 BUGS + +There are undoubtedly serious bugs lurking somewhere in code this funky :-) +Bug reports and other feedback are most welcome. + +=head1 COPYRIGHT AND LICENSE + + Copyright (c) 2001-2014, Damian Conway. All Rights Reserved. + This module is free software. It may be used, redistributed + and/or modified under the same terms as Perl itself. diff --git a/git/usr/share/perl5/core_perl/B/Deparse.pm b/git/usr/share/perl5/core_perl/B/Deparse.pm new file mode 100644 index 0000000000000000000000000000000000000000..668ab90c7e3c41abafe9e24306cbb4b1a0ea2a42 --- /dev/null +++ b/git/usr/share/perl5/core_perl/B/Deparse.pm @@ -0,0 +1,7371 @@ +# B::Deparse.pm +# Copyright (c) 1998-2000, 2002, 2003, 2004, 2005, 2006 Stephen McCamant. +# All rights reserved. +# This module is free software; you can redistribute and/or modify +# it under the same terms as Perl itself. + +# This is based on the module of the same name by Malcolm Beattie, +# but essentially none of his code remains. + +package B::Deparse 1.85; +use strict; +use Carp; +use B qw(class main_root main_start main_cv svref_2object opnumber perlstring + OPf_WANT OPf_WANT_VOID OPf_WANT_SCALAR OPf_WANT_LIST + OPf_KIDS OPf_REF OPf_STACKED OPf_SPECIAL OPf_MOD OPf_PARENS + OPpLVAL_INTRO OPpOUR_INTRO OPpENTERSUB_AMPER OPpSLICE OPpKVSLICE + OPpCONST_BARE OPpEMPTYAVHV_IS_HV + OPpCONST_TOKEN_MASK + OPpCONST_TOKEN_LINE OPpCONST_TOKEN_FILE OPpCONST_TOKEN_PACKAGE + OPpTRANS_SQUASH OPpTRANS_DELETE OPpTRANS_COMPLEMENT OPpTARGET_MY + OPpEXISTS_SUB OPpSORT_NUMERIC OPpSORT_INTEGER OPpREPEAT_DOLIST + OPpSORT_REVERSE OPpMULTIDEREF_EXISTS OPpMULTIDEREF_DELETE + OPpSPLIT_ASSIGN OPpSPLIT_LEX + OPpPADHV_ISKEYS OPpRV2HV_ISKEYS + OPpCONCAT_NESTED + OPpMULTICONCAT_APPEND OPpMULTICONCAT_STRINGIFY OPpMULTICONCAT_FAKE + OPpTRUEBOOL OPpINDEX_BOOLNEG OPpDEFER_FINALLY + OPpARG_IF_UNDEF OPpARG_IF_FALSE + SVf_IOK SVf_NOK SVf_ROK SVf_POK SVf_FAKE SVs_RMG SVs_SMG + SVs_PADTMP + CVf_NOWARN_AMBIGUOUS CVf_LVALUE CVf_IsMETHOD + PMf_KEEP PMf_GLOBAL PMf_CONTINUE PMf_EVAL PMf_ONCE + PMf_MULTILINE PMf_SINGLELINE PMf_FOLD PMf_EXTENDED PMf_EXTENDED_MORE + PADNAMEf_OUTER PADNAMEf_OUR PADNAMEf_TYPED + MDEREF_reload + MDEREF_AV_pop_rv2av_aelem + MDEREF_AV_gvsv_vivify_rv2av_aelem + MDEREF_AV_padsv_vivify_rv2av_aelem + MDEREF_AV_vivify_rv2av_aelem + MDEREF_AV_padav_aelem + MDEREF_AV_gvav_aelem + MDEREF_HV_pop_rv2hv_helem + MDEREF_HV_gvsv_vivify_rv2hv_helem + MDEREF_HV_padsv_vivify_rv2hv_helem + MDEREF_HV_vivify_rv2hv_helem + MDEREF_HV_padhv_helem + MDEREF_HV_gvhv_helem + MDEREF_ACTION_MASK + MDEREF_INDEX_none + MDEREF_INDEX_const + MDEREF_INDEX_padsv + MDEREF_INDEX_gvsv + MDEREF_INDEX_MASK + MDEREF_FLAG_last + MDEREF_MASK + MDEREF_SHIFT + ); + +our $AUTOLOAD; +use warnings (); +require feature; + +use Config; + +BEGIN { + # List version-specific constants here. + # Easiest way to keep this code portable between version looks to + # be to fake up a dummy constant that will never actually be true. + foreach (qw(OPpSORT_INPLACE OPpSORT_DESCEND OPpITER_INDEXED + OPpITER_REVERSED OPpCONST_NOVER + OPpPAD_STATE PMf_SKIPWHITE RXf_SKIPWHITE + PMf_CHARSET PMf_KEEPCOPY PMf_NOCAPTURE CVf_ANONCONST + CVf_LOCKED OPpREVERSE_INPLACE OPpSUBSTR_REPL_FIRST + PMf_NONDESTRUCT OPpEVAL_BYTES + OPpLVREF_TYPE OPpLVREF_SV OPpLVREF_AV OPpLVREF_HV + OPpLVREF_CV OPpLVREF_ELEM SVpad_STATE)) { + eval { B->import($_) }; + no strict 'refs'; + *{$_} = sub () {0} unless *{$_}{CODE}; + } +} + +# Todo: +# (See also BUGS section at the end of this file) +# +# - finish tr/// changes +# - add option for even more parens (generalize \&foo change) +# - left/right context +# - copy comments (look at real text with $^P?) +# - avoid semis in one-statement blocks +# - associativity of &&=, ||=, ?: +# - ',' => '=>' (auto-unquote?) +# - break long lines ("\r" as discretionary break?) +# - configurable syntax highlighting: ANSI color, HTML, TeX, etc. +# - more style options: brace style, hex vs. octal, quotes, ... +# - print big ints as hex/octal instead of decimal (heuristic?) +# - handle 'my $x if 0'? +# - version using op_next instead of op_first/sibling? +# - avoid string copies (pass arrays, one big join?) +# - here-docs? + +# Current test.deparse failures +# comp/hints 6 - location of BEGIN blocks wrt. block openings +# run/switchI 1 - missing -I switches entirely +# perl -Ifoo -e 'print @INC' +# op/caller 2 - warning mask propagates backwards before warnings::register +# 'use warnings; BEGIN {${^WARNING_BITS} eq "U"x12;} use warnings::register' +# op/getpid 2 - can't assign to shared my() declaration (threads only) +# 'my $x : shared = 5' +# op/override 7 - parens on overridden require change v-string interpretation +# 'BEGIN{*CORE::GLOBAL::require=sub {}} require v5.6' +# c.f. 'BEGIN { *f = sub {0} }; f 2' +# op/pat 774 - losing Unicode-ness of Latin1-only strings +# 'use charnames ":short"; $x="\N{latin:a with acute}"' +# op/recurse 12 - missing parens on recursive call makes it look like method +# 'sub f { f($x) }' +# op/subst 90 - inconsistent handling of utf8 under "use utf8" +# op/taint 29 - "use re 'taint'" deparsed in the wrong place wrt. block open +# op/tiehandle compile - "use strict" deparsed in the wrong place +# uni/tr_ several +# ext/B/t/xref 11 - line numbers when we add newlines to one-line subs +# ext/Data/Dumper/t/dumper compile +# ext/DB_file/several +# ext/Encode/several +# ext/Ernno/Errno warnings +# ext/IO/lib/IO/t/io_sel 23 +# ext/PerlIO/t/encoding compile +# ext/POSIX/t/posix 6 +# ext/Socket/Socket 8 +# ext/Storable/t/croak compile +# lib/Attribute/Handlers/t/multi compile +# lib/bignum/ several +# lib/charnames 35 +# lib/constant 32 +# lib/English 40 +# lib/ExtUtils/t/bytes 4 +# lib/File/DosGlob compile +# lib/Filter/Simple/t/data 1 +# lib/Math/BigInt/t/constant 1 +# lib/Net/t/config Deparse-warning +# lib/overload compile +# lib/Switch/ several +# lib/Symbol 4 +# lib/Test/Simple several +# lib/Term/Complete +# lib/Tie/File/t/29_downcopy 5 +# lib/vars 22 + +# Object fields: +# +# in_coderef2text: +# True when deparsing via $deparse->coderef2text; false when deparsing the +# main program. +# +# avoid_local: +# (local($a), local($b)) and local($a, $b) have the same internal +# representation but the short form looks better. We notice we can +# use a large-scale local when checking the list, but need to prevent +# individual locals too. This hash holds the addresses of OPs that +# have already had their local-ness accounted for. The same thing +# is done with my(). +# +# curcv: +# CV for current sub (or main program) being deparsed +# +# curcvlex: +# Cached hash of lexical variables for curcv: keys are +# names prefixed with "m" or "o" (representing my/our), and +# each value is an array with two elements indicating the cop_seq +# of scopes in which a var of that name is valid and a third ele- +# ment referencing the pad name. +# +# curcop: +# COP for statement being deparsed +# +# curstash: +# name of the current package for deparsed code +# +# subs_todo: +# array of [cop_seq, CV, is_format?, name] for subs and formats we still +# want to deparse. The fourth element is a pad name thingy for lexical +# subs or a string for special blocks. For other subs, it is undef. For +# lexical subs, CV may be undef, indicating a stub declaration. +# +# protos_todo: +# as above, but [name, prototype] for subs that never got a GV +# +# subs_done, forms_done: +# keys are addresses of GVs for subs and formats we've already +# deparsed (or at least put into subs_todo) +# +# subs_declared +# keys are names of subs for which we've printed declarations. +# That means we can omit parentheses from the arguments. It also means we +# need to put CORE:: on core functions of the same name. +# +# in_subst_repl +# True when deparsing the replacement part of a substitution. +# +# in_refgen +# True when deparsing the argument to \. +# +# parens: -p +# linenums: -l +# unquote: -q +# cuddle: ' ' or '\n', depending on -sC +# indent_size: -si +# use_tabs: -sT +# ex_const: -sv + +# A little explanation of how precedence contexts and associativity +# work: +# +# deparse() calls each per-op subroutine with an argument $cx (short +# for context, but not the same as the cx* in the perl core), which is +# a number describing the op's parents in terms of precedence, whether +# they're inside an expression or at statement level, etc. (see +# chart below). When ops with children call deparse on them, they pass +# along their precedence. Fractional values are used to implement +# associativity ('($x + $y) + $z' => '$x + $y + $y') and related +# parentheses hacks. The major disadvantage of this scheme is that +# it doesn't know about right sides and left sides, so say if you +# assign a listop to a variable, it can't tell it's allowed to leave +# the parens off the listop. + +# Precedences: +# 26 [TODO] inside interpolation context ("") +# 25 left terms and list operators (leftward) +# 24 left -> +# 23 nonassoc ++ -- +# 22 right ** +# 21 right ! ~ \ and unary + and - +# 20 left =~ !~ +# 19 left * / % x +# 18 left + - . +# 17 left << >> +# 16 nonassoc named unary operators +# 15 nonassoc < > <= >= lt gt le ge +# 14 nonassoc == != <=> eq ne cmp +# 13 left & +# 12 left | ^ +# 11 left && +# 10 left || +# 9 nonassoc .. ... +# 8 right ?: +# 7 right = += -= *= etc. +# 6 left , => +# 5 nonassoc list operators (rightward) +# 4 right not +# 3 left and +# 2 left or xor +# 1 statement modifiers +# 0.5 statements, but still print scopes as do { ... } +# 0 statement level +# -1 format body + +# Nonprinting characters with special meaning: +# \cS - steal parens (see maybe_parens_unop) +# \n - newline and indent +# \t - increase indent +# \b - decrease indent ('outdent') +# \f - flush left (no indent) +# \cK - kill following semicolon, if any + +# Semicolon handling: +# - Individual statements are not deparsed with trailing semicolons. +# (If necessary, \cK is tacked on to the end.) +# - Whatever code joins statements together or emits them (lineseq, +# scopeop, deparse_root) is responsible for adding semicolons where +# necessary. +# - use statements are deparsed with trailing semicolons because they are +# immediately concatenated with the following statement. +# - indent() removes semicolons wherever it sees \cK. + + +BEGIN { for (qw[ const stringify rv2sv list glob pushmark null aelem + kvaslice kvhslice padsv argcheck + nextstate dbstate rv2av rv2hv helem pushdefer leavetrycatch + custom ]) { + eval "sub OP_\U$_ () { " . opnumber($_) . "}" +}} + +# _pessimise_walk(): recursively walk the optree of a sub, +# possibly undoing optimisations along the way. + +sub DEBUG { 0 } +use if DEBUG, 'Data::Dumper'; + +sub _pessimise_walk { + my ($self, $startop) = @_; + + return unless $$startop; + my ($op, $prevop); + for ($op = $startop; $$op; $prevop = $op, $op = $op->sibling) { + my $ppname = $op->name; + + # pessimisations start here + + if ($ppname eq "padrange") { + # remove PADRANGE: + # the original optimisation either (1) changed this: + # pushmark -> (various pad and list and null ops) -> the_rest + # or (2), for the = @_ case, changed this: + # pushmark -> gv[_] -> rv2av -> (pad stuff) -> the_rest + # into this: + # padrange ----------------------------------------> the_rest + # so we just need to convert the padrange back into a + # pushmark, and in case (1), set its op_next to op_sibling, + # which is the head of the original chain of optimised-away + # pad ops, or for (2), set it to sibling->first, which is + # the original gv[_]. + + $B::overlay->{$$op} = { + type => OP_PUSHMARK, + name => 'pushmark', + private => ($op->private & OPpLVAL_INTRO), + }; + } + + # pessimisations end here + + if (class($op) eq 'PMOP') { + if (ref($op->pmreplroot) + && ${$op->pmreplroot} + && $op->pmreplroot->isa( 'B::OP' )) + { + $self-> _pessimise_walk($op->pmreplroot); + } + + # pessimise any /(?{...})/ code blocks + my ($re, $cv); + my $code_list = $op->code_list; + if ($$code_list) { + $self->_pessimise_walk($code_list); + } + elsif (${$re = $op->pmregexp} && ${$cv = $re->qr_anoncv}) { + $code_list = $cv->ROOT # leavesub + ->first # qr + ->code_list; # list + $self->_pessimise_walk($code_list); + } + } + + if ($op->flags & OPf_KIDS) { + $self-> _pessimise_walk($op->first); + } + + } +} + + +# _pessimise_walk_exe(): recursively walk the op_next chain of a sub, +# possibly undoing optimisations along the way. + +sub _pessimise_walk_exe { + my ($self, $startop, $visited) = @_; + + no warnings 'recursion'; + + return unless $$startop; + return if $visited->{$$startop}; + my ($op, $prevop); + for ($op = $startop; $$op; $prevop = $op, $op = $op->next) { + last if $visited->{$$op}; + $visited->{$$op} = 1; + my $ppname = $op->name; + if ($ppname =~ + /^((and|d?or)(assign)?|(map|grep)while|range|cond_expr|once)$/ + # entertry is also a logop, but its op_other invariably points + # into the same chain as the main execution path, so we skip it + ) { + $self->_pessimise_walk_exe($op->other, $visited); + } + elsif ($ppname eq "subst") { + $self->_pessimise_walk_exe($op->pmreplstart, $visited); + } + elsif ($ppname =~ /^(enter(loop|iter))$/) { + # redoop and nextop will already be covered by the main block + # of the loop + $self->_pessimise_walk_exe($op->lastop, $visited); + } + + # pessimisations start here + } +} + +# Go through an optree and "remove" some optimisations by using an +# overlay to selectively modify or un-null some ops. Deparsing in the +# absence of those optimisations is then easier. +# +# Note that older optimisations are not removed, as Deparse was already +# written to recognise them before the pessimise/overlay system was added. + +sub pessimise { + my ($self, $root, $start) = @_; + + no warnings 'recursion'; + # walk tree in root-to-branch order + $self->_pessimise_walk($root); + + my %visited; + # walk tree in execution order + $self->_pessimise_walk_exe($start, \%visited); +} + + +sub null { + my $op = shift; + return class($op) eq "NULL"; +} + + +# Add a CV to the list of subs that still need deparsing. + +sub todo { + my $self = shift; + my($cv, $is_form, $name) = @_; + my $cvfile = $cv->FILE//''; + return unless ($cvfile eq $0 || exists $self->{files}{$cvfile}); + my $seq; + if ($cv->OUTSIDE_SEQ) { + $seq = $cv->OUTSIDE_SEQ; + } elsif (!null($cv->START) and is_state($cv->START)) { + $seq = $cv->START->cop_seq; + } else { + $seq = 0; + } + my $stash = $cv->STASH; + if (class($stash) eq 'HV') { + $self->{packs}{$stash->NAME}++; + } + push @{$self->{'subs_todo'}}, [$seq, $cv, $is_form, $name]; +} + + +# Pop the next sub from the todo list and deparse it + +sub next_todo { + my $self = shift; + my $ent = shift @{$self->{'subs_todo'}}; + my ($seq, $cv, $is_form, $name) = @$ent; + + # any 'use strict; package foo' that should come before the sub + # declaration to sync with the first COP of the sub + my $pragmata = ''; + if ($cv and !null($cv->START) and is_state($cv->START)) { + $pragmata = $self->pragmata($cv->START); + } + + if (ref $name) { # lexical sub + # emit the sub. + my @text; + my $flags = $name->FLAGS; + my $category = + !$cv || $seq <= $name->COP_SEQ_RANGE_LOW + ? $self->keyword($flags & PADNAMEf_OUR + ? "our" + : $flags & SVpad_STATE + ? "state" + : "my") . " " + : ""; + + # Skip lexical 'state' subs imported from the builtin:: + # package, since they are created automatically by + # use builtin "foo" + if ($cv && $category =~ /\bstate\b/) { + my $globname; + my $gv = $cv->GV; + if ( + $gv && $gv->isa('B::GV') + && defined (($globname = $gv->object_2svref)) + && $$globname =~ /^\*builtin::/ + ) { + return ''; + } + } + + push @text, $category; + + # XXX We would do $self->keyword("sub"), but ‘my CORE::sub’ + # doesn’t work and ‘my sub’ ignores a &sub in scope. I.e., + # we have a core bug here. + my $kw = $cv ? $self->kw_sub_or_method($cv) : "sub"; + push @text, "$kw " . substr $name->PVX, 1; + if ($cv) { + # my sub foo { } + push @text, " " . $self->deparse_sub($cv); + $text[-1] =~ s/ ;$/;/; + } + else { + # my sub foo; + push @text, ";\n"; + } + return $pragmata . join "", @text; + } + + my $gv = $cv->GV; + $name //= $self->gv_name($gv); + if ($is_form) { + return $pragmata . $self->keyword("format") . " $name =\n" + . $self->deparse_format($cv). "\n"; + } else { + my $use_dec; + if ($name eq "BEGIN") { + $use_dec = $self->begin_is_use($cv); + if (defined ($use_dec) and $self->{'expand'} < 5) { + return $pragmata if 0 == length($use_dec); + + # XXX bit of a hack: Test::More's use_ok() method + # builds a fake use statement which deparses as, e.g. + # use Net::Ping (@{$args[0];}); + # As well as being superfluous (the use_ok() is deparsed + # too) and ugly, it fails under use strict and otherwise + # makes use of a lexical var that's not in scope. + # So strip it out. + return $pragmata + if $use_dec =~ + m/ + \A + use \s \S+ \s \(\@\{ + ( + \s*\#line\ \d+\ \".*"\s* + )? + \$args\[0\];\}\); + \n + \Z + /x; + + $use_dec =~ s/^(use|no)\b/$self->keyword($1)/e; + } + } + my $l = ''; + if ($self->{'linenums'}) { + my $line = $gv->LINE; + my $file = $gv->FILE; + $l = "\n\f#line $line \"$file\"\n"; + } + my $p = ''; + my $stash; + if (class($cv->STASH) ne "SPECIAL") { + $stash = $cv->STASH->NAME; + if ($stash ne $self->{'curstash'}) { + $p = $self->keyword("package") . " $stash;\n"; + $name = "$self->{'curstash'}::$name" unless $name =~ /::/; + $self->{'curstash'} = $stash; + } + } + if ($use_dec) { + return "$pragmata$p$l$use_dec"; + } + if ( $name !~ /::/ and $self->lex_in_scope("&$name") + || $self->lex_in_scope("&$name", 1) ) + { + $name = "$self->{'curstash'}::$name"; + } elsif (defined $stash) { + $name =~ s/^\Q$stash\E::(?!\z|.*::)//; + } + my $ret = "$pragmata${p}${l}" . $self->keyword($self->kw_sub_or_method($cv)) . " $name " + . $self->deparse_sub($cv); + $self->{'subs_declared'}{$name} = 1; + return $ret; + } +} + + +# Return a "use" declaration for this BEGIN block, if appropriate +sub begin_is_use { + my ($self, $cv) = @_; + my $root = $cv->ROOT; + local @$self{qw'curcv curcvlex'} = ($cv); + local $B::overlay = {}; + $self->pessimise($root, $cv->START); +#require B::Debug; +#B::walkoptree($cv->ROOT, "debug"); + my $lineseq = $root->first; + return if $lineseq->name ne "lineseq"; + + my $req_op = $lineseq->first->sibling; + return if $req_op->name ne "require"; + + # maybe it's C rather than C + return if ($req_op->first->name ne 'const'); + + my $module; + if ($req_op->first->private & OPpCONST_BARE) { + # Actually it should always be a bareword + $module = $self->const_sv($req_op->first)->PV; + $module =~ s[/][::]g; + $module =~ s/.pm$//; + } + else { + $module = $self->const($self->const_sv($req_op->first), 6); + } + + my $version; + my $version_op = $req_op->sibling; + return if class($version_op) eq "NULL"; + if ($version_op->name eq "lineseq") { + # We have a version parameter; skip nextstate & pushmark + my $constop = $version_op->first->next->next; + + return unless $self->const_sv($constop)->PV eq $module; + $constop = $constop->sibling; + $version = $self->const_sv($constop); + if (class($version) eq "IV") { + $version = $version->int_value; + } elsif (class($version) eq "NV") { + $version = $version->NV; + } elsif (class($version) ne "PVMG") { + # Includes PVIV and PVNV + $version = $version->PV; + } else { + # version specified as a v-string + $version = 'v'.join '.', map ord, split //, $version->PV; + } + $constop = $constop->sibling; + return if $constop->name ne "method_named"; + return if $self->meth_sv($constop)->PV ne "VERSION"; + } + + $lineseq = $version_op->sibling; + return if $lineseq->name ne "lineseq"; + my $entersub = $lineseq->first->sibling; + if ($entersub->name eq "stub") { + return "use $module $version ();\n" if defined $version; + return "use $module ();\n"; + } + return if $entersub->name ne "entersub"; + + # See if there are import arguments + my $args = ''; + + my $svop = $entersub->first->sibling; # Skip over pushmark + return unless $self->const_sv($svop)->PV eq $module; + + # Pull out the arguments + for ($svop=$svop->sibling; index($svop->name, "method_") != 0; + $svop = $svop->sibling) { + $args .= ", " if length($args); + $args .= $self->deparse($svop, 6); + } + + my $use = 'use'; + my $method_named = $svop; + return if $method_named->name ne "method_named"; + my $method_name = $self->meth_sv($method_named)->PV; + + if ($method_name eq "unimport") { + $use = 'no'; + } + + # Certain pragmas are dealt with using hint bits, + # so we ignore them here + if ($module eq 'strict' || $module eq 'integer' + || $module eq 'bytes' || $module eq 'warnings' + || $module eq 'feature') { + return ""; + } + + if (defined $version && length $args) { + return "$use $module $version ($args);\n"; + } elsif (defined $version) { + return "$use $module $version;\n"; + } elsif (length $args) { + return "$use $module ($args);\n"; + } else { + return "$use $module;\n"; + } +} + +sub stash_subs { + my ($self, $pack, $seen) = @_; + my (@ret, $stash); + if (!defined $pack) { + $pack = ''; + $stash = \%::; + } + else { + $pack =~ s/(::)?$/::/; + no strict 'refs'; + $stash = \%{"main::$pack"}; + } + return + if ($seen ||= {})->{ + $INC{"overload.pm"} ? overload::StrVal($stash) : $stash + }++; + my $stashobj = svref_2object($stash); + my %stash = $stashobj->ARRAY; + while (my ($key, $val) = each %stash) { + my $flags = $val->FLAGS; + if ($flags & SVf_ROK) { + # A reference. Dump this if it is a reference to a CV. If it + # is a constant acting as a proxy for a full subroutine, then + # we may or may not have to dump it. If some form of perl- + # space visible code must have created it, be it a use + # statement, or some direct symbol-table manipulation code that + # we will deparse, then we don’t want to dump it. If it is the + # result of a declaration like sub f () { 42 } then we *do* + # want to dump it. The only way to distinguish these seems + # to be the SVs_PADTMP flag on the constant, which is admit- + # tedly a hack. + my $class = class(my $referent = $val->RV); + if ($class eq "CV") { + $self->todo($referent, 0); + } elsif ( + $class !~ /^(AV|HV|CV|FM|IO|SPECIAL)\z/ + # A more robust way to write that would be this, but B does + # not provide the SVt_ constants: + # ($referent->FLAGS & B::SVTYPEMASK) < B::SVt_PVAV + and $referent->FLAGS & SVs_PADTMP + ) { + push @{$self->{'protos_todo'}}, [$pack . $key, $val]; + } + } elsif ($flags & (SVf_POK|SVf_IOK)) { + # Just a prototype. As an ugly but fairly effective way + # to find out if it belongs here is to see if the AUTOLOAD + # (if any) for the stash was defined in one of our files. + my $A = $stash{"AUTOLOAD"}; + if (defined ($A) && class($A) eq "GV" && defined($A->CV) + && class($A->CV) eq "CV") { + my $AF = $A->FILE; + next unless $AF eq $0 || exists $self->{'files'}{$AF}; + } + push @{$self->{'protos_todo'}}, + [$pack . $key, $flags & SVf_POK ? $val->PV: undef]; + } elsif (class($val) eq "GV") { + if (class(my $cv = $val->CV) ne "SPECIAL") { + next if $self->{'subs_done'}{$$val}++; + + # Ignore imposters (aliases etc) + my $name = $cv->NAME_HEK; + if(defined $name) { + # avoid using $cv->GV here because if the $val GV is + # an alias, CvGV() could upgrade the real stash entry + # from an RV to a GV + next unless $name eq $key; + next unless $$stashobj == ${$cv->STASH}; + } + else { + next if $$val != ${$cv->GV}; + } + + $self->todo($cv, 0); + } + if (class(my $cv = $val->FORM) ne "SPECIAL") { + next if $self->{'forms_done'}{$$val}++; + next if $$val != ${$cv->GV}; # Ignore imposters + $self->todo($cv, 1); + } + if (class($val->HV) ne "SPECIAL" && $key =~ /::$/) { + $self->stash_subs($pack . $key, $seen); + } + } + } +} + +sub print_protos { + my $self = shift; + my $ar; + my @ret; + foreach $ar (@{$self->{'protos_todo'}}) { + if (ref $ar->[1]) { + # Only print a constant if it occurs in the same package as a + # dumped sub. This is not perfect, but a heuristic that will + # hopefully work most of the time. Ideally we would use + # CvFILE, but a constant stub has no CvFILE. + my $pack = ($ar->[0] =~ /(.*)::/)[0]; + next if $pack and !$self->{packs}{$pack} + } + my $body = defined $ar->[1] + ? ref $ar->[1] + ? " () {\n " . $self->const($ar->[1]->RV,0) . ";\n}" + : " (". $ar->[1] . ");" + : ";"; + push @ret, "sub " . $ar->[0] . "$body\n"; + } + delete $self->{'protos_todo'}; + return @ret; +} + +sub style_opts { + my $self = shift; + my $opts = shift; + my $opt; + while (length($opt = substr($opts, 0, 1))) { + if ($opt eq "C") { + $self->{'cuddle'} = " "; + $opts = substr($opts, 1); + } elsif ($opt eq "i") { + $opts =~ s/^i(\d+)//; + $self->{'indent_size'} = $1; + } elsif ($opt eq "T") { + $self->{'use_tabs'} = 1; + $opts = substr($opts, 1); + } elsif ($opt eq "v") { + $opts =~ s/^v([^.]*)(.|$)//; + $self->{'ex_const'} = $1; + } + } +} + +sub new { + my $class = shift; + my $self = bless {}, $class; + $self->{'cuddle'} = "\n"; + $self->{'curcop'} = undef; + $self->{'curstash'} = "main"; + $self->{'ex_const'} = "'???'"; + $self->{'expand'} = 0; + $self->{'files'} = {}; + $self->{'packs'} = {}; + $self->{'indent_size'} = 4; + $self->{'linenums'} = 0; + $self->{'parens'} = 0; + $self->{'subs_todo'} = []; + $self->{'unquote'} = 0; + $self->{'use_dumper'} = 0; + $self->{'use_tabs'} = 0; + + $self->{'ambient_warnings'} = undef; # Assume no lexical warnings + $self->{'ambient_hints'} = 0; + $self->{'ambient_hinthash'} = undef; + $self->init(); + + while (my $arg = shift @_) { + if ($arg eq "-d") { + $self->{'use_dumper'} = 1; + require Data::Dumper; + } elsif ($arg =~ /^-f(.*)/) { + $self->{'files'}{$1} = 1; + } elsif ($arg eq "-l") { + $self->{'linenums'} = 1; + } elsif ($arg eq "-p") { + $self->{'parens'} = 1; + } elsif ($arg eq "-P") { + $self->{'noproto'} = 1; + } elsif ($arg eq "-q") { + $self->{'unquote'} = 1; + } elsif (substr($arg, 0, 2) eq "-s") { + $self->style_opts(substr $arg, 2); + } elsif ($arg =~ /^-x(\d)$/) { + $self->{'expand'} = $1; + } + } + return $self; +} + + +# Initialise the contextual information, either from +# defaults provided with the ambient_pragmas method, +# or from perl's own defaults otherwise. +sub init { + my $self = shift; + + $self->{'warnings'} = $self->{'ambient_warnings'}; + $self->{'hints'} = $self->{'ambient_hints'}; + $self->{'hinthash'} = $self->{'ambient_hinthash'}; + + # also a convenient place to clear out subs_declared + delete $self->{'subs_declared'}; +} + +sub compile { + my(@args) = @_; + return sub { + my $self = B::Deparse->new(@args); + # First deparse command-line args + if (defined $^I) { # deparse -i + print q(BEGIN { $^I = ).perlstring($^I).qq(; }\n); + } + if ($^W) { # deparse -w + print qq(BEGIN { \$^W = $^W; }\n); + } + if ($/ ne "\n" or defined $O::savebackslash) { # deparse -l and -0 + my $fs = perlstring($/) || 'undef'; + my $bs = perlstring($O::savebackslash) || 'undef'; + print qq(BEGIN { \$/ = $fs; \$\\ = $bs; }\n); + } + my @BEGINs = B::begin_av->isa("B::AV") ? B::begin_av->ARRAY : (); + my @UNITCHECKs = B::unitcheck_av->isa("B::AV") + ? B::unitcheck_av->ARRAY + : (); + my @CHECKs = B::check_av->isa("B::AV") ? B::check_av->ARRAY : (); + my @INITs = B::init_av->isa("B::AV") ? B::init_av->ARRAY : (); + my @ENDs = B::end_av->isa("B::AV") ? B::end_av->ARRAY : (); + my @names = qw(BEGIN UNITCHECK CHECK INIT END); + my @blocks = \(@BEGINs, @UNITCHECKs, @CHECKs, @INITs, @ENDs); + while (@names) { + my ($name, $blocks) = (shift @names, shift @blocks); + for my $block (@$blocks) { + $self->todo($block, 0, $name); + } + } + $self->stash_subs(); + local($SIG{"__DIE__"}) = + sub { + if ($self->{'curcop'}) { + my $cop = $self->{'curcop'}; + my($line, $file) = ($cop->line, $cop->file); + print STDERR "While deparsing $file near line $line,\n"; + } + }; + $self->{'curcv'} = main_cv; + $self->{'curcvlex'} = undef; + print $self->print_protos; + @{$self->{'subs_todo'}} = + sort {$a->[0] <=> $b->[0]} @{$self->{'subs_todo'}}; + my $root = main_root; + local $B::overlay = {}; + unless (null $root) { + $self->pad_subs($self->{'curcv'}); + # Check for a stub-followed-by-ex-cop, resulting from a program + # consisting solely of sub declarations. For backward-compati- + # bility (and sane output) we don’t want to emit the stub. + # leave + # enter + # stub + # ex-nextstate (or ex-dbstate) + my $kid; + if ( $root->name eq 'leave' + and ($kid = $root->first)->name eq 'enter' + and !null($kid = $kid->sibling) and $kid->name eq 'stub' + and !null($kid = $kid->sibling) and $kid->name eq 'null' + and class($kid) eq 'COP' and null $kid->sibling ) + { + # ignore + } else { + $self->pessimise($root, main_start); + print $self->indent($self->deparse_root($root)), "\n"; + } + } + my @text; + while (scalar(@{$self->{'subs_todo'}})) { + push @text, $self->next_todo; + } + print $self->indent(join("", @text)), "\n" if @text; + + # Print __DATA__ section, if necessary + no strict 'refs'; + my $laststash = defined $self->{'curcop'} + ? $self->{'curcop'}->stash->NAME : $self->{'curstash'}; + if (defined *{$laststash."::DATA"}{IO}) { + print $self->keyword("package") . " $laststash;\n" + unless $laststash eq $self->{'curstash'}; + print $self->keyword("__DATA__") . "\n"; + print readline(*{$laststash."::DATA"}); + } + } +} + +sub coderef2text { + my $self = shift; + my $sub = shift; + croak "Usage: ->coderef2text(CODEREF)" unless UNIVERSAL::isa($sub, "CODE"); + + $self->init(); + local $self->{in_coderef2text} = 1; + return $self->indent($self->deparse_sub(svref_2object($sub))); +} + +my %strict_bits = do { + local $^H; + map +($_ => strict::bits($_)), qw/refs subs vars/ +}; + +sub ambient_pragmas { + my $self = shift; + my ($hint_bits, $warning_bits, $hinthash) = (0); + + while (@_ > 1) { + my $name = shift(); + my $val = shift(); + + if ($name eq 'strict') { + require strict; + + if ($val eq 'none') { + $hint_bits &= $strict_bits{$_} for qw/refs subs vars/; + next(); + } + + my @names; + if ($val eq "all") { + @names = qw/refs subs vars/; + } + elsif (ref $val) { + @names = @$val; + } + else { + @names = split' ', $val; + } + $hint_bits |= $strict_bits{$_} for @names; + } + + elsif ($name eq 'integer' + || $name eq 'bytes' + || $name eq 'utf8') { + require "$name.pm"; + if ($val) { + $hint_bits |= ${$::{"${name}::"}{"hint_bits"}}; + } + else { + $hint_bits &= ~${$::{"${name}::"}{"hint_bits"}}; + } + } + + elsif ($name eq 're') { + require re; + if ($val eq 'none') { + $hint_bits &= ~re::bits(qw/taint eval/); + next(); + } + + my @names; + if ($val eq 'all') { + @names = qw/taint eval/; + } + elsif (ref $val) { + @names = @$val; + } + else { + @names = split' ',$val; + } + $hint_bits |= re::bits(@names); + } + + elsif ($name eq 'warnings') { + if ($val eq 'none') { + $warning_bits = $warnings::NONE; + next(); + } + + my @names; + if (ref $val) { + @names = @$val; + } + else { + @names = split/\s+/, $val; + } + + $warning_bits = $warnings::NONE if !defined ($warning_bits); + $warning_bits |= warnings::bits(@names); + } + + elsif ($name eq 'warning_bits') { + $warning_bits = $val; + } + + elsif ($name eq 'hint_bits') { + $hint_bits = $val; + } + + elsif ($name eq '%^H') { + $hinthash = $val; + } + + else { + croak "Unknown pragma type: $name"; + } + } + if (@_) { + croak "The ambient_pragmas method expects an even number of args"; + } + + $self->{'ambient_warnings'} = $warning_bits; + $self->{'ambient_hints'} = $hint_bits; + $self->{'ambient_hinthash'} = $hinthash; +} + +# This method is the inner loop, so try to keep it simple +sub deparse { + my $self = shift; + my($op, $cx) = @_; + + Carp::confess("Null op in deparse") if !defined($op) + || class($op) eq "NULL"; + my $meth = "pp_" . $op->name; + return $self->$meth($op, $cx); +} + +sub indent { + my $self = shift; + my $txt = shift; + # \cK also swallows a preceding line break when followed by a + # semicolon. + $txt =~ s/\n\cK;//g; + my @lines = split(/\n/, $txt); + my $leader = ""; + my $level = 0; + my $line; + for $line (@lines) { + my $cmd = substr($line, 0, 1); + if ($cmd eq "\t" or $cmd eq "\b") { + $level += ($cmd eq "\t" ? 1 : -1) * $self->{'indent_size'}; + if ($self->{'use_tabs'}) { + $leader = "\t" x ($level / 8) . " " x ($level % 8); + } else { + $leader = " " x $level; + } + $line = substr($line, 1); + } + if (index($line, "\f") > 0) { + $line =~ s/\f/\n/; + } + if (substr($line, 0, 1) eq "\f") { + $line = substr($line, 1); # no indent + } else { + $line = $leader . $line; + } + $line =~ s/\cK;?//g; + } + return join("\n", @lines); +} + +sub pad_subs { + my ($self, $cv) = @_; + my $padlist = $cv->PADLIST; + my @names = $padlist->ARRAYelt(0)->ARRAY; + my @values = $padlist->ARRAYelt(1)->ARRAY; + my @todo; + PADENTRY: + for my $ix (0.. $#names) { for $_ ($names[$ix]) { + next if class($_) eq "SPECIAL"; + my $name = $_->PVX; + if (defined $name && $name =~ /^&./) { + my $low = $_->COP_SEQ_RANGE_LOW; + my $flags = $_->FLAGS; + my $outer = $flags & PADNAMEf_OUTER; + if ($flags & PADNAMEf_OUR) { + push @todo, [$low, undef, 0, $_] + # [seq, no cv, not format, padname] + unless $outer; + next; + } + my $protocv = $flags & SVpad_STATE + ? $values[$ix] + : $_->PROTOCV; + if (class ($protocv) ne 'CV') { + my $flags = $flags; + my $cv = $cv; + my $name = $_; + while ($flags & PADNAMEf_OUTER && class ($protocv) ne 'CV') + { + $cv = $cv->OUTSIDE; + next PADENTRY if class($cv) eq 'SPECIAL'; # XXX freed? + my $padlist = $cv->PADLIST; + my $ix = $name->PARENT_PAD_INDEX; + $name = $padlist->NAMES->ARRAYelt($ix); + $flags = $name->FLAGS; + $protocv = $flags & SVpad_STATE + ? $padlist->ARRAYelt(1)->ARRAYelt($ix) + : $name->PROTOCV; + } + } + my $defined_in_this_sub = ${$protocv->OUTSIDE} == $$cv || do { + my $other = $protocv->PADLIST; + $$other && $other->outid == $padlist->id; + }; + if ($flags & PADNAMEf_OUTER) { + next unless $defined_in_this_sub; + push @todo, [$protocv->OUTSIDE_SEQ, $protocv, 0, $_]; + next; + } + my $outseq = $protocv->OUTSIDE_SEQ; + if ($outseq <= $low) { + # defined before its name is visible, so it’s gotta be + # declared and defined at once: my sub foo { ... } + push @todo, [$low, $protocv, 0, $_]; + } + else { + # declared and defined separately: my sub f; sub f { ... } + push @todo, [$low, undef, 0, $_]; + push @todo, [$outseq, $protocv, 0, $_] + if $defined_in_this_sub; + } + } + }} + @{$self->{'subs_todo'}} = + sort {$a->[0] <=> $b->[0]} @{$self->{'subs_todo'}}, @todo +} + + +# deparse_argops(): deparse, if possible, a sequence of argcheck + argelem +# ops into a subroutine signature. If successful, return the first op +# following the signature ops plus the signature string; else return the +# empty list. +# +# Normally a bunch of argelem ops will have been generated by the +# signature parsing, but it's possible that ops have been added manually +# or altered. In this case we return "()" and fall back to general +# deparsing of the individual sigelems as 'my $x = $_[N]' etc. +# +# We're only called if the top is an ex-argcheck, which is a placeholder +# indicating a signature subtree. +# +# Return a signature string, or an empty list if no deparseable as a +# signature + +sub deparse_argops { + my ($self, $topop, $cv) = @_; + + my @sig; + + + $topop = $topop->first; + return unless $$topop and $topop->name eq 'lineseq'; + + + # last op should be nextstate + my $last = $topop->last; + return unless $$last + and ( _op_is_or_was($last, OP_NEXTSTATE) + or _op_is_or_was($last, OP_DBSTATE)); + + # first OP_NEXTSTATE + + my $o = $topop->first; + return unless $$o; + return if $o->label; + + # OP_ARGCHECK + + $o = $o->sibling; + return unless $$o and $o->name eq 'argcheck'; + + my ($params, $opt_params, $slurpy) = $o->aux_list($cv); + my $mandatory = $params - $opt_params; + my $seen_slurpy = 0; + my $last_ix = -1; + + # keep looking for valid nextstate + argelem pairs, terminated + # by a final nextstate + + while (1) { + $o = $o->sibling; + return unless $$o; + + # skip trailing nextstate + last if $$o == $$last; + + # OP_NEXTSTATE + return unless $o->name =~ /^(next|db)state$/; + return if $o->label; + + # OP_ARGELEM + $o = $o->sibling; + last unless $$o; + + if ($o->name eq 'argelem') { + my $ix = $o->string($cv); + while (++$last_ix < $ix) { + push @sig, $last_ix < $mandatory ? '$' : '$='; + } + my $var = $self->padname($o->targ); + if ($var =~ /^[@%]/) { + return if $seen_slurpy; + $seen_slurpy = 1; + return if $ix != $params or !$slurpy + or substr($var,0,1) ne $slurpy; + } + else { + return if $ix >= $params; + } + if ($o->flags & OPf_KIDS) { + my $kid = $o->first; + return unless $$kid and $kid->name eq 'argdefelem'; + my $def = $self->deparse($kid->first, 7); + $def = "($def)" if $kid->first->flags & OPf_PARENS; + my $assign = "="; + $assign = "//=" if $kid->private & OPpARG_IF_UNDEF; + $assign = "||=" if $kid->private & OPpARG_IF_FALSE; + $var .= " $assign $def"; + } + push @sig, $var; + } + elsif ($o->name eq 'null' + and ($o->flags & OPf_KIDS) + and $o->first->name eq 'argdefelem') + { + # special case - a void context default expression: $ = expr + + my $defop = $o->first; + my $ix = $defop->targ; + while (++$last_ix < $ix) { + push @sig, $last_ix < $mandatory ? '$' : '$='; + } + return if $last_ix >= $params + or $last_ix < $mandatory; + my $def = $self->deparse($defop->first, 7); + $def = "($def)" if $defop->first->flags & OPf_PARENS; + push @sig, '$ = ' . $def; + } + else { + return; + } + + } + + while (++$last_ix < $params) { + push @sig, $last_ix < $mandatory ? '$' : '$='; + } + push @sig, $slurpy if $slurpy and !$seen_slurpy; + + return (join(', ', @sig)); +} + + +sub kw_sub_or_method { + my $self = shift; + my $cv = shift; + return ($cv->CvFLAGS & CVf_IsMETHOD) ? "method" : "sub"; +} + +# Deparse a sub. Returns everything except the 'sub foo', +# e.g. ($$) : method { ...; } +# or : prototype($$) lvalue ($a, $b) { ...; }; + +sub deparse_sub { + my $self = shift; + my $cv = shift; + my @attrs; + my $proto; + my $sig; + +Carp::confess("NULL in deparse_sub") if !defined($cv) || $cv->isa("B::NULL"); +Carp::confess("SPECIAL in deparse_sub") if $cv->isa("B::SPECIAL"); + local $self->{'curcop'} = $self->{'curcop'}; + + my $has_sig = $self->feature_enabled('signatures'); + if ($cv->FLAGS & SVf_POK) { + my $myproto = $cv->PV; + if ($has_sig) { + push @attrs, "prototype($myproto)"; + } + else { + $proto = $myproto; + } + } + my $cv_flags = $cv->CvFLAGS; + my $is_method = $cv_flags & CVf_IsMETHOD; + + if ($cv_flags & (CVf_NOWARN_AMBIGUOUS|CVf_LOCKED|CVf_LVALUE|CVf_ANONCONST)) { + push @attrs, "lvalue" if $cv_flags & CVf_LVALUE; + push @attrs, "method" if $cv_flags & CVf_NOWARN_AMBIGUOUS and !$is_method; + push @attrs, "const" if $cv_flags & CVf_ANONCONST; + } + + local($self->{'curcv'}) = $cv; + local($self->{'curcvlex'}); + local(@$self{qw'curstash warnings hints hinthash'}) + = @$self{qw'curstash warnings hints hinthash'}; + my $body; + my $root = $cv->ROOT; + local $B::overlay = {}; + if (not null $root) { + $self->pad_subs($cv); + $self->pessimise($root, $cv->START); + my $lineseq = $root->first; + + # stub sub may have single op rather than list of ops + my $is_list = ($lineseq->name eq "lineseq"); + my $firstop = $is_list ? $lineseq->first : $lineseq; + + if ($is_method and $firstop->name eq "methstart") { + $firstop = $firstop->sibling; + } + + # Try to deparse first subtree as a signature if possible. + # Top of signature subtree has an ex-argcheck as a placeholder + if ( $has_sig + and $$firstop + and $firstop->name eq 'null' + and $firstop->targ == OP_ARGCHECK + ) { + my ($mysig) = $self->deparse_argops($firstop, $cv); + if (defined $mysig) { + $sig = $mysig; + $firstop = $is_list ? $firstop->sibling : undef; + } + } + + if ($is_list && $firstop) { + my @ops; + for (my $o = $firstop; $$o; $o=$o->sibling) { + push @ops, $o; + } + $body = $self->lineseq(undef, 0, @ops).";"; + if (!$has_sig and $ops[-1]->name =~ /^(next|db)state$/) { + # this handles void context in + # use feature signatures; sub ($=1) {} + $body .= "\n()"; + } + my $scope_en = $self->find_scope_en($lineseq); + if (defined $scope_en) { + my $subs = join"", $self->seq_subs($scope_en); + $body .= ";\n$subs" if length($subs); + } + } + elsif ($firstop) { + $body = $self->deparse($root->first, 0); + } + else { + $body = ';'; # stub sub + } + + my $l = ''; + if ($self->{'linenums'}) { + # a glob's gp_line is set from the line containing a + # sub's closing '}' if the CV is the first use of the GV. + # So make sure the linenum is set correctly for '}' + my $gv = $cv->GV; + my $line = $gv->LINE; + my $file = $gv->FILE; + $l = "\f#line $line \"$file\"\n"; + } + $body = "{\n\t$body\n$l\b}"; + } + else { + my $sv = $cv->const_sv; + if ($$sv) { + # uh-oh. inlinable sub... format it differently + $body = "{ " . $self->const($sv, 0) . " }\n"; + } else { # XSUB? (or just a declaration) + $body = ';' + } + } + $proto = defined $proto ? "($proto) " : ""; + $sig = defined $sig ? "($sig) " : ""; + my $attrs = ''; + $attrs = ': ' . join('', map "$_ ", @attrs) if @attrs; + return "$proto$attrs$sig$body\n"; +} + +sub deparse_format { + my $self = shift; + my $form = shift; + my @text; + local($self->{'curcv'}) = $form; + local($self->{'curcvlex'}); + local($self->{'in_format'}) = 1; + local(@$self{qw'curstash warnings hints hinthash'}) + = @$self{qw'curstash warnings hints hinthash'}; + my $op = $form->ROOT; + local $B::overlay = {}; + $self->pessimise($op, $form->START); + my $kid; + return "\f." if $op->first->name eq 'stub' + || $op->first->name eq 'nextstate'; + $op = $op->first->first; # skip leavewrite, lineseq + while (not null $op) { + $op = $op->sibling; # skip nextstate + my @exprs; + $kid = $op->first->sibling; # skip pushmark + push @text, "\f".$self->const_sv($kid)->PV; + $kid = $kid->sibling; + for (; not null $kid; $kid = $kid->sibling) { + push @exprs, $self->deparse($kid, -1); + $exprs[-1] =~ s/;\z//; + } + push @text, "\f".join(", ", @exprs)."\n" if @exprs; + $op = $op->sibling; + } + return join("", @text) . "\f."; +} + +sub is_scope { + my $op = shift; + return $op->name eq "leave" || $op->name eq "scope" + || $op->name eq "lineseq" + || ($op->name eq "null" && class($op) eq "UNOP" + && (is_scope($op->first) || $op->first->name eq "enter")); +} + +sub is_state { + my $name = $_[0]->name; + return $name eq "nextstate" || $name eq "dbstate" || $name eq "setstate"; +} + +sub is_miniwhile { # check for one-line loop ('foo() while $y--') + my $op = shift; + return (!null($op) and null($op->sibling) + and $op->name eq "null" and class($op) eq "UNOP" + and (($op->first->name =~ /^(and|or)$/ + and $op->first->first->sibling->name eq "lineseq") + or ($op->first->name eq "lineseq" + and not null $op->first->first->sibling + and $op->first->first->sibling->name eq "unstack") + )); +} + +# Check if the op and its sibling are the initialization and the rest of a +# for (..;..;..) { ... } loop +sub is_for_loop { + my $op = shift; + # This OP might be almost anything, though it won't be a + # nextstate. (It's the initialization, so in the canonical case it + # will be an sassign.) The sibling is (old style) a lineseq whose + # first child is a nextstate and whose second is a leaveloop, or + # (new style) an unstack whose sibling is a leaveloop. + my $lseq = $op->sibling; + return 0 unless !is_state($op) and !null($lseq); + if ($lseq->name eq "lineseq") { + if ($lseq->first && !null($lseq->first) && is_state($lseq->first) + && (my $sib = $lseq->first->sibling)) { + return (!null($sib) && $sib->name eq "leaveloop"); + } + } elsif ($lseq->name eq "unstack" && ($lseq->flags & OPf_SPECIAL)) { + my $sib = $lseq->sibling; + return $sib && !null($sib) && $sib->name eq "leaveloop"; + } + return 0; +} + +sub is_scalar { + my $op = shift; + return ($op->name eq "rv2sv" or + $op->name eq "padsv" or + $op->name eq "gv" or # only in array/hash constructs + $op->flags & OPf_KIDS && !null($op->first) + && $op->first->name eq "gvsv"); +} + +sub maybe_parens { + my $self = shift; + my($text, $cx, $prec) = @_; + if ($prec < $cx # unary ops nest just fine + or $prec == $cx and $cx != 4 and $cx != 16 and $cx != 21 + or $self->{'parens'}) + { + $text = "($text)"; + # In a unop, let parent reuse our parens; see maybe_parens_unop + $text = "\cS" . $text if $cx == 16; + return $text; + } else { + return $text; + } +} + +# same as above, but get around the 'if it looks like a function' rule +sub maybe_parens_unop { + my $self = shift; + my($name, $kid, $cx) = @_; + if ($cx > 16 or $self->{'parens'}) { + $kid = $self->deparse($kid, 1); + if ($name eq "umask" && $kid =~ /^\d+$/) { + $kid = sprintf("%#o", $kid); + } + return $self->keyword($name) . "($kid)"; + } else { + $kid = $self->deparse($kid, 16); + if ($name eq "umask" && $kid =~ /^\d+$/) { + $kid = sprintf("%#o", $kid); + } + $name = $self->keyword($name); + if (substr($kid, 0, 1) eq "\cS") { + # use kid's parens + return $name . substr($kid, 1); + } elsif (substr($kid, 0, 1) eq "(") { + # avoid looks-like-a-function trap with extra parens + # ('+' can lead to ambiguities) + return "$name(" . $kid . ")"; + } else { + return "$name $kid"; + } + } +} + +sub maybe_parens_func { + my $self = shift; + my($func, $text, $cx, $prec) = @_; + if ($prec <= $cx or substr($text, 0, 1) eq "(" or $self->{'parens'}) { + return "$func($text)"; + } else { + return $func . (length($text) ? " $text" : ""); + } +} + +sub find_our_type { + my ($self, $name) = @_; + $self->populate_curcvlex() if !defined $self->{'curcvlex'}; + my $seq = $self->{'curcop'} ? $self->{'curcop'}->cop_seq : 0; + for my $a (@{$self->{'curcvlex'}{"o$name"}}) { + my ($st, undef, $padname) = @$a; + if ($st >= $seq && $padname->FLAGS & PADNAMEf_TYPED) { + return $padname->SvSTASH->NAME; + } + } + return ''; +} + +sub maybe_local { + my $self = shift; + my($op, $cx, $text) = @_; + my $name = $op->name; + my $our_intro = ($name =~ /^(?:(?:gv|rv2)[ash]v|split|refassign + |lv(?:av)?ref)$/x) + ? OPpOUR_INTRO + : 0; + my $lval_intro = $name eq 'split' ? 0 : OPpLVAL_INTRO; + # The @a in \(@a) isn't in ref context, but only when the + # parens are there. + my $need_parens = $self->{'in_refgen'} && $name =~ /[ah]v\z/ + && ($op->flags & (OPf_PARENS|OPf_REF)) == OPf_PARENS; + if ((my $priv = $op->private) & ($lval_intro|$our_intro)) { + my @our_local; + push @our_local, "local" if $priv & $lval_intro; + push @our_local, "our" if $priv & $our_intro; + my $our_local = join " ", map $self->keyword($_), @our_local; + if( $our_local[-1] eq 'our' ) { + if ( $text !~ /^\W(\w+::)*\w+\z/ + and !utf8::decode($text) || $text !~ /^\W(\w+::)*\w+\z/ + ) { + die "Unexpected our($text)\n"; + } + $text =~ s/(\w+::)+//; + + if (my $type = $self->find_our_type($text)) { + $our_local .= ' ' . $type; + } + } + return $need_parens ? "($text)" : $text + if $self->{'avoid_local'}{$$op}; + if ($need_parens) { + return "$our_local($text)"; + } elsif (want_scalar($op) || $our_local eq 'our') { + return "$our_local $text"; + } else { + return $self->maybe_parens_func("$our_local", $text, $cx, 16); + } + } else { + return $need_parens ? "($text)" : $text; + } +} + +sub maybe_targmy { + my $self = shift; + my($op, $cx, $func, @args) = @_; + if ($op->private & OPpTARGET_MY) { + my $var = $self->padname($op->targ); + my $val = $func->($self, $op, 7, @args); + return $self->maybe_parens("$var = $val", $cx, 7); + } else { + return $func->($self, $op, $cx, @args); + } +} + +sub padname_sv { + my $self = shift; + my $targ = shift; + return $self->{'curcv'}->PADLIST->ARRAYelt(0)->ARRAYelt($targ); +} + +sub maybe_my { + my $self = shift; + my($op, $cx, $text, $padname, $forbid_parens) = @_; + # The @a in \(@a) isn't in ref context, but only when the + # parens are there. + my $need_parens = !$forbid_parens && $self->{'in_refgen'} + && $op->name =~ /[ah]v\z/ + && ($op->flags & (OPf_PARENS|OPf_REF)) == OPf_PARENS; + # The @a in \my @a must not have parens. + if (!$need_parens && $self->{'in_refgen'}) { + $forbid_parens = 1; + } + if ($op->private & OPpLVAL_INTRO and not $self->{'avoid_local'}{$$op}) { + # Check $padname->FLAGS for statehood, rather than $op->private, + # because enteriter ops do not carry the flag. + my $my = + $self->keyword($padname->FLAGS & SVpad_STATE ? "state" : "my"); + if ($padname->FLAGS & PADNAMEf_TYPED) { + $my .= ' ' . $padname->SvSTASH->NAME; + } + if ($need_parens) { + return "$my($text)"; + } elsif ($forbid_parens || want_scalar($op)) { + return "$my $text"; + } else { + return $self->maybe_parens_func($my, $text, $cx, 16); + } + } else { + return $need_parens ? "($text)" : $text; + } +} + +# The following OPs don't have functions: + +# pp_padany -- does not exist after parsing + +sub AUTOLOAD { + if ($AUTOLOAD =~ s/^.*::pp_//) { + warn "unexpected OP_". + ($_[1]->type == OP_CUSTOM ? "CUSTOM ($AUTOLOAD)" : uc $AUTOLOAD); + return "XXX"; + } else { + die "Undefined subroutine $AUTOLOAD called"; + } +} + +sub DESTROY {} # Do not AUTOLOAD + +# $root should be the op which represents the root of whatever +# we're sequencing here. If it's undefined, then we don't append +# any subroutine declarations to the deparsed ops, otherwise we +# append appropriate declarations. +sub lineseq { + my($self, $root, $cx, @ops) = @_; + my($expr, @exprs); + + my $out_cop = $self->{'curcop'}; + my $out_seq = defined($out_cop) ? $out_cop->cop_seq : undef; + my $limit_seq; + if (defined $root) { + $limit_seq = $out_seq; + my $nseq; + $nseq = $self->find_scope_st($root->sibling) if ${$root->sibling}; + $limit_seq = $nseq if !defined($limit_seq) + or defined($nseq) && $nseq < $limit_seq; + } + $limit_seq = $self->{'limit_seq'} + if defined($self->{'limit_seq'}) + && (!defined($limit_seq) || $self->{'limit_seq'} < $limit_seq); + local $self->{'limit_seq'} = $limit_seq; + + $self->walk_lineseq($root, \@ops, + sub { push @exprs, $_[0]} ); + + my $sep = $cx ? '; ' : ";\n"; + my $body = join($sep, grep {length} @exprs); + my $subs = ""; + if (defined $root && defined $limit_seq && !$self->{'in_format'}) { + $subs = join "\n", $self->seq_subs($limit_seq); + } + return join($sep, grep {length} $body, $subs); +} + +sub scopeop { + my($real_block, $self, $op, $cx) = @_; + my $kid; + my @kids; + + local(@$self{qw'curstash warnings hints hinthash'}) + = @$self{qw'curstash warnings hints hinthash'} if $real_block; + if ($real_block) { + $kid = $op->first->sibling; # skip enter + if (is_miniwhile($kid)) { + my $top = $kid->first; + my $name = $top->name; + if ($name eq "and") { + $name = $self->keyword("while"); + } elsif ($name eq "or") { + $name = $self->keyword("until"); + } else { # no conditional -> while 1 or until 0 + return $self->deparse($top->first, 1) . " " + . $self->keyword("while") . " 1"; + } + my $cond = $top->first; + my $body = $cond->sibling->first; # skip lineseq + $cond = $self->deparse($cond, 1); + $body = $self->deparse($body, 1); + return "$body $name $cond"; + } + elsif($kid->type == OP_PUSHDEFER && + $kid->private & OPpDEFER_FINALLY && + $kid->sibling->type == OP_LEAVETRYCATCH && + null($kid->sibling->sibling)) { + return $self->pp_leavetrycatch_with_finally($kid->sibling, $kid, $cx); + } + } else { + $kid = $op->first; + } + for (; !null($kid); $kid = $kid->sibling) { + push @kids, $kid; + } + if ($cx > 0) { # inside an expression, (a do {} while for lineseq) + my $body = $self->lineseq($op, 0, @kids); + return is_lexical_subs(@kids) + ? $body + : ($self->lex_in_scope("&do") ? "CORE::do" : "do") + . " {\n\t$body\n\b}"; + } else { + my $lineseq = $self->lineseq($op, $cx, @kids); + return (length ($lineseq) ? "$lineseq;" : ""); + } +} + +sub pp_scope { scopeop(0, @_); } +sub pp_lineseq { scopeop(0, @_); } +sub pp_leave { scopeop(1, @_); } + +# This is a special case of scopeop and lineseq, for the case of the +# main_root. The difference is that we print the output statements as +# soon as we get them, for the sake of impatient users. +sub deparse_root { + my $self = shift; + my($op) = @_; + local(@$self{qw'curstash warnings hints hinthash'}) + = @$self{qw'curstash warnings hints hinthash'}; + my @kids; + return if null $op->first; # Can happen, e.g., for Bytecode without -k + for (my $kid = $op->first->sibling; !null($kid); $kid = $kid->sibling) { + push @kids, $kid; + } + $self->walk_lineseq($op, \@kids, + sub { return unless length $_[0]; + print $self->indent($_[0].';'); + print "\n" + unless $_[1] == $#kids; + }); +} + +sub walk_lineseq { + my ($self, $op, $kids, $callback) = @_; + my @kids = @$kids; + for (my $i = 0; $i < @kids; $i++) { + my $expr = ""; + if (is_state $kids[$i]) { + $expr = $self->deparse($kids[$i++], 0); + if ($i > $#kids) { + $callback->($expr, $i); + last; + } + } + if (is_for_loop($kids[$i])) { + $callback->($expr . $self->for_loop($kids[$i], 0), + $i += $kids[$i]->sibling->name eq "unstack" ? 2 : 1); + next; + } + my $expr2 = $self->deparse($kids[$i], (@kids != 1)/2); + $expr2 =~ s/^sub :(?!:)/+sub :/; # statement label otherwise + $expr .= $expr2; + $callback->($expr, $i); + } +} + +# The BEGIN {} is used here because otherwise this code isn't executed +# when you run B::Deparse on itself. +my %globalnames; +BEGIN { map($globalnames{$_}++, "SIG", "STDIN", "STDOUT", "STDERR", "INC", + "ENV", "ARGV", "ARGVOUT", "_"); } + +sub gv_name { + my $self = shift; + my $gv = shift; + my $raw = shift; +#Carp::confess() unless ref($gv) eq "B::GV"; + my $cv = $gv->FLAGS & SVf_ROK ? $gv->RV : 0; + my $stash = ($cv || $gv)->STASH->NAME; + my $name = $raw + ? $cv ? $cv->NAME_HEK || $cv->GV->NAME : $gv->NAME + : $cv + ? B::safename($cv->NAME_HEK || $cv->GV->NAME) + : $gv->SAFENAME; + if ($stash eq 'main' && $name =~ /^::/) { + $stash = '::'; + } + elsif (($stash eq 'main' + && ($globalnames{$name} || $name =~ /^[^A-Za-z_:]/)) + or ($stash eq $self->{'curstash'} && !$globalnames{$name} + && ($stash eq 'main' || $name !~ /::/)) + ) + { + $stash = ""; + } else { + $stash = $stash . "::"; + } + if (!$raw and $name =~ /^(\^..|{)/) { + $name = "{$name}"; # ${^WARNING_BITS}, etc and ${ + } + return $stash . $name; +} + +# Return the name to use for a stash variable. +# If a lexical with the same name is in scope, or +# if strictures are enabled, it may need to be +# fully-qualified. +sub stash_variable { + my ($self, $prefix, $name, $cx) = @_; + + return $prefix.$self->maybe_qualify($prefix, $name) if $name =~ /::/; + + unless ($prefix eq '$' || $prefix eq '@' || $prefix eq '&' || #' + $prefix eq '%' || $prefix eq '$#') { + return "$prefix$name"; + } + + if ($name =~ /^[^[:alpha:]_+-]$/) { + if (defined $cx && $cx == 26) { + if ($prefix eq '@') { + return "$prefix\{$name}"; + } + elsif ($name eq '#') { return '${#}' } # "${#}a" vs "$#a" + } + if ($prefix eq '$#') { + return "\$#{$name}"; + } + } + + return $prefix . $self->maybe_qualify($prefix, $name); +} + +my %unctrl = # portable to EBCDIC + ( + "\c@" => '@', # unused + "\cA" => 'A', + "\cB" => 'B', + "\cC" => 'C', + "\cD" => 'D', + "\cE" => 'E', + "\cF" => 'F', + "\cG" => 'G', + "\cH" => 'H', + "\cI" => 'I', + "\cJ" => 'J', + "\cK" => 'K', + "\cL" => 'L', + "\cM" => 'M', + "\cN" => 'N', + "\cO" => 'O', + "\cP" => 'P', + "\cQ" => 'Q', + "\cR" => 'R', + "\cS" => 'S', + "\cT" => 'T', + "\cU" => 'U', + "\cV" => 'V', + "\cW" => 'W', + "\cX" => 'X', + "\cY" => 'Y', + "\cZ" => 'Z', + "\c[" => '[', # unused + "\c\\" => '\\', # unused + "\c]" => ']', # unused + "\c_" => '_', # unused + ); + +# Return just the name, without the prefix. It may be returned as a quoted +# string. The second return value is a boolean indicating that. +sub stash_variable_name { + my($self, $prefix, $gv) = @_; + my $name = $self->gv_name($gv, 1); + $name = $self->maybe_qualify($prefix,$name); + if ($name =~ /^(?:\S|(?!\d)[\ca-\cz]?(?:\w|::)*|\d+)\z/) { + $name =~ s/^([\ca-\cz])/'^' . $unctrl{$1}/e; + $name =~ /^(\^..|{)/ and $name = "{$name}"; + return $name, 0; # not quoted + } + else { + single_delim("q", "'", $name, $self), 1; + } +} + +sub maybe_qualify { + my ($self,$prefix,$name) = @_; + my $v = ($prefix eq '$#' ? '@' : $prefix) . $name; + if ($prefix eq "") { + $name .= "::" if $name =~ /(?:\ACORE::[^:]*|::)\z/; + return $name; + } + return $name if $name =~ /::/; + return $self->{'curstash'}.'::'. $name + if + $name =~ /^(?!\d)\w/ # alphabetic + && $v !~ /^\$[ab]\z/ # not $a or $b + && $v =~ /\A[\$\@\%\&]/ # scalar, array, hash, or sub + && !$globalnames{$name} # not a global name + && $self->{hints} & $strict_bits{vars} # strict vars + && !$self->lex_in_scope($v,1) # no "our" + or $self->lex_in_scope($v); # conflicts with "my" variable + return $name; +} + +sub lex_in_scope { + my ($self, $name, $our) = @_; + substr $name, 0, 0, = $our ? 'o' : 'm'; # our/my + $self->populate_curcvlex() if !defined $self->{'curcvlex'}; + + return 0 if !defined($self->{'curcop'}); + my $seq = $self->{'curcop'}->cop_seq; + return 0 if !exists $self->{'curcvlex'}{$name}; + for my $a (@{$self->{'curcvlex'}{$name}}) { + my ($st, $en) = @$a; + return 1 if $seq > $st && $seq <= $en; + } + return 0; +} + +sub populate_curcvlex { + my $self = shift; + for (my $cv = $self->{'curcv'}; class($cv) eq "CV"; $cv = $cv->OUTSIDE) { + my $padlist = $cv->PADLIST; + # an undef CV still in lexical chain + next if class($padlist) eq "SPECIAL"; + my @padlist = $padlist->ARRAY; + my @ns = $padlist[0]->ARRAY; + + for (my $i=0; $i<@ns; ++$i) { + next if class($ns[$i]) eq "SPECIAL"; + if (class($ns[$i]) eq "PV") { + # Probably that pesky lexical @_ + next; + } + my $name = $ns[$i]->PVX; + next unless defined $name; + my ($seq_st, $seq_en) = + ($ns[$i]->FLAGS & SVf_FAKE) + ? (0, 999999) + : ($ns[$i]->COP_SEQ_RANGE_LOW, $ns[$i]->COP_SEQ_RANGE_HIGH); + + push @{$self->{'curcvlex'}{ + ($ns[$i]->FLAGS & PADNAMEf_OUR ? 'o' : 'm') . $name + }}, [$seq_st, $seq_en, $ns[$i]]; + } + } +} + +sub find_scope_st { ((find_scope(@_))[0]); } +sub find_scope_en { ((find_scope(@_))[1]); } + +# Recurses down the tree, looking for pad variable introductions and COPs +sub find_scope { + my ($self, $op, $scope_st, $scope_en) = @_; + carp("Undefined op in find_scope") if !defined $op; + return ($scope_st, $scope_en) unless $op->flags & OPf_KIDS; + + my @queue = ($op); + while(my $op = shift @queue ) { + for (my $o=$op->first; $$o; $o=$o->sibling) { + if ($o->name =~ /^pad.v$/ && $o->private & OPpLVAL_INTRO) { + my $s = int($self->padname_sv($o->targ)->COP_SEQ_RANGE_LOW); + my $e = $self->padname_sv($o->targ)->COP_SEQ_RANGE_HIGH; + $scope_st = $s if !defined($scope_st) || $s < $scope_st; + $scope_en = $e if !defined($scope_en) || $e > $scope_en; + return ($scope_st, $scope_en); + } + elsif (is_state($o)) { + my $c = $o->cop_seq; + $scope_st = $c if !defined($scope_st) || $c < $scope_st; + $scope_en = $c if !defined($scope_en) || $c > $scope_en; + return ($scope_st, $scope_en); + } + elsif ($o->flags & OPf_KIDS) { + unshift (@queue, $o); + } + } + } + + return ($scope_st, $scope_en); +} + +# Returns a list of subs which should be inserted before the COP +sub cop_subs { + my ($self, $op, $out_seq) = @_; + my $seq = $op->cop_seq; + $seq = $out_seq if defined($out_seq) && $out_seq < $seq; + return $self->seq_subs($seq); +} + +sub seq_subs { + my ($self, $seq) = @_; + my @text; +#push @text, "# ($seq)\n"; + + return "" if !defined $seq; + my @pending; + while (scalar(@{$self->{'subs_todo'}}) + and $seq > $self->{'subs_todo'}[0][0]) { + my $cv = $self->{'subs_todo'}[0][1]; + # Skip the OUTSIDE check for lexical subs. We may be deparsing a + # cloned anon sub with lexical subs declared in it, in which case + # the OUTSIDE pointer points to the anon protosub. + my $lexical = ref $self->{'subs_todo'}[0][3]; + my $outside = !$lexical && $cv && $cv->OUTSIDE; + if (!$lexical and $cv + and ${$cv->OUTSIDE || \0} != ${$self->{'curcv'}}) + { + push @pending, shift @{$self->{'subs_todo'}}; + next; + } + push @text, $self->next_todo; + } + unshift @{$self->{'subs_todo'}}, @pending; + return @text; +} + +sub _features_from_bundle { + my ($hints, $hh) = @_; + foreach (@{$feature::feature_bundle{@feature::hint_bundles[$hints >> $feature::hint_shift]}}) { + $hh->{$feature::feature{$_}} = 1; + } + return $hh; +} + +# generate any pragmas, 'package foo' etc needed to synchronise +# with the given cop + +sub pragmata { + my $self = shift; + my($op) = @_; + + my @text; + + my $stash = $op->stashpv; + if ($stash ne $self->{'curstash'}) { + push @text, $self->keyword("package") . " $stash;\n"; + $self->{'curstash'} = $stash; + } + + my $warnings = $op->warnings; + my $warning_bits; + if ($warnings->isa("B::SPECIAL") && $$warnings == 4) { + $warning_bits = $warnings::Bits{"all"}; + } + elsif ($warnings->isa("B::SPECIAL") && $$warnings == 5) { + $warning_bits = $warnings::NONE; + } + elsif ($warnings->isa("B::SPECIAL")) { + $warning_bits = undef; + } + else { + $warning_bits = $warnings->PV; + } + + my ($w1, $w2); + # The number of valid bit positions may have grown (by a byte or + # more) since the last warnings state, by custom warnings + # categories being registered in the meantime. Normalise the + # bitmasks first so they may be fairly compared. + $w1 = defined($self->{warnings}) + ? warnings::_expand_bits($self->{warnings}) + : undef; + $w2 = defined($warning_bits) + ? warnings::_expand_bits($warning_bits) + : undef; + + if (defined($w2) and !defined($w1) || $w1 ne $w2) { + push @text, $self->declare_warnings($w1, $w2); + $self->{'warnings'} = $w2; + } + + my $hints = $op->hints; + my $old_hints = $self->{'hints'}; + if ($self->{'hints'} != $hints) { + push @text, $self->declare_hints($self->{'hints'}, $hints); + $self->{'hints'} = $hints; + } + + my $newhh; + $newhh = $op->hints_hash->HASH; + + { + # feature bundle hints + my $from = $old_hints & $feature::hint_mask; + my $to = $ hints & $feature::hint_mask; + if ($from != $to) { + if ($to == $feature::hint_mask) { + if ($self->{'hinthash'}) { + delete $self->{'hinthash'}{$_} + for grep /^feature_/, keys %{$self->{'hinthash'}}; + } + else { $self->{'hinthash'} = {} } + $self->{'hinthash'} + = _features_from_bundle($from, $self->{'hinthash'}); + } + else { + my $bundle = + $feature::hint_bundles[$to >> $feature::hint_shift]; + $bundle =~ s/(\d[13579])\z/$1+1/e; # 5.11 => 5.12 + push @text, + $self->keyword("no") . " feature ':all';\n", + $self->keyword("use") . " feature ':$bundle';\n"; + } + } + } + + { + push @text, $self->declare_hinthash( + $self->{'hinthash'}, $newhh, + $self->{indent_size}, $self->{hints}, + ); + $self->{'hinthash'} = $newhh; + } + + return join("", @text); +} + + +# Notice how subs and formats are inserted between statements here; +# also $[ assignments and pragmas. +sub pp_nextstate { + my $self = shift; + my($op, $cx) = @_; + $self->{'curcop'} = $op; + + my @text; + + my @subs = $self->cop_subs($op); + if (@subs) { + # Special marker to swallow up the semicolon + push @subs, "\cK"; + } + push @text, @subs; + + push @text, $self->pragmata($op); + + + # This should go after of any branches that add statements, to + # increase the chances that it refers to the same line it did in + # the original program. + if ($self->{'linenums'} && $cx != .5) { # $cx == .5 means in a format + push @text, "\f#line " . $op->line . + ' "' . $op->file, qq'"\n'; + } + + push @text, $op->label . ": " if $op->label; + + return join("", @text); +} + +sub declare_warnings { + my ($self, $from, $to) = @_; + $from //= ''; + my $all = warnings::bits("all"); + unless (($from & ~$all) =~ /[^\0]/) { + # no FATAL bits need turning off + if ( $to eq $all) { + return $self->keyword("use") . " warnings;\n"; + } + elsif ($to eq ("\0"x length($to))) { + return $self->keyword("no") . " warnings;\n"; + } + } + + return "BEGIN {\${^WARNING_BITS} = \"" + . join("", map { sprintf("\\x%02x", ord $_) } split "", $to) + . "\"}\n\cK"; +} + +sub declare_hints { + my ($self, $from, $to) = @_; + my $use = $to & ~$from; + my $no = $from & ~$to; + my $decls = ""; + for my $pragma (hint_pragmas($use)) { + $decls .= $self->keyword("use") . " $pragma;\n"; + } + for my $pragma (hint_pragmas($no)) { + $decls .= $self->keyword("no") . " $pragma;\n"; + } + return $decls; +} + +# Internal implementation hints that the core sets automatically, so don't need +# (or want) to be passed back to the user +my %ignored_hints = ( + 'open<' => 1, + 'open>' => 1, + ':' => 1, + 'strict/refs' => 1, + 'strict/subs' => 1, + 'strict/vars' => 1, + 'feature/bits' => 1, +); + +my %rev_feature; + +sub declare_hinthash { + my ($self, $from, $to, $indent, $hints) = @_; + my $doing_features = + ($hints & $feature::hint_mask) == $feature::hint_mask; + my @decls; + my @features; + my @unfeatures; # bugs? + for my $key (sort keys %$to) { + next if $ignored_hints{$key}; + my $is_feature = $key =~ /^feature_/; + next if $is_feature and not $doing_features; + if (!exists $from->{$key} or $from->{$key} ne $to->{$key}) { + push(@features, $key), next if $is_feature; + push @decls, + qq(\$^H{) . single_delim("q", "'", $key, $self) . qq(} = ) + . ( + defined $to->{$key} + ? single_delim("q", "'", $to->{$key}, $self) + : 'undef' + ) + . qq(;); + } + } + for my $key (sort keys %$from) { + next if $ignored_hints{$key}; + my $is_feature = $key =~ /^feature_/; + next if $is_feature and not $doing_features; + if (!exists $to->{$key}) { + push(@unfeatures, $key), next if $is_feature; + push @decls, qq(delete \$^H{'$key'};); + } + } + my @ret; + if (@features || @unfeatures) { + if (!%rev_feature) { %rev_feature = reverse %feature::feature } + } + if (@features) { + push @ret, $self->keyword("use") . " feature " + . join(", ", map "'$rev_feature{$_}'", @features) . ";\n"; + } + if (@unfeatures) { + push @ret, $self->keyword("no") . " feature " + . join(", ", map "'$rev_feature{$_}'", @unfeatures) + . ";\n"; + } + @decls and + push @ret, + join("\n" . (" " x $indent), "BEGIN {", @decls) . "\n}\n\cK"; + return @ret; +} + +sub hint_pragmas { + my ($bits) = @_; + my (@pragmas, @strict); + push @pragmas, "integer" if $bits & 0x1; + for (sort keys %strict_bits) { + push @strict, "'$_'" if $bits & $strict_bits{$_}; + } + if (@strict == keys %strict_bits) { + push @pragmas, "strict"; + } + elsif (@strict) { + push @pragmas, "strict " . join ', ', @strict; + } + push @pragmas, "bytes" if $bits & 0x8; + return @pragmas; +} + +sub pp_dbstate { pp_nextstate(@_) } +sub pp_setstate { pp_nextstate(@_) } + +sub pp_unstack { return "" } # see also leaveloop + +my %feature_keywords = ( + # keyword => 'feature', + state => 'state', + say => 'say', + given => 'switch', + when => 'switch', + default => 'switch', + break => 'switch', + evalbytes=>'evalbytes', + __SUB__ => '__SUB__', + fc => 'fc', + try => 'try', + catch => 'try', + finally => 'try', + defer => 'defer', + signatures => 'signatures', + any => 'any', + all => 'all', +); + +# keywords that are strong and also have a prototype +# +my %strong_proto_keywords = map { $_ => 1 } qw( + pos + prototype + scalar + study + undef +); + +sub feature_enabled { + my($self,$name) = @_; + my $hh; + my $hints = $self->{hints} & $feature::hint_mask; + if ($hints && $hints != $feature::hint_mask) { + $hh = _features_from_bundle($hints); + } + elsif ($hints) { $hh = $self->{'hinthash'} } + return $hh && $hh->{"feature_$feature_keywords{$name}"} +} + +sub keyword { + my $self = shift; + my $name = shift; + return $name if $name =~ /^CORE::/; # just in case + if (exists $feature_keywords{$name}) { + return "CORE::$name" if not $self->feature_enabled($name); + } + # This sub may be called for a program that has no nextstate ops. In + # that case we may have a lexical sub named no/use/sub in scope but + # $self->lex_in_scope will return false because it depends on the + # current nextstate op. So we need this alternate method if there is + # no current cop. + if (!$self->{'curcop'}) { + $self->populate_curcvlex() if !defined $self->{'curcvlex'}; + return "CORE::$name" if exists $self->{'curcvlex'}{"m&$name"} + || exists $self->{'curcvlex'}{"o&$name"}; + } elsif ($self->lex_in_scope("&$name") + || $self->lex_in_scope("&$name", 1)) { + return "CORE::$name"; + } + if ($strong_proto_keywords{$name} + || ($name !~ /^(?:chom?p|do|exec|glob|s(?:elect|ystem))\z/ + && !defined eval{prototype "CORE::$name"}) + ) { return $name } + if ( + exists $self->{subs_declared}{$name} + or + exists &{"$self->{curstash}::$name"} + ) { + return "CORE::$name" + } + return $name; +} + +sub baseop { + my $self = shift; + my($op, $cx, $name) = @_; + return $self->keyword($name); +} + +sub pp_stub { "()" } +sub pp_wantarray { baseop(@_, "wantarray") } +sub pp_fork { baseop(@_, "fork") } +sub pp_wait { maybe_targmy(@_, \&baseop, "wait") } +sub pp_getppid { maybe_targmy(@_, \&baseop, "getppid") } +sub pp_time { maybe_targmy(@_, \&baseop, "time") } +sub pp_tms { baseop(@_, "times") } +sub pp_ghostent { baseop(@_, "gethostent") } +sub pp_gnetent { baseop(@_, "getnetent") } +sub pp_gprotoent { baseop(@_, "getprotoent") } +sub pp_gservent { baseop(@_, "getservent") } +sub pp_ehostent { baseop(@_, "endhostent") } +sub pp_enetent { baseop(@_, "endnetent") } +sub pp_eprotoent { baseop(@_, "endprotoent") } +sub pp_eservent { baseop(@_, "endservent") } +sub pp_gpwent { baseop(@_, "getpwent") } +sub pp_spwent { baseop(@_, "setpwent") } +sub pp_epwent { baseop(@_, "endpwent") } +sub pp_ggrent { baseop(@_, "getgrent") } +sub pp_sgrent { baseop(@_, "setgrent") } +sub pp_egrent { baseop(@_, "endgrent") } +sub pp_getlogin { baseop(@_, "getlogin") } + +sub POSTFIX () { 1 } + +# I couldn't think of a good short name, but this is the category of +# symbolic unary operators with interesting precedence + +sub pfixop { + my $self = shift; + my($op, $cx, $name, $prec, $flags) = (@_, 0); + my $kid = $op->first; + $kid = $self->deparse($kid, $prec); + return $self->maybe_parens(($flags & POSTFIX) + ? "$kid$name" + # avoid confusion with filetests + : $name eq '-' + && $kid =~ /^[a-zA-Z](?!\w)/ + ? "$name($kid)" + : "$name$kid", + $cx, $prec); +} + +sub pp_preinc { pfixop(@_, "++", 23) } +sub pp_predec { pfixop(@_, "--", 23) } +sub pp_postinc { maybe_targmy(@_, \&pfixop, "++", 23, POSTFIX) } +sub pp_postdec { maybe_targmy(@_, \&pfixop, "--", 23, POSTFIX) } +sub pp_i_preinc { pfixop(@_, "++", 23) } +sub pp_i_predec { pfixop(@_, "--", 23) } +sub pp_i_postinc { maybe_targmy(@_, \&pfixop, "++", 23, POSTFIX) } +sub pp_i_postdec { maybe_targmy(@_, \&pfixop, "--", 23, POSTFIX) } +sub pp_complement { maybe_targmy(@_, \&pfixop, "~", 21) } +*pp_ncomplement = *pp_complement; +sub pp_scomplement { maybe_targmy(@_, \&pfixop, "~.", 21) } + +sub pp_negate { maybe_targmy(@_, \&real_negate) } +sub real_negate { + my $self = shift; + my($op, $cx) = @_; + if ($op->first->name =~ /^(i_)?negate$/) { + # avoid --$x + $self->pfixop($op, $cx, "-", 21.5); + } else { + $self->pfixop($op, $cx, "-", 21); + } +} +sub pp_i_negate { pp_negate(@_) } + +sub pp_not { + my $self = shift; + my($op, $cx) = @_; + if ($cx <= 4) { + $self->listop($op, $cx, "not", $op->first); + } else { + $self->pfixop($op, $cx, "!", 21); + } +} + +sub unop { + my $self = shift; + my($op, $cx, $name, $nollafr) = @_; + my $kid; + if ($op->flags & OPf_KIDS) { + $kid = $op->first; + if (not $name) { + # this deals with 'boolkeys' right now + return $self->deparse($kid,$cx); + } + my $builtinname = $name; + $builtinname =~ /^CORE::/ or $builtinname = "CORE::$name"; + if (defined prototype($builtinname) + && $builtinname ne 'CORE::readline' + && prototype($builtinname) =~ /^;?\*/ + && $kid->name eq "rv2gv") { + $kid = $kid->first; + } + + if ($nollafr) { + if (($kid = $self->deparse($kid, 16)) !~ s/^\cS//) { + # require foo() is a syntax error. + $kid =~ /^(?!\d)\w/ and $kid = "($kid)"; + } + return $self->maybe_parens( + $self->keyword($name) . " $kid", $cx, 16 + ); + } + return $self->maybe_parens_unop($name, $kid, $cx); + } else { + return $self->maybe_parens( + $self->keyword($name) . ($op->flags & OPf_SPECIAL ? "()" : ""), + $cx, 16, + ); + } +} + +sub pp_chop { maybe_targmy(@_, \&unop, "chop") } +sub pp_chomp { maybe_targmy(@_, \&unop, "chomp") } +sub pp_schop { maybe_targmy(@_, \&unop, "chop") } +sub pp_schomp { maybe_targmy(@_, \&unop, "chomp") } +sub pp_defined { unop(@_, "defined") } +sub pp_undef { + if ($_[1]->private & OPpTARGET_MY) { + my $targ = $_[1]->targ; + my $var = $_[0]->maybe_my($_[1], $_[2], $_[0]->padname($targ), + $_[0]->padname_sv($targ), + 1); + my $func = unop(@_, "undef"); + if ($func =~ /\s/) { + return unop(@_, "undef").$var; + } else { + return "$var = undef"; + } + } + unop(@_, "undef") +} +sub pp_study { unop(@_, "study") } +sub pp_ref { unop(@_, "ref") } +sub pp_pos { maybe_local(@_, unop(@_, "pos")) } + +sub pp_sin { maybe_targmy(@_, \&unop, "sin") } +sub pp_cos { maybe_targmy(@_, \&unop, "cos") } +sub pp_rand { maybe_targmy(@_, \&unop, "rand") } +sub pp_srand { unop(@_, "srand") } +sub pp_exp { maybe_targmy(@_, \&unop, "exp") } +sub pp_log { maybe_targmy(@_, \&unop, "log") } +sub pp_sqrt { maybe_targmy(@_, \&unop, "sqrt") } +sub pp_int { maybe_targmy(@_, \&unop, "int") } +sub pp_hex { maybe_targmy(@_, \&unop, "hex") } +sub pp_oct { maybe_targmy(@_, \&unop, "oct") } +sub pp_abs { maybe_targmy(@_, \&unop, "abs") } + +sub pp_length { maybe_targmy(@_, \&unop, "length") } +sub pp_ord { maybe_targmy(@_, \&unop, "ord") } +sub pp_chr { maybe_targmy(@_, \&unop, "chr") } + +sub pp_each { unop(@_, "each") } +sub pp_values { unop(@_, "values") } +sub pp_keys { unop(@_, "keys") } +{ no strict 'refs'; *{"pp_r$_"} = *{"pp_$_"} for qw< keys each values >; } +sub pp_boolkeys { + # no name because its an optimisation op that has no keyword + unop(@_,""); +} +sub pp_aeach { unop(@_, "each") } +sub pp_avalues { unop(@_, "values") } +sub pp_akeys { unop(@_, "keys") } +sub pp_pop { unop(@_, "pop") } +sub pp_shift { unop(@_, "shift") } + +sub pp_caller { unop(@_, "caller") } +sub pp_reset { unop(@_, "reset") } +sub pp_exit { unop(@_, "exit") } +sub pp_prototype { unop(@_, "prototype") } + +sub pp_close { unop(@_, "close") } +sub pp_fileno { unop(@_, "fileno") } +sub pp_umask { unop(@_, "umask") } +sub pp_untie { unop(@_, "untie") } +sub pp_tied { unop(@_, "tied") } +sub pp_dbmclose { unop(@_, "dbmclose") } +sub pp_getc { unop(@_, "getc") } +sub pp_eof { unop(@_, "eof") } +sub pp_tell { unop(@_, "tell") } +sub pp_getsockname { unop(@_, "getsockname") } +sub pp_getpeername { unop(@_, "getpeername") } + +sub pp_chdir { + my ($self, $op, $cx) = @_; + if (($op->flags & (OPf_SPECIAL|OPf_KIDS)) == (OPf_SPECIAL|OPf_KIDS)) { + my $kw = $self->keyword("chdir"); + my $kid = $self->const_sv($op->first)->PV; + my $code = $kw + . ($cx >= 16 || $self->{'parens'} ? "($kid)" : " $kid"); + maybe_targmy(@_, sub { $_[3] }, $code); + } else { + maybe_targmy(@_, \&unop, "chdir") + } +} + +sub pp_chroot { maybe_targmy(@_, \&unop, "chroot") } +sub pp_readlink { unop(@_, "readlink") } +sub pp_rmdir { maybe_targmy(@_, \&unop, "rmdir") } +sub pp_readdir { unop(@_, "readdir") } +sub pp_telldir { unop(@_, "telldir") } +sub pp_rewinddir { unop(@_, "rewinddir") } +sub pp_closedir { unop(@_, "closedir") } +sub pp_getpgrp { maybe_targmy(@_, \&unop, "getpgrp") } +sub pp_localtime { unop(@_, "localtime") } +sub pp_gmtime { unop(@_, "gmtime") } +sub pp_alarm { unop(@_, "alarm") } +sub pp_sleep { maybe_targmy(@_, \&unop, "sleep") } + +sub pp_dofile { + my $code = unop(@_, "do", 1); # llafr does not apply + if ($code =~ s/^((?:CORE::)?do) \{/$1({/) { $code .= ')' } + $code; +} +sub pp_entereval { + unop( + @_, + $_[1]->private & OPpEVAL_BYTES ? 'evalbytes' : "eval" + ) +} + +sub pp_ghbyname { unop(@_, "gethostbyname") } +sub pp_gnbyname { unop(@_, "getnetbyname") } +sub pp_gpbyname { unop(@_, "getprotobyname") } +sub pp_shostent { unop(@_, "sethostent") } +sub pp_snetent { unop(@_, "setnetent") } +sub pp_sprotoent { unop(@_, "setprotoent") } +sub pp_sservent { unop(@_, "setservent") } +sub pp_gpwnam { unop(@_, "getpwnam") } +sub pp_gpwuid { unop(@_, "getpwuid") } +sub pp_ggrnam { unop(@_, "getgrnam") } +sub pp_ggrgid { unop(@_, "getgrgid") } + +sub pp_lock { unop(@_, "lock") } + +sub pp_continue { unop(@_, "continue"); } +sub pp_break { unop(@_, "break"); } + +sub givwhen { + my $self = shift; + my($op, $cx, $givwhen) = @_; + + my $enterop = $op->first; + my ($head, $block); + if ($enterop->flags & OPf_SPECIAL) { + $head = $self->keyword("default"); + $block = $self->deparse($enterop->first, 0); + } + else { + my $cond = $enterop->first; + my $cond_str = $self->deparse($cond, 1); + $head = "$givwhen ($cond_str)"; + $block = $self->deparse($cond->sibling, 0); + } + + return "$head {\n". + "\t$block\n". + "\b}\cK"; +} + +sub pp_leavegiven { givwhen(@_, $_[0]->keyword("given")); } +sub pp_leavewhen { givwhen(@_, $_[0]->keyword("when")); } + +sub pp_exists { + my $self = shift; + my($op, $cx) = @_; + my $arg; + my $name = $self->keyword("exists"); + if ($op->private & OPpEXISTS_SUB) { + # Checking for the existence of a subroutine + return $self->maybe_parens_func($name, + $self->pp_rv2cv($op->first, 16), $cx, 16); + } + if ($op->flags & OPf_SPECIAL) { + # Array element, not hash element + return $self->maybe_parens_func($name, + $self->pp_aelem($op->first, 16), $cx, 16); + } + return $self->maybe_parens_func($name, $self->pp_helem($op->first, 16), + $cx, 16); +} + +sub pp_delete { + my $self = shift; + my($op, $cx) = @_; + my $arg; + my $name = $self->keyword("delete"); + if ($op->private & (OPpSLICE|OPpKVSLICE)) { + if ($op->flags & OPf_SPECIAL) { + # Deleting from an array, not a hash + return $self->maybe_parens_func($name, + $self->pp_aslice($op->first, 16), + $cx, 16); + } + return $self->maybe_parens_func($name, + $self->pp_hslice($op->first, 16), + $cx, 16); + } else { + if ($op->flags & OPf_SPECIAL) { + # Deleting from an array, not a hash + return $self->maybe_parens_func($name, + $self->pp_aelem($op->first, 16), + $cx, 16); + } + return $self->maybe_parens_func($name, + $self->pp_helem($op->first, 16), + $cx, 16); + } +} + +sub pp_require { + my $self = shift; + my($op, $cx) = @_; + my $opname = $op->flags & OPf_SPECIAL ? 'CORE::require' : 'require'; + my $kid = $op->first; + if ($kid->name eq 'const') { + my $priv = $kid->private; + my $sv = $self->const_sv($kid); + my $arg; + if ($priv & OPpCONST_BARE) { + $arg = $sv->PV; + $arg =~ s[/][::]g; + $arg =~ s/\.pm//g; + } elsif ($priv & OPpCONST_NOVER) { + $opname = $self->keyword('no'); + $arg = $self->const($sv, 16); + } elsif ((my $tmp = $self->const($sv, 16)) =~ /^v/) { + $arg = $tmp; + } + if ($arg) { + return $self->maybe_parens("$opname $arg", $cx, 16); + } + } + $self->unop( + $op, $cx, + $opname, + 1, # llafr does not apply + ); +} + +sub pp_scalar { + my $self = shift; + my($op, $cx) = @_; + my $kid = $op->first; + if (not null $kid->sibling) { + # XXX Was a here-doc + return $self->dquote($op); + } + $self->unop(@_, "scalar"); +} + + +sub padval { + my $self = shift; + my $targ = shift; + return $self->{'curcv'}->PADLIST->ARRAYelt(1)->ARRAYelt($targ); +} + +sub anon_hash_or_list { + my $self = shift; + my($op, $cx) = @_; + + my($pre, $post) = @{{"anonlist" => ["[","]"], + "anonhash" => ["{","}"]}->{$op->name}}; + my($expr, @exprs); + $op = $op->first->sibling; # skip pushmark + for (; !null($op); $op = $op->sibling) { + $expr = $self->deparse($op, 6); + push @exprs, $expr; + } + if ($pre eq "{" and $cx < 1) { + # Disambiguate that it's not a block + $pre = "+{"; + } + return $pre . join(", ", @exprs) . $post; +} + +sub pp_anonlist { + my $self = shift; + my ($op, $cx) = @_; + if ($op->flags & OPf_SPECIAL) { + return $self->anon_hash_or_list($op, $cx); + } + warn "Unexpected op pp_" . $op->name() . " without OPf_SPECIAL"; + return 'XXX'; +} + +*pp_anonhash = \&pp_anonlist; + +sub pp_emptyavhv { + my $self = shift; + my ($op, $cx, $forbid_parens) = @_; + my $val = ($op->private & OPpEMPTYAVHV_IS_HV) ? '{}' : '[]'; + if ($op->private & OPpTARGET_MY) { + my $targ = $op->targ; + my $var = $self->maybe_my($op, $cx, $self->padname($targ), + $self->padname_sv($targ), + $forbid_parens); + return $self->maybe_parens("$var = $val", $cx, 7); + } else { + return $val; + } +} + +sub pp_refgen { + my $self = shift; + my($op, $cx) = @_; + my $kid = $op->first; + if ($kid->name eq "null") { + my $anoncode = $kid = $kid->first; + + # Perl no longer generates this, but XS modules might: + if ($anoncode->name eq "anonconst") { + $anoncode = $anoncode->first->first->sibling; + } + + # Same as with `anonconst`: + if ($anoncode->name eq "anoncode" + or !null($anoncode = $kid->sibling) and + $anoncode->name eq "anoncode") { + return $self->e_anoncode({ code => $self->padval($anoncode->targ) }); + + # Perl still generates this: + } elsif ($kid->name eq "pushmark") { + my $sib_name = $kid->sibling->name; + if ($sib_name eq 'entersub') { + my $text = $self->deparse($kid->sibling, 1); + # Always show parens for \(&func()), but only with -p otherwise + $text = "($text)" if $self->{'parens'} + or $kid->sibling->private & OPpENTERSUB_AMPER; + return "\\$text"; + } + } + } + local $self->{'in_refgen'} = 1; + $self->pfixop($op, $cx, "\\", 20); +} + +sub e_anoncode { + my ($self, $info) = @_; + my $cv = $info->{code}; + my $text = $self->deparse_sub($cv); + return $self->keyword($self->kw_sub_or_method($cv)) . " $text"; +} + +sub pp_anoncode { + my ($self, $anoncode) = @_; + + return $self->e_anoncode( { code => $self->padval($anoncode->targ) } ); +} + +sub pp_anonconst { + my ($self, $anonconst) = @_; + + return $self->pp_anoncode( $anonconst->first->first->sibling ); +} + +sub pp_srefgen { pp_refgen(@_) } + +sub pp_readline { + my $self = shift; + my($op, $cx) = @_; + my $kid = $op->first; + if (is_scalar($kid) + and $op->flags & OPf_SPECIAL + and $self->deparse($kid, 1) eq 'ARGV') + { + return '<<>>'; + } + return $self->unop($op, $cx, "readline"); +} + +sub pp_rcatline { + my $self = shift; + my($op) = @_; + return "<" . $self->gv_name($self->gv_or_padgv($op)) . ">"; +} + +# Unary operators that can occur as pseudo-listops inside double quotes +sub dq_unop { + my $self = shift; + my($op, $cx, $name, $prec, $flags) = (@_, 0, 0); + my $kid; + if ($op->flags & OPf_KIDS) { + $kid = $op->first; + # If there's more than one kid, the first is an ex-pushmark. + $kid = $kid->sibling if not null $kid->sibling; + return $self->maybe_parens_unop($name, $kid, $cx); + } else { + return $name . ($op->flags & OPf_SPECIAL ? "()" : ""); + } +} + +sub pp_ucfirst { dq_unop(@_, "ucfirst") } +sub pp_lcfirst { dq_unop(@_, "lcfirst") } +sub pp_uc { dq_unop(@_, "uc") } +sub pp_lc { dq_unop(@_, "lc") } +sub pp_quotemeta { maybe_targmy(@_, \&dq_unop, "quotemeta") } +sub pp_fc { dq_unop(@_, "fc") } + +sub loopex { + my $self = shift; + my ($op, $cx, $name) = @_; + if (class($op) eq "PVOP") { + $name .= " " . $op->pv; + } elsif (class($op) eq "OP") { + # no-op + } elsif (class($op) eq "UNOP") { + (my $kid = $self->deparse($op->first, 7)) =~ s/^\cS//; + # last foo() is a syntax error. + $kid =~ /^(?!\d)\w/ and $kid = "($kid)"; + $name .= " $kid"; + } + return $self->maybe_parens($name, $cx, 7); +} + +sub pp_last { loopex(@_, "last") } +sub pp_next { loopex(@_, "next") } +sub pp_redo { loopex(@_, "redo") } +sub pp_goto { loopex(@_, "goto") } +sub pp_dump { loopex(@_, "CORE::dump") } + +sub ftst { + my $self = shift; + my($op, $cx, $name) = @_; + if (class($op) eq "UNOP") { + # Genuine '-X' filetests are exempt from the LLAFR, but not + # l?stat() + if ($name =~ /^-/) { + (my $kid = $self->deparse($op->first, 16)) =~ s/^\cS//; + return $self->maybe_parens("$name $kid", $cx, 16); + } + return $self->maybe_parens_unop($name, $op->first, $cx); + } elsif (class($op) =~ /^(SV|PAD)OP$/) { + return $self->maybe_parens_func($name, $self->pp_gv($op, 1), $cx, 16); + } else { # I don't think baseop filetests ever survive ck_ftst, but... + return $name; + } +} + +sub pp_lstat { ftst(@_, "lstat") } +sub pp_stat { ftst(@_, "stat") } +sub pp_ftrread { ftst(@_, "-R") } +sub pp_ftrwrite { ftst(@_, "-W") } +sub pp_ftrexec { ftst(@_, "-X") } +sub pp_fteread { ftst(@_, "-r") } +sub pp_ftewrite { ftst(@_, "-w") } +sub pp_fteexec { ftst(@_, "-x") } +sub pp_ftis { ftst(@_, "-e") } +sub pp_fteowned { ftst(@_, "-O") } +sub pp_ftrowned { ftst(@_, "-o") } +sub pp_ftzero { ftst(@_, "-z") } +sub pp_ftsize { ftst(@_, "-s") } +sub pp_ftmtime { ftst(@_, "-M") } +sub pp_ftatime { ftst(@_, "-A") } +sub pp_ftctime { ftst(@_, "-C") } +sub pp_ftsock { ftst(@_, "-S") } +sub pp_ftchr { ftst(@_, "-c") } +sub pp_ftblk { ftst(@_, "-b") } +sub pp_ftfile { ftst(@_, "-f") } +sub pp_ftdir { ftst(@_, "-d") } +sub pp_ftpipe { ftst(@_, "-p") } +sub pp_ftlink { ftst(@_, "-l") } +sub pp_ftsuid { ftst(@_, "-u") } +sub pp_ftsgid { ftst(@_, "-g") } +sub pp_ftsvtx { ftst(@_, "-k") } +sub pp_fttty { ftst(@_, "-t") } +sub pp_fttext { ftst(@_, "-T") } +sub pp_ftbinary { ftst(@_, "-B") } + +sub SWAP_CHILDREN () { 1 } +sub ASSIGN () { 2 } # has OP= variant +sub LIST_CONTEXT () { 4 } # Assignment is in list context + +my(%left, %right); + +sub assoc_class { + my $op = shift; + my $name = $op->name; + if ($name eq "concat" and $op->first->name eq "concat") { + # avoid spurious '=' -- see comment in pp_concat + return "concat"; + } + if ($name eq "null" and class($op) eq "UNOP" + and $op->first->name =~ /^(and|x?or)$/ + and null $op->first->sibling) + { + # Like all conditional constructs, OP_ANDs and OP_ORs are topped + # with a null that's used as the common end point of the two + # flows of control. For precedence purposes, ignore it. + # (COND_EXPRs have these too, but we don't bother with + # their associativity). + return assoc_class($op->first); + } + return $name . ($op->flags & OPf_STACKED ? "=" : ""); +} + +# Left associative operators, like '+', for which +# $a + $b + $c is equivalent to ($a + $b) + $c + +BEGIN { + %left = ('multiply' => 19, 'i_multiply' => 19, + 'divide' => 19, 'i_divide' => 19, + 'modulo' => 19, 'i_modulo' => 19, + 'repeat' => 19, + 'add' => 18, 'i_add' => 18, + 'subtract' => 18, 'i_subtract' => 18, + 'concat' => 18, + 'left_shift' => 17, 'right_shift' => 17, + 'bit_and' => 13, 'nbit_and' => 13, 'sbit_and' => 13, + 'bit_or' => 12, 'bit_xor' => 12, + 'sbit_or' => 12, 'sbit_xor' => 12, + 'nbit_or' => 12, 'nbit_xor' => 12, + 'and' => 3, + 'or' => 2, 'xor' => 2, + ); +} + +sub deparse_binop_left { + my $self = shift; + my($op, $left, $prec) = @_; + if ($left{assoc_class($op)} && $left{assoc_class($left)} + and $left{assoc_class($op)} == $left{assoc_class($left)}) + { + return $self->deparse($left, $prec - .00001); + } else { + return $self->deparse($left, $prec); + } +} + +# Right associative operators, like '=', for which +# $a = $b = $c is equivalent to $a = ($b = $c) + +BEGIN { + %right = ('pow' => 22, + 'sassign=' => 7, 'aassign=' => 7, + 'multiply=' => 7, 'i_multiply=' => 7, + 'divide=' => 7, 'i_divide=' => 7, + 'modulo=' => 7, 'i_modulo=' => 7, + 'repeat=' => 7, 'refassign' => 7, 'refassign=' => 7, + 'add=' => 7, 'i_add=' => 7, + 'subtract=' => 7, 'i_subtract=' => 7, + 'concat=' => 7, + 'left_shift=' => 7, 'right_shift=' => 7, + 'bit_and=' => 7, 'sbit_and=' => 7, 'nbit_and=' => 7, + 'nbit_or=' => 7, 'nbit_xor=' => 7, + 'sbit_or=' => 7, 'sbit_xor=' => 7, + 'andassign' => 7, + 'orassign' => 7, + ); +} + +sub deparse_binop_right { + my $self = shift; + my($op, $right, $prec) = @_; + if ($right{assoc_class($op)} && $right{assoc_class($right)} + and $right{assoc_class($op)} == $right{assoc_class($right)}) + { + return $self->deparse($right, $prec - .00001); + } else { + return $self->deparse($right, $prec); + } +} + +my %can_warn_about_lhs_not; +BEGIN { + %can_warn_about_lhs_not = map +($_ => 1), qw( + == + != + < + <= + > + >= + eq + ne + lt + le + gt + ge + isa + ); +} + +sub binop { + my $self = shift; + my ($op, $cx, $opname, $prec, $flags) = (@_, 0); + my $left = $op->first; + my $right = $op->last; + my $eq = ""; + if ($op->flags & OPf_STACKED && $flags & ASSIGN) { + $eq = "="; + $prec = 7; + } + if ($flags & SWAP_CHILDREN) { + ($left, $right) = ($right, $left); + } + my $leftop = $left; + $left = $self->deparse_binop_left($op, $left, $prec); + $left = "($left)" + if $flags & LIST_CONTEXT + and $left !~ /^(my|our|local|state|)\s*[\@%\(]/ + || do { + # Parenthesize if the left argument is a + # lone repeat op. + my $left = $leftop->first->sibling; + $left->name eq 'repeat' + && null($left->sibling); + } + or + $can_warn_about_lhs_not{$opname} + and $leftop->name eq 'not' + and $leftop->flags & OPf_PARENS + and $left !~ /\(/; + $right = $self->deparse_binop_right($op, $right, $prec); + return $self->maybe_parens("$left $opname$eq $right", $cx, $prec); +} + +sub pp_add { maybe_targmy(@_, \&binop, "+", 18, ASSIGN) } +sub pp_multiply { maybe_targmy(@_, \&binop, "*", 19, ASSIGN) } +sub pp_subtract { maybe_targmy(@_, \&binop, "-",18, ASSIGN) } +sub pp_divide { maybe_targmy(@_, \&binop, "/", 19, ASSIGN) } +sub pp_modulo { maybe_targmy(@_, \&binop, "%", 19, ASSIGN) } +sub pp_i_add { maybe_targmy(@_, \&binop, "+", 18, ASSIGN) } +sub pp_i_multiply { maybe_targmy(@_, \&binop, "*", 19, ASSIGN) } +sub pp_i_subtract { maybe_targmy(@_, \&binop, "-", 18, ASSIGN) } +sub pp_i_divide { maybe_targmy(@_, \&binop, "/", 19, ASSIGN) } +sub pp_i_modulo { maybe_targmy(@_, \&binop, "%", 19, ASSIGN) } +sub pp_pow { maybe_targmy(@_, \&binop, "**", 22, ASSIGN) } + +sub pp_left_shift { maybe_targmy(@_, \&binop, "<<", 17, ASSIGN) } +sub pp_right_shift { maybe_targmy(@_, \&binop, ">>", 17, ASSIGN) } +sub pp_bit_and { maybe_targmy(@_, \&binop, "&", 13, ASSIGN) } +sub pp_bit_or { maybe_targmy(@_, \&binop, "|", 12, ASSIGN) } +sub pp_bit_xor { maybe_targmy(@_, \&binop, "^", 12, ASSIGN) } +*pp_nbit_and = *pp_bit_and; +*pp_nbit_or = *pp_bit_or; +*pp_nbit_xor = *pp_bit_xor; +sub pp_sbit_and { maybe_targmy(@_, \&binop, "&.", 13, ASSIGN) } +sub pp_sbit_or { maybe_targmy(@_, \&binop, "|.", 12, ASSIGN) } +sub pp_sbit_xor { maybe_targmy(@_, \&binop, "^.", 12, ASSIGN) } + +sub pp_eq { binop(@_, "==", 14) } +sub pp_ne { binop(@_, "!=", 14) } +sub pp_lt { binop(@_, "<", 15) } +sub pp_gt { binop(@_, ">", 15) } +sub pp_ge { binop(@_, ">=", 15) } +sub pp_le { binop(@_, "<=", 15) } +sub pp_ncmp { binop(@_, "<=>", 14) } +sub pp_i_eq { binop(@_, "==", 14) } +sub pp_i_ne { binop(@_, "!=", 14) } +sub pp_i_lt { binop(@_, "<", 15) } +sub pp_i_gt { binop(@_, ">", 15) } +sub pp_i_ge { binop(@_, ">=", 15) } +sub pp_i_le { binop(@_, "<=", 15) } +sub pp_i_ncmp { maybe_targmy(@_, \&binop, "<=>", 14) } + +sub pp_seq { binop(@_, "eq", 14) } +sub pp_sne { binop(@_, "ne", 14) } +sub pp_slt { binop(@_, "lt", 15) } +sub pp_sgt { binop(@_, "gt", 15) } +sub pp_sge { binop(@_, "ge", 15) } +sub pp_sle { binop(@_, "le", 15) } +sub pp_scmp { maybe_targmy(@_, \&binop, "cmp", 14) } + +sub pp_isa { binop(@_, "isa", 15) } + +sub pp_sassign { binop(@_, "=", 7, SWAP_CHILDREN) } +sub pp_aassign { binop(@_, "=", 7, SWAP_CHILDREN | LIST_CONTEXT) } + +sub pp_padsv_store { + my $self = shift; + my ($op, $cx, $forbid_parens, @args) = @_; + my $targ = $op->targ; + my $var = $self->maybe_my($op, $cx, $self->padname($targ), + $self->padname_sv($targ), + $forbid_parens); + + my $val = $self->deparse($op->first, 7); + return $self->maybe_parens("$var = $val", $cx, 7); +} + +sub pp_smartmatch { + my ($self, $op, $cx) = @_; + if (($op->flags & OPf_SPECIAL) && $self->{expand} < 2) { + return $self->deparse($op->last, $cx); + } + else { + binop(@_, "~~", 14); + } +} + +# '.' is special because concats-of-concats are optimized to save copying +# by making all but the first concat stacked. The effect is as if the +# programmer had written '($a . $b) .= $c', except legal. +sub pp_concat { maybe_targmy(@_, \&real_concat) } +sub real_concat { + my $self = shift; + my($op, $cx) = @_; + my $left = $op->first; + my $right = $op->last; + my $eq = ""; + my $prec = 18; + if (($op->flags & OPf_STACKED) and !($op->private & OPpCONCAT_NESTED)) { + # '.=' rather than optimised '.' + $eq = "="; + $prec = 7; + } + $left = $self->deparse_binop_left($op, $left, $prec); + $right = $self->deparse_binop_right($op, $right, $prec); + return $self->maybe_parens("$left .$eq $right", $cx, $prec); +} + +sub pp_repeat { maybe_targmy(@_, \&repeat) } + +# 'x' is weird when the left arg is a list +sub repeat { + my $self = shift; + my($op, $cx) = @_; + my $left = $op->first; + my $right = $op->last; + my $eq = ""; + my $prec = 19; + if ($op->flags & OPf_STACKED) { + $eq = "="; + $prec = 7; + } + if (null($right)) { # list repeat; count is inside left-side ex-list + # in 5.21.5 and earlier + my $kid = $left->first->sibling; # skip pushmark + my @exprs; + for (; !null($kid->sibling); $kid = $kid->sibling) { + push @exprs, $self->deparse($kid, 6); + } + $right = $kid; + $left = "(" . join(", ", @exprs). ")"; + } else { + my $dolist = $op->private & OPpREPEAT_DOLIST; + $left = $self->deparse_binop_left($op, $left, $dolist ? 1 : $prec); + if ($dolist) { + $left = "($left)"; + } + } + $right = $self->deparse_binop_right($op, $right, $prec); + return $self->maybe_parens("$left x$eq $right", $cx, $prec); +} + +sub range { + my $self = shift; + my ($op, $cx, $type) = @_; + my $left = $op->first; + my $right = $left->sibling; + $left = $self->deparse($left, 9); + $right = $self->deparse($right, 9); + return $self->maybe_parens("$left $type $right", $cx, 9); +} + +sub pp_flop { + my $self = shift; + my($op, $cx) = @_; + my $flip = $op->first; + my $type = ($flip->flags & OPf_SPECIAL) ? "..." : ".."; + return $self->range($flip->first, $cx, $type); +} + +# one-line while/until is handled in pp_leave + +sub logop { + my $self = shift; + my ($op, $cx, $lowop, $lowprec, $highop, $highprec, $blockname) = @_; + my $left = $op->first; + my $right = $op->first->sibling; + $blockname &&= $self->keyword($blockname); + if ($cx < 1 and is_scope($right) and $blockname + and $self->{'expand'} < 7) + { # if ($a) {$b} + $left = $self->deparse($left, 1); + $right = $self->deparse($right, 0); + return "$blockname ($left) {\n\t$right\n\b}\cK"; + } elsif ($cx < 1 and $blockname and not $self->{'parens'} + and $self->{'expand'} < 7) { # $b if $a + $right = $self->deparse($right, 1); + $left = $self->deparse($left, 1); + return "$right $blockname $left"; + } elsif ($cx > $lowprec and $highop) { # $a && $b + $left = $self->deparse_binop_left($op, $left, $highprec); + $right = $self->deparse_binop_right($op, $right, $highprec); + return $self->maybe_parens("$left $highop $right", $cx, $highprec); + } else { # $a and $b + $left = $self->deparse_binop_left($op, $left, $lowprec); + $right = $self->deparse_binop_right($op, $right, $lowprec); + return $self->maybe_parens("$left $lowop $right", $cx, $lowprec); + } +} + +sub pp_and { logop(@_, "and", 3, "&&", 11, "if") } +sub pp_or { logop(@_, "or", 2, "||", 10, "unless") } +sub pp_dor { logop(@_, "//", 10) } + +sub pp_xor { + my $self = shift; + my ($op, $cx) = @_; + if ($cx > 2 or $op->flags & OPf_STACKED) { + binop($self, @_, "^^", 10, ASSIGN); + } + else { + binop($self, @_, "xor", 2); + } +} + +sub logassignop { + my $self = shift; + my ($op, $cx, $opname) = @_; + my $left = $op->first; + my $right = $op->first->sibling->first; # skip sassign + $left = $self->deparse($left, 7); + $right = $self->deparse($right, 7); + return $self->maybe_parens("$left $opname $right", $cx, 7); +} + +sub pp_andassign { logassignop(@_, "&&=") } +sub pp_orassign { logassignop(@_, "||=") } +sub pp_dorassign { logassignop(@_, "//=") } + +my %cmpchain_cmpops = ( + eq => ["==", 14], + i_eq => ["==", 14], + ne => ["!=", 14], + i_ne => ["!=", 14], + seq => ["eq", 14], + sne => ["ne", 14], + lt => ["<", 15], + i_lt => ["<", 15], + gt => [">", 15], + i_gt => [">", 15], + le => ["<=", 15], + i_le => ["<=", 15], + ge => [">=", 15], + i_ge => [">=", 15], + slt => ["lt", 15], + sgt => ["gt", 15], + sle => ["le", 15], + sge => ["ge", 15], +); +sub pp_cmpchain_and { + my($self, $op, $cx) = @_; + my($prec, $dep); + while(1) { + my($thiscmp, $rightcond); + if($op->name eq "cmpchain_and") { + $thiscmp = $op->first; + $rightcond = $thiscmp->sibling; + } else { + $thiscmp = $op; + } + my $thiscmptype = $cmpchain_cmpops{$thiscmp->name} // (return "XXX"); + if(defined $prec) { + $thiscmptype->[1] == $prec or return "XXX"; + $thiscmp->first->name eq "null" && + !($thiscmp->first->flags & OPf_KIDS) + or return "XXX"; + } else { + $prec = $thiscmptype->[1]; + $dep = $self->deparse($thiscmp->first, $prec); + } + $dep .= " ".$thiscmptype->[0]." "; + my $operand = $thiscmp->last; + if(defined $rightcond) { + $operand->name eq "cmpchain_dup" or return "XXX"; + $operand = $operand->first; + } + $dep .= $self->deparse($operand, $prec); + last unless defined $rightcond; + if($rightcond->name eq "null" && ($rightcond->flags & OPf_KIDS) && + $rightcond->first->name eq "cmpchain_and") { + $rightcond = $rightcond->first; + } + $op = $rightcond; + } + return $self->maybe_parens($dep, $cx, $prec); +} + +sub rv2gv_or_string { + my($self,$op) = @_; + if ($op->name eq "gv") { # could be open("open") or open("###") + my($name,$quoted) = + $self->stash_variable_name("", $self->gv_or_padgv($op)); + $quoted ? $name : "*$name"; + } + else { + $self->deparse($op, 6); + } +} + +sub listop { + my $self = shift; + my($op, $cx, $name, $kid, $nollafr) = @_; + my(@exprs); + my $parens = ($cx >= 5) || $self->{'parens'}; + $kid ||= $op->first->sibling; + # If there are no arguments, add final parentheses (or parenthesize the + # whole thing if the llafr does not apply) to account for cases like + # (return)+1 or setpgrp()+1. When the llafr does not apply, we use a + # precedence of 6 (< comma), as "return, 1" does not need parentheses. + if (null $kid) { + return $nollafr + ? $self->maybe_parens($self->keyword($name), $cx, 7) + : $self->keyword($name) . '()' x (7 < $cx); + } + my $first; + my $fullname = $self->keyword($name); + my $proto = prototype("CORE::$name"); + if ( + ( (defined $proto && $proto =~ /^;?\*/) + || $name eq 'select' # select(F) doesn't have a proto + ) + && $kid->name eq "rv2gv" + && !($kid->private & OPpLVAL_INTRO) + ) { + $first = $self->rv2gv_or_string($kid->first); + } + else { + $first = $self->deparse($kid, 6); + } + if ($name eq "chmod" && $first =~ /^\d+$/) { + $first = sprintf("%#o", $first); + } + $first = "+$first" + if not $parens and not $nollafr and substr($first, 0, 1) eq "("; + push @exprs, $first; + $kid = $kid->sibling; + if (defined $proto && $proto =~ /^\*\*/ && $kid->name eq "rv2gv" + && !($kid->private & OPpLVAL_INTRO)) { + push @exprs, $first = $self->rv2gv_or_string($kid->first); + $kid = $kid->sibling; + } + for (; !null($kid); $kid = $kid->sibling) { + push @exprs, $self->deparse($kid, 6); + } + if ($name eq "reverse" && ($op->private & OPpREVERSE_INPLACE)) { + return "$exprs[0] = $fullname" + . ($parens ? "($exprs[0])" : " $exprs[0]"); + } + + if ($parens && $nollafr) { + return "($fullname " . join(", ", @exprs) . ")"; + } elsif ($parens) { + return "$fullname(" . join(", ", @exprs) . ")"; + } else { + return "$fullname " . join(", ", @exprs); + } +} + +sub pp_bless { listop(@_, "bless") } +sub pp_atan2 { maybe_targmy(@_, \&listop, "atan2") } +sub pp_substr { + my ($self,$op,$cx) = @_; + if ($op->private & OPpSUBSTR_REPL_FIRST) { + return + listop($self, $op, 7, "substr", $op->first->sibling->sibling) + . " = " + . $self->deparse($op->first->sibling, 7); + } + maybe_local(@_, listop(@_, "substr")) +} + +sub pp_substr_left { + my ($self,$op,$cx) = @_; + + my $lex = ($op->private & OPpTARGET_MY); + + my $val = 'substr(' . $self->deparse($op->first->sibling, $cx) + . ', 0, ' . $self->deparse($op->first->sibling->sibling->sibling, $cx) + . ( (($op->private & 7) == 3) ? ')' : ", '')" ); + + if ($lex) { + my $targ = $op->targ; + my $var = $self->maybe_my($op, $cx, $self->padname($op->targ), + $self->padname_sv($targ), + 0); + $val = $self->maybe_parens("$var = $val", $cx, 7); + } + $val; +} + +sub pp_index { + # Also handles pp_rindex. + # + # The body of this function includes an unrolled maybe_targmy(), + # since the two parts of that sub's actions need to have have the + # '== -1' bit in between + + my($self, $op, $cx) = @_; + + my $lex = ($op->private & OPpTARGET_MY); + my $bool = ($op->private & OPpTRUEBOOL); + + my $val = $self->listop($op, ($bool ? 14 : $lex ? 7 : $cx), $op->name); + + # (index() == -1) has op_eq and op_const optimised away + if ($bool) { + $val .= ($op->private & OPpINDEX_BOOLNEG) ? " == -1" : " != -1"; + $val = "($val)" if ($op->flags & OPf_PARENS); + } + if ($lex) { + my $var = $self->padname($op->targ); + $val = $self->maybe_parens("$var = $val", $cx, 7); + } + $val; +} + +sub pp_rindex { pp_index(@_); } +sub pp_vec { maybe_targmy(@_, \&maybe_local, listop(@_, "vec")) } +sub pp_sprintf { maybe_targmy(@_, \&listop, "sprintf") } +sub pp_formline { listop(@_, "formline") } # see also deparse_format +sub pp_crypt { maybe_targmy(@_, \&listop, "crypt") } +sub pp_unpack { listop(@_, "unpack") } +sub pp_pack { listop(@_, "pack") } +sub pp_join { maybe_targmy(@_, \&listop, "join") } +sub pp_splice { listop(@_, "splice") } +sub pp_push { maybe_targmy(@_, \&listop, "push") } +sub pp_unshift { maybe_targmy(@_, \&listop, "unshift") } +sub pp_reverse { listop(@_, "reverse") } +sub pp_warn { listop(@_, "warn") } +sub pp_die { listop(@_, "die") } +sub pp_return { listop(@_, "return", undef, 1) } # llafr does not apply +sub pp_open { listop(@_, "open") } +sub pp_pipe_op { listop(@_, "pipe") } +sub pp_tie { listop(@_, "tie") } +sub pp_binmode { listop(@_, "binmode") } +sub pp_dbmopen { listop(@_, "dbmopen") } +sub pp_sselect { listop(@_, "select") } +sub pp_select { listop(@_, "select") } +sub pp_read { listop(@_, "read") } +sub pp_sysopen { listop(@_, "sysopen") } +sub pp_sysseek { listop(@_, "sysseek") } +sub pp_sysread { listop(@_, "sysread") } +sub pp_syswrite { listop(@_, "syswrite") } +sub pp_send { listop(@_, "send") } +sub pp_recv { listop(@_, "recv") } +sub pp_seek { listop(@_, "seek") } +sub pp_fcntl { listop(@_, "fcntl") } +sub pp_ioctl { listop(@_, "ioctl") } +sub pp_flock { maybe_targmy(@_, \&listop, "flock") } +sub pp_socket { listop(@_, "socket") } +sub pp_sockpair { listop(@_, "socketpair") } +sub pp_bind { listop(@_, "bind") } +sub pp_connect { listop(@_, "connect") } +sub pp_listen { listop(@_, "listen") } +sub pp_accept { listop(@_, "accept") } +sub pp_shutdown { listop(@_, "shutdown") } +sub pp_gsockopt { listop(@_, "getsockopt") } +sub pp_ssockopt { listop(@_, "setsockopt") } +sub pp_chown { maybe_targmy(@_, \&listop, "chown") } +sub pp_unlink { maybe_targmy(@_, \&listop, "unlink") } +sub pp_chmod { maybe_targmy(@_, \&listop, "chmod") } +sub pp_utime { maybe_targmy(@_, \&listop, "utime") } +sub pp_rename { maybe_targmy(@_, \&listop, "rename") } +sub pp_link { maybe_targmy(@_, \&listop, "link") } +sub pp_symlink { maybe_targmy(@_, \&listop, "symlink") } +sub pp_mkdir { maybe_targmy(@_, \&listop, "mkdir") } +sub pp_open_dir { listop(@_, "opendir") } +sub pp_seekdir { listop(@_, "seekdir") } +sub pp_waitpid { maybe_targmy(@_, \&listop, "waitpid") } +sub pp_system { maybe_targmy(@_, \&indirop, "system") } +sub pp_exec { maybe_targmy(@_, \&indirop, "exec") } +sub pp_kill { maybe_targmy(@_, \&listop, "kill") } +sub pp_setpgrp { maybe_targmy(@_, \&listop, "setpgrp") } +sub pp_getpriority { maybe_targmy(@_, \&listop, "getpriority") } +sub pp_setpriority { maybe_targmy(@_, \&listop, "setpriority") } +sub pp_shmget { listop(@_, "shmget") } +sub pp_shmctl { listop(@_, "shmctl") } +sub pp_shmread { listop(@_, "shmread") } +sub pp_shmwrite { listop(@_, "shmwrite") } +sub pp_msgget { listop(@_, "msgget") } +sub pp_msgctl { listop(@_, "msgctl") } +sub pp_msgsnd { listop(@_, "msgsnd") } +sub pp_msgrcv { listop(@_, "msgrcv") } +sub pp_semget { listop(@_, "semget") } +sub pp_semctl { listop(@_, "semctl") } +sub pp_semop { listop(@_, "semop") } +sub pp_ghbyaddr { listop(@_, "gethostbyaddr") } +sub pp_gnbyaddr { listop(@_, "getnetbyaddr") } +sub pp_gpbynumber { listop(@_, "getprotobynumber") } +sub pp_gsbyname { listop(@_, "getservbyname") } +sub pp_gsbyport { listop(@_, "getservbyport") } +sub pp_syscall { listop(@_, "syscall") } + +sub pp_glob { + my $self = shift; + my($op, $cx) = @_; + my $kid = $op->first->sibling; # skip pushmark + my $keyword = + $op->flags & OPf_SPECIAL ? 'glob' : $self->keyword('glob'); + my $text = $self->deparse($kid, $cx); + return $cx >= 5 || $self->{'parens'} + ? "$keyword($text)" + : "$keyword $text"; +} + +# Truncate is special because OPf_SPECIAL makes a bareword first arg +# be a filehandle. This could probably be better fixed in the core +# by moving the GV lookup into ck_truc. + +sub pp_truncate { + my $self = shift; + my($op, $cx) = @_; + my(@exprs); + my $parens = ($cx >= 5) || $self->{'parens'}; + my $kid = $op->first->sibling; + my $fh; + if ($op->flags & OPf_SPECIAL) { + # $kid is an OP_CONST + $fh = $self->const_sv($kid)->PV; + } else { + $fh = $self->deparse($kid, 6); + $fh = "+$fh" if not $parens and substr($fh, 0, 1) eq "("; + } + my $len = $self->deparse($kid->sibling, 6); + my $name = $self->keyword('truncate'); + if ($parens) { + return "$name($fh, $len)"; + } else { + return "$name $fh, $len"; + } +} + +sub indirop { + my $self = shift; + my($op, $cx, $name) = @_; + my($expr, @exprs); + my $firstkid = my $kid = $op->first->sibling; + my $indir = ""; + if ($op->flags & OPf_STACKED) { + $indir = $kid; + $indir = $indir->first; # skip rv2gv + if (is_scope($indir)) { + $indir = "{" . $self->deparse($indir, 0) . "}"; + $indir = "{;}" if $indir eq "{}"; + } elsif ($indir->name eq "const" && $indir->private & OPpCONST_BARE) { + $indir = $self->const_sv($indir)->PV; + } else { + $indir = $self->deparse($indir, 24); + } + $indir = $indir . " "; + $kid = $kid->sibling; + } + if ($name eq "sort" && $op->private & (OPpSORT_NUMERIC | OPpSORT_INTEGER)) { + $indir = ($op->private & OPpSORT_DESCEND) ? '{$b <=> $a} ' + : '{$a <=> $b} '; + } + elsif ($name eq "sort" && $op->private & OPpSORT_DESCEND) { + $indir = '{$b cmp $a} '; + } + for (; !null($kid); $kid = $kid->sibling) { + $expr = $self->deparse($kid, !$indir && $kid == $firstkid && $name eq "sort" && $firstkid->name eq "entersub" ? 16 : 6); + push @exprs, $expr; + } + my $name2; + if ($name eq "sort" && $op->private & OPpSORT_REVERSE) { + $name2 = $self->keyword('reverse') . ' ' . $self->keyword('sort'); + } + else { $name2 = $self->keyword($name) } + if ($name eq "sort" && ($op->private & OPpSORT_INPLACE)) { + return "$exprs[0] = $name2 $indir $exprs[0]"; + } + + my $args = $indir . join(", ", @exprs); + if ($indir ne "" && $name eq "sort") { + # We don't want to say "sort(f 1, 2, 3)", since perl -w will + # give bareword warnings in that case. Therefore if context + # requires, we'll put parens around the outside "(sort f 1, 2, + # 3)". Unfortunately, we'll currently think the parens are + # necessary more often that they really are, because we don't + # distinguish which side of an assignment we're on. + if ($cx >= 5) { + return "($name2 $args)"; + } else { + return "$name2 $args"; + } + } elsif ( + !$indir && $name eq "sort" + && !null($op->first->sibling) + && $op->first->sibling->name eq 'entersub' + ) { + # We cannot say sort foo(bar), as foo will be interpreted as a + # comparison routine. We have to say sort(...) in that case. + return "$name2($args)"; + } else { + return length $args + ? $self->maybe_parens_func($name2, $args, $cx, 5) + : $name2 . '()' x (7 < $cx); + } + +} + +sub pp_prtf { indirop(@_, "printf") } +sub pp_print { indirop(@_, "print") } +sub pp_say { indirop(@_, "say") } +sub pp_sort { indirop(@_, "sort") } + +sub mapop { + my $self = shift; + my($op, $cx) = @_; + my($expr, @exprs); + my $kid = $op->first; # this is the (map|grep|any|all)start + my ( $name ) = $kid->name =~ m/(.*)start/; # anystart and allstart share anywhile + $kid = $kid->first->sibling; # skip a pushmark + my $code = $kid->first; # skip a null + if (is_scope $code) { + $code = "{" . $self->deparse($code, 0) . "} "; + } else { + $code = $self->deparse($code, 24); + $code .= ", " if !null($kid->sibling); + } + $kid = $kid->sibling; + for (; !null($kid); $kid = $kid->sibling) { + $expr = $self->deparse($kid, 6); + push @exprs, $expr if defined $expr; + } + return $self->maybe_parens_func($self->keyword($name), + $code . join(", ", @exprs), $cx, 5); +} + +sub pp_mapwhile { mapop(@_) } +sub pp_grepwhile { mapop(@_) } +sub pp_anywhile { mapop(@_) } +sub pp_mapstart { baseop(@_, "map") } +sub pp_grepstart { baseop(@_, "grep") } + +my %uses_intro; +BEGIN { + @uses_intro{ + eval { require B::Op_private } + ? @{$B::Op_private::ops_using{OPpLVAL_INTRO}} + : qw(gvsv rv2sv rv2hv rv2gv rv2av aelem helem aslice + hslice delete padsv padav padhv enteriter entersub padrange + pushmark cond_expr refassign list) + } = (); + delete @uses_intro{qw( lvref lvrefslice lvavref entersub )}; +} + + +# Look for a my/state attribute declaration in a list or ex-list. +# Returns undef if not found, 'my($x, @a) :Foo(bar)' etc otherwise. +# +# There are three basic tree structs that are expected: +# +# my $x :foo; +# <1> ex-list vK/LVINTRO ->c +# <0> ex-pushmark v ->3 +# <1> entersub[t2] vKRS*/TARG ->b +# .... +# <0> padsv[$x:64,65] vM/LVINTRO ->c +# +# my @a :foo; +# my %h :foo; +# +# <1> ex-list vK ->c +# <0> ex-pushmark v ->3 +# <0> padav[@a:64,65] vM/LVINTRO ->4 +# <1> entersub[t2] vKRS*/TARG ->c +# .... +# +# my ($x,@a,%h) :foo; +# +# <;> nextstate(main 64 -e:1) v:{ ->3 +# <@> list vKP ->w +# <0> pushmark vM/LVINTRO ->4 +# <0> padsv[$x:64,65] vM/LVINTRO ->5 +# <0> padav[@a:64,65] vM/LVINTRO ->6 +# <0> padhv[%h:64,65] vM/LVINTRO ->7 +# <1> entersub[t4] vKRS*/TARG ->f +# .... +# <1> entersub[t5] vKRS*/TARG ->n +# .... +# <1> entersub[t6] vKRS*/TARG ->v +# .... +# where the entersub in all cases looks like +# <1> entersub[t2] vKRS*/TARG ->c +# <0> pushmark s ->5 +# <$> const[PV "attributes"] sM ->6 +# <$> const[PV "main"] sM ->7 +# <1> srefgen sKM/1 ->9 +# <1> ex-list lKRM ->8 +# <0> padsv[@a:64,65] sRM ->8 +# <$> const[PV "foo"] sM ->a +# <.> method_named[PV "import"] ->b + +sub maybe_var_attr { + my ($self, $op, $cx) = @_; + + my $kid = $op->first->sibling; # skip pushmark + return if class($kid) eq 'NULL'; + + my $lop; + my $type; + + # Extract out all the pad ops and entersub ops into + # @padops and @entersubops. Return if anything else seen. + # Also determine what class (if any) all the pad vars belong to + my $class; + my $decl; # 'my' or 'state' + my (@padops, @entersubops); + for ($lop = $kid; !null($lop); $lop = $lop->sibling) { + my $lopname = $lop->name; + my $loppriv = $lop->private; + if ($lopname =~ /^pad[sah]v$/) { + return unless $loppriv & OPpLVAL_INTRO; + + my $padname = $self->padname_sv($lop->targ); + my $thisclass = ($padname->FLAGS & PADNAMEf_TYPED) + ? $padname->SvSTASH->NAME : 'main'; + + # all pad vars must be in the same class + $class //= $thisclass; + return unless $thisclass eq $class; + + # all pad vars must be the same sort of declaration + # (all my, all state, etc) + my $this = ($loppriv & OPpPAD_STATE) ? 'state' : 'my'; + if (defined $decl) { + return unless $this eq $decl; + } + $decl = $this; + + push @padops, $lop; + } + elsif ($lopname eq 'entersub') { + push @entersubops, $lop; + } + else { + return; + } + } + + return unless @padops && @padops == @entersubops; + + # there should be a balance: each padop has a corresponding + # 'attributes'->import() method call, in the same order. + + my @varnames; + my $attr_text; + + for my $i (0..$#padops) { + my $padop = $padops[$i]; + my $esop = $entersubops[$i]; + + push @varnames, $self->padname($padop->targ); + + return unless ($esop->flags & OPf_KIDS); + + my $kid = $esop->first; + return unless $kid->type == OP_PUSHMARK; + + $kid = $kid->sibling; + return unless $$kid && $kid->type == OP_CONST; + return unless $self->const_sv($kid)->PV eq 'attributes'; + + $kid = $kid->sibling; + return unless $$kid && $kid->type == OP_CONST; # __PACKAGE__ + + $kid = $kid->sibling; + return unless $$kid + && $kid->name eq "srefgen" + && ($kid->flags & OPf_KIDS) + && ($kid->first->flags & OPf_KIDS) + && $kid->first->first->name =~ /^pad[sah]v$/ + && $kid->first->first->targ == $padop->targ; + + $kid = $kid->sibling; + my @attr; + while ($$kid) { + last if ($kid->type != OP_CONST); + push @attr, $self->const_sv($kid)->PV; + $kid = $kid->sibling; + } + return unless @attr; + my $thisattr = ":" . join(' ', @attr); + $attr_text //= $thisattr; + # all import calls must have the same list of attributes + return unless $attr_text eq $thisattr; + + return unless $kid->name eq 'method_named'; + return unless $self->meth_sv($kid)->PV eq 'import'; + + $kid = $kid->sibling; + return if $$kid; + } + + my $res = $decl; + $res .= " $class " if $class ne 'main'; + $res .= + (@varnames > 1) + ? "(" . join(', ', @varnames) . ')' + : " $varnames[0]"; + + return "$res $attr_text"; +} + + +sub pp_list { + my $self = shift; + my($op, $cx) = @_; + + { + # might be my ($s,@a,%h) :Foo(bar); + my $my_attr = maybe_var_attr($self, $op, $cx); + return $my_attr if defined $my_attr; + } + + my($expr, @exprs); + my $kid = $op->first->sibling; # skip pushmark + return '' if class($kid) eq 'NULL'; + my $lop; + my $local = "either"; # could be local(...), my(...), state(...) or our(...) + my $type; + for ($lop = $kid; !null($lop); $lop = $lop->sibling) { + my $lopname = $lop->name; + my $loppriv = $lop->private; + my $newtype; + if ($lopname =~ /^pad[ash]v$/ && $loppriv & OPpLVAL_INTRO) { + if ($loppriv & OPpPAD_STATE) { # state() + ($local = "", last) if $local !~ /^(?:either|state)$/; + $local = "state"; + } else { # my() + ($local = "", last) if $local !~ /^(?:either|my)$/; + $local = "my"; + } + my $padname = $self->padname_sv($lop->targ); + if ($padname->FLAGS & PADNAMEf_TYPED) { + $newtype = $padname->SvSTASH->NAME; + } + } elsif ($lopname eq 'padsv_store') { + # don't interpret as my (list) if it has an implicit assign + $local = ""; + } elsif ($lopname =~ /^(?:gv|rv2)([ash])v$/ + && $loppriv & OPpOUR_INTRO + or $lopname eq "null" && class($lop) eq 'UNOP' + && $lop->first->name eq "gvsv" + && $lop->first->private & OPpOUR_INTRO) { # our() + my $newlocal = "local " x !!($loppriv & OPpLVAL_INTRO) . "our"; + ($local = "", last) + if $local ne 'either' && $local ne $newlocal; + $local = $newlocal; + my $funny = !$1 || $1 eq 's' ? '$' : $1 eq 'a' ? '@' : '%'; + if (my $t = $self->find_our_type( + $funny . $self->gv_or_padgv($lop->first)->NAME + )) { + $newtype = $t; + } + } elsif ($lopname ne 'undef' + and !($loppriv & OPpLVAL_INTRO) + || !exists $uses_intro{$lopname eq 'null' + ? substr B::ppname($lop->targ), 3 + : $lopname}) + { + $local = ""; # or not + last; + } elsif ($lopname ne "undef") + { + # local() + ($local = "", last) if $local !~ /^(?:either|local)$/; + $local = "local"; + } + if (defined $type && defined $newtype && $newtype ne $type) { + $local = ''; + last; + } + $type = $newtype; + } + $local = "" if $local eq "either"; # no point if it's all undefs + $local &&= join ' ', map $self->keyword($_), split / /, $local; + $local .= " $type " if $local && length $type; + return $self->deparse($kid, $cx) if null $kid->sibling and not $local; + for (; !null($kid); $kid = $kid->sibling) { + if ($local) { + if (class($kid) eq "UNOP" and $kid->first->name eq "gvsv") { + $lop = $kid->first; + } else { + $lop = $kid; + } + $self->{'avoid_local'}{$$lop}++; + $expr = $self->deparse($kid, 6); + delete $self->{'avoid_local'}{$$lop}; + } else { + $expr = $self->deparse($kid, 6); + } + push @exprs, $expr; + } + if ($local) { + if (@exprs == 1 && ($local eq 'state' || $local eq 'CORE::state')) { + # 'state @a = ...' is legal, while 'state(@a) = ...' currently isn't + return "$local $exprs[0]"; + } + return "$local(" . join(", ", @exprs) . ")"; + } else { + return $self->maybe_parens( join(", ", @exprs), $cx, 6); + } +} + +sub is_ifelse_cont { + my $op = shift; + return ($op->name eq "null" and class($op) eq "UNOP" + and $op->first->name =~ /^(and|cond_expr)$/ + and is_scope($op->first->first->sibling)); +} + +sub pp_cond_expr { + my $self = shift; + my($op, $cx) = @_; + my $cond = $op->first; + my $true = $cond->sibling; + my $false = $true->sibling; + my $cuddle = $self->{'cuddle'}; + unless ($cx < 1 and (is_scope($true) and $true->name ne "null") and + (is_scope($false) || is_ifelse_cont($false)) + and $self->{'expand'} < 7) { + $cond = $self->deparse($cond, 8); + $true = $self->deparse($true, 6); + $false = $self->deparse($false, 8); + return $self->maybe_parens("$cond ? $true : $false", $cx, 8); + } + + $cond = $self->deparse($cond, 1); + $true = $self->deparse($true, 0); + my $head = $self->keyword("if") . " ($cond) {\n\t$true\n\b}"; + my @elsifs; + my $elsif; + while (!null($false) and is_ifelse_cont($false)) { + my $newop = $false->first; + my $newcond = $newop->first; + my $newtrue = $newcond->sibling; + $false = $newtrue->sibling; # last in chain is OP_AND => no else + if ($newcond->name eq "lineseq") + { + # lineseq to ensure correct line numbers in elsif() + # Bug #37302 fixed by change #33710. + $newcond = $newcond->first->sibling; + } + $newcond = $self->deparse($newcond, 1); + $newtrue = $self->deparse($newtrue, 0); + $elsif ||= $self->keyword("elsif"); + push @elsifs, "$elsif ($newcond) {\n\t$newtrue\n\b}"; + } + if (!null($false)) { + $false = $cuddle . $self->keyword("else") . " {\n\t" . + $self->deparse($false, 0) . "\n\b}\cK"; + } else { + $false = "\cK"; + } + return $head . join($cuddle, "", @elsifs) . $false; +} + +sub pp_once { + my ($self, $op, $cx) = @_; + my $cond = $op->first; + my $true = $cond->sibling; + + my $ret = $self->deparse($true, $cx); + $ret =~ s/^(\(?)\$/$1 . $self->keyword("state") . ' $'/e; + $ret; +} + +sub loop_common { + my $self = shift; + my($op, $cx, $init) = @_; + my $enter = $op->first; + my $kid = $enter->sibling; + local(@$self{qw'curstash warnings hints hinthash'}) + = @$self{qw'curstash warnings hints hinthash'}; + my $head = ""; + my $bare = 0; + my $body; + my $cond = undef; + my $name; + if ($kid->name eq "lineseq") { # bare or infinite loop + if ($kid->last->name eq "unstack") { # infinite + $head = "while (1) "; # Can't use for(;;) if there's a continue + $cond = ""; + } else { + $bare = 1; + } + $body = $kid; + } elsif ($enter->name eq "enteriter") { # foreach + my $ary = $enter->first->sibling; # first was pushmark + my $var = $ary->sibling; + my $iter = $kid->first->first; + if ($ary->name eq 'null' and $enter->private & OPpITER_REVERSED) { + # "reverse" was optimised away + $ary = listop($self, $ary->first->sibling, 1, 'reverse'); + } elsif ($enter->flags & OPf_STACKED + and not null $ary->first->sibling->sibling) + { + $ary = $self->deparse($ary->first->sibling, 9) . " .. " . + $self->deparse($ary->first->sibling->sibling, 9); + } else { + $ary = $self->deparse($ary, 1); + } + + if ($iter->private & OPpITER_INDEXED) { + $ary = "builtin::indexed $ary"; + } + + if ($enter->flags & OPf_PARENS) { + # for my ($x, $y, ...) ... + # for my ($foo, $bar) () stores the count (less 1) in the targ of + # the ITER op. For the degenerate case of 1 var ($x), the + # TARG is zero, so it works anyway + my $iter_targ = $kid->first->first->targ; + my @vars; + my $targ = $enter->targ; + while ($iter_targ-- >= 0) { + push @vars, $self->padname_sv($targ)->PVX; + ++$targ; + } + $var = 'my (' . join(', ', @vars) . ')'; + } elsif (null $var) { + $var = $self->pp_padsv($enter, 1, 1); + } elsif ($var->name eq "rv2gv") { + $var = $self->pp_rv2sv($var, 1); + if ($enter->private & OPpOUR_INTRO) { + # our declarations don't have package names + $var =~ s/^(.).*::/$1/; + $var = "our $var"; + } + } elsif ($var->name eq "gv") { + $var = "\$" . $self->deparse($var, 1); + } else { + $var = $self->deparse($var, 1); + } + $body = $iter->sibling; + if (!is_state $body->first and $body->first->name !~ /^(?:stub|leave|scope)$/) { + confess unless $var eq '$_'; + $body = $body->first; + return $self->deparse($body, 2) . " " + . $self->keyword("foreach") . " ($ary)"; + } + $head = "foreach $var ($ary) "; + } elsif ($kid->name eq "null") { # while/until + $kid = $kid->first; + $name = {"and" => "while", "or" => "until"}->{$kid->name}; + $cond = $kid->first; + $body = $kid->first->sibling; + } elsif ($kid->name eq "stub") { # bare and empty + return "{;}"; # {} could be a hashref + } + # If there isn't a continue block, then the next pointer for the loop + # will point to the unstack, which is kid's last child, except + # in a bare loop, when it will point to the leaveloop. When neither of + # these conditions hold, then the second-to-last child is the continue + # block (or the last in a bare loop). + my $cont_start = $enter->nextop; + my $cont; + my $precond; + my $postcond; + if ($$cont_start != $$op && ${$cont_start} != ${$body->last}) { + if ($bare) { + $cont = $body->last; + } else { + $cont = $body->first; + while (!null($cont->sibling->sibling)) { + $cont = $cont->sibling; + } + } + my $state = $body->first; + my $cuddle = $self->{'cuddle'}; + my @states; + for (; $$state != $$cont; $state = $state->sibling) { + push @states, $state; + } + $body = $self->lineseq(undef, 0, @states); + if (defined $cond and not is_scope $cont and $self->{'expand'} < 3) { + $precond = "for ($init; "; + $postcond = "; " . $self->deparse($cont, 1) .") "; + $cont = "\cK"; + } else { + $cont = $cuddle . "continue {\n\t" . + $self->deparse($cont, 0) . "\n\b}\cK"; + } + } else { + return "" if !defined $body; + if (length $init) { + $precond = "for ($init; "; + $postcond = ";) "; + } + $cont = "\cK"; + $body = $self->deparse($body, 0); + } + if ($precond) { # for(;;) + $cond &&= $name eq 'until' + ? listop($self, undef, 1, "not", $cond->first) + : $self->deparse($cond, 1); + $head = "$precond$cond$postcond"; + } + if ($name && !$head) { + ref $cond and $cond = $self->deparse($cond, 1); + $head = "$name ($cond) "; + } + $head =~ s/^(for(?:each)?|while|until)/$self->keyword($1)/e; + $body =~ s/;?$/;\n/; + + return $head . "{\n\t" . $body . "\b}" . $cont; +} + +sub pp_leaveloop { shift->loop_common(@_, "") } + +sub for_loop { + my $self = shift; + my($op, $cx) = @_; + my $init = $self->deparse($op, 1); + my $s = $op->sibling; + my $ll = $s->name eq "unstack" ? $s->sibling : $s->first->sibling; + return $self->loop_common($ll, $cx, $init); +} + +sub pp_leavetry { + my $self = shift; + return "eval {\n\t" . $self->pp_leave(@_) . "\n\b}"; +} + +sub pp_leavetrycatch_with_finally { + my $self = shift; + my ($op, $finallyop) = @_; + + # Expect that the first three kids should be (entertrycatch, poptry, catch) + my $entertrycatch = $op->first; + $entertrycatch->name eq "entertrycatch" or die "Expected entertrycatch as first child of leavetrycatch"; + + my $tryblock = $entertrycatch->sibling; + $tryblock->name eq "poptry" or die "Expected poptry as second child of leavetrycatch"; + + my $catch = $tryblock->sibling; + $catch->name eq "catch" or die "Expected catch as third child of leavetrycatch"; + + my $catchblock = $catch->first->sibling; + my $name = $catchblock->name; + unless ($name eq "scope" || $name eq "leave") { + die "Expected scope or leave as second child of catch, got $name instead"; + } + + my $trycode = scopeop(0, $self, $tryblock); + my $catchvar = $self->padname($catch->targ); + my $catchcode = $name eq 'scope' ? scopeop(0, $self, $catchblock) + : scopeop(1, $self, $catchblock); + + my $finallycode = ""; + if($finallyop) { + my $body = $self->deparse($finallyop->first->first); + $finallycode = "\nfinally {\n\t$body\n\b}"; + } + + return "try {\n\t$trycode\n\b}\n" . + "catch($catchvar) {\n\t$catchcode\n\b}$finallycode\cK"; +} + +sub pp_leavetrycatch { + my $self = shift; + my ($op, @args) = @_; + return $self->pp_leavetrycatch_with_finally($op, undef, @args); +} + +sub _op_is_or_was { + my ($op, $expect_type) = @_; + my $type = $op->type; + return($type == $expect_type + || ($type == OP_NULL && $op->targ == $expect_type)); +} + +sub pp_null { + my($self, $op, $cx) = @_; + + # might be 'my $s :Foo(bar);' + if ($op->targ == OP_LIST) { + my $my_attr = maybe_var_attr($self, $op, $cx); + return $my_attr if defined $my_attr; + } + + if (class($op) eq "OP") { + # old value is lost + return $self->{'ex_const'} if $op->targ == OP_CONST; + } elsif (class ($op) eq "COP") { + return &pp_nextstate; + } elsif ($op->first->name eq 'pushmark' + or $op->first->name eq 'null' + && $op->first->targ == OP_PUSHMARK + && _op_is_or_was($op, OP_LIST)) { + return $self->pp_list($op, $cx); + } elsif ($op->first->name eq "enter") { + return $self->pp_leave($op, $cx); + } elsif ($op->first->name eq "leave") { + return $self->pp_leave($op->first, $cx); + } elsif ($op->first->name eq "scope") { + return $self->pp_scope($op->first, $cx); + } elsif ($op->targ == OP_STRINGIFY) { + return $self->dquote($op, $cx); + } elsif ($op->targ == OP_GLOB) { + return $self->pp_glob( + $op->first # entersub + ->first # ex-list + ->first # pushmark + ->sibling, # glob + $cx + ); + } elsif (!null($op->first->sibling) and + $op->first->sibling->name eq "readline" and + $op->first->sibling->flags & OPf_STACKED) { + return $self->maybe_parens($self->deparse($op->first, 7) . " = " + . $self->deparse($op->first->sibling, 7), + $cx, 7); + } elsif (!null($op->first->sibling) and + $op->first->sibling->name =~ /^transr?\z/ and + $op->first->sibling->flags & OPf_STACKED) { + my $lhs = $self->deparse($op->first, 20); + $lhs = "($lhs)" + if $op->first->name eq 'not' + and $op->first->flags & OPf_PARENS + and $lhs !~ /\(/; + return $self->maybe_parens( "$lhs =~ " + . $self->deparse($op->first->sibling, 20), + $cx, 20); + } elsif ($op->flags & OPf_SPECIAL && $cx < 1 && !$op->targ) { + return ($self->lex_in_scope("&do") ? "CORE::do" : "do") + . " {\n\t". $self->deparse($op->first, $cx) ."\n\b};"; + } elsif (!null($op->first->sibling) and + $op->first->sibling->name eq "null" and + class($op->first->sibling) eq "UNOP" and + $op->first->sibling->first->flags & OPf_STACKED and + $op->first->sibling->first->name eq "rcatline") { + return $self->maybe_parens($self->deparse($op->first, 18) . " .= " + . $self->deparse($op->first->sibling, 18), + $cx, 18); + } else { + return $self->deparse($op->first, $cx); + } +} + +sub padname { + my $self = shift; + my $targ = shift; + return $self->padname_sv($targ)->PVX; +} + +sub padany { + my $self = shift; + my $op = shift; + return substr($self->padname($op->targ), 1); # skip $/@/% +} + +sub pp_padsv { + my $self = shift; + my($op, $cx, $forbid_parens) = @_; + my $targ = $op->targ; + return $self->maybe_my($op, $cx, $self->padname($targ), + $self->padname_sv($targ), + $forbid_parens); +} + +sub pp_padav { pp_padsv(@_) } + +# prepend 'keys' where its been optimised away, with suitable handling +# of CORE:: and parens + +sub add_keys_keyword { + my ($self, $str, $cx) = @_; + $str = $self->maybe_parens($str, $cx, 16); + # 'keys %h' versus 'keys(%h)' + $str = " $str" unless $str =~ /^\(/; + return $self->keyword("keys") . $str; +} + +sub pp_padhv { + my ($self, $op, $cx) = @_; + my $str = pp_padsv(@_); + # with OPpPADHV_ISKEYS the keys op is optimised away, except + # in scalar context the old op is kept (but not executed) so its targ + # can be used. + if ( ($op->private & OPpPADHV_ISKEYS) + && !(($op->flags & OPf_WANT) == OPf_WANT_SCALAR)) + { + $str = $self->add_keys_keyword($str, $cx); + } + $str; +} + +sub gv_or_padgv { + my $self = shift; + my $op = shift; + if (class($op) eq "PADOP") { + return $self->padval($op->padix); + } else { # class($op) eq "SVOP" + return $op->gv; + } +} + +sub pp_gvsv { + my $self = shift; + my($op, $cx) = @_; + my $gv = $self->gv_or_padgv($op); + return $self->maybe_local($op, $cx, $self->stash_variable("\$", + $self->gv_name($gv), $cx)); +} + +sub pp_gv { + my $self = shift; + my($op, $cx) = @_; + my $gv = $self->gv_or_padgv($op); + return $self->maybe_qualify("", $self->gv_name($gv)); +} + +sub pp_aelemfastlex_store { + my $self = shift; + my($op, $cx) = @_; + my $name = $self->padname($op->targ); + $name =~ s/^@/\$/; + my $i = $op->private; + $i -= 256 if $i > 127; + my $val = $self->deparse($op->first, 7); + return $self->maybe_parens("${name}[$i] = $val", $cx, 7); +} + +sub pp_aelemfast_lex { + my $self = shift; + my($op, $cx) = @_; + my $name = $self->padname($op->targ); + $name =~ s/^@/\$/; + my $i = $op->private; + $i -= 256 if $i > 127; + return $name . "[$i]"; +} + +sub pp_aelemfast { + my $self = shift; + my($op, $cx) = @_; + # optimised PADAV, pre 5.15 + return $self->pp_aelemfast_lex(@_) if ($op->flags & OPf_SPECIAL); + + my $gv = $self->gv_or_padgv($op); + my($name,$quoted) = $self->stash_variable_name('@',$gv); + $name = $quoted ? "$name->" : '$' . $name; + my $i = $op->private; + $i -= 256 if $i > 127; + return $name . "[$i]"; +} + +sub rv2x { + my $self = shift; + my($op, $cx, $type) = @_; + + if (class($op) eq 'NULL' || !$op->can("first")) { + carp("Unexpected op in pp_rv2x"); + return 'XXX'; + } + my $kid = $op->first; + if ($kid->name eq "gv") { + return $self->stash_variable($type, + $self->gv_name($self->gv_or_padgv($kid)), $cx); + } elsif (is_scalar $kid) { + my $str = $self->deparse($kid, 0); + if ($str =~ /^\$([^\w\d])\z/) { + # "$$+" isn't a legal way to write the scalar dereference + # of $+, since the lexer can't tell you aren't trying to + # do something like "$$ + 1" to get one more than your + # PID. Either "${$+}" or "$${+}" are workable + # disambiguations, but if the programmer did the former, + # they'd be in the "else" clause below rather than here. + # It's not clear if this should somehow be unified with + # the code in dq and re_dq that also adds lexer + # disambiguation braces. + $str = '$' . "{$1}"; #' + } + return $type . $str; + } else { + return $type . "{" . $self->deparse($kid, 0) . "}"; + } +} + +sub pp_rv2sv { maybe_local(@_, rv2x(@_, "\$")) } +sub pp_rv2gv { maybe_local(@_, rv2x(@_, "*")) } + +sub pp_rv2hv { + my ($self, $op, $cx) = @_; + my $str = rv2x(@_, "%"); + if ($op->private & OPpRV2HV_ISKEYS) { + $str = $self->add_keys_keyword($str, $cx); + } + return maybe_local(@_, $str); +} + +# skip rv2av +sub pp_av2arylen { + my $self = shift; + my($op, $cx) = @_; + my $kid = $op->first; + if ($kid->name eq "padav") { + return $self->maybe_local($op, $cx, '$#' . $self->padany($kid)); + } else { + my $kkid; + if ( $kid->name eq "rv2av" + && ($kkid = $kid->first) + && $kkid->name !~ /^(scope|leave|gv)$/) + { + # handle (expr)->$#* postfix form + my $expr; + $expr = $self->deparse($kkid, 24); # 24 is '->' + $expr = "$expr->\$#*"; + # XXX maybe_local is probably wrong here: local($#-expression) + # doesn't "do" local (the is no INTRO flag set) + return $self->maybe_local($op, $cx, $expr); + } + else { + # handle $#{expr} form + # XXX see maybe_local comment above + return $self->maybe_local($op, $cx, $self->rv2x($kid, $cx, '$#')); + } + } +} + +# skip down to the old, ex-rv2cv +sub pp_rv2cv { + my ($self, $op, $cx) = @_; + if (!null($op->first) && $op->first->name eq 'null' && + $op->first->targ == OP_LIST) + { + return $self->rv2x($op->first->first->sibling, $cx, "&") + } + else { + return $self->rv2x($op, $cx, "") + } +} + +sub list_const { + my $self = shift; + my($cx, @list) = @_; + my @a = map $self->const($_, 6), @list; + if (@a == 0) { + return "()"; + } elsif (@a == 1) { + return $a[0]; + } elsif ( @a > 2 and !grep(!/^-?\d+$/, @a)) { + # collapse (-1,0,1,2) into (-1..2) + my ($s, $e) = @a[0,-1]; + my $i = $s; + return $self->maybe_parens("$s..$e", $cx, 9) + unless grep $i++ != $_, @a; + } + return $self->maybe_parens(join(", ", @a), $cx, 6); +} + +sub pp_rv2av { + my $self = shift; + my($op, $cx) = @_; + my $kid = $op->first; + if ($kid->name eq "const") { # constant list + my $av = $self->const_sv($kid); + return $self->list_const($cx, $av->ARRAY); + } else { + return $self->maybe_local($op, $cx, $self->rv2x($op, $cx, "\@")); + } + } + +sub is_subscriptable { + my $op = shift; + if ($op->name =~ /^([ahg]elem|multideref$)/) { + return 1; + } elsif ($op->name eq "entersub") { + my $kid = $op->first; + return 0 unless null $kid->sibling; + $kid = $kid->first; + $kid = $kid->sibling until null $kid->sibling; + return 0 if is_scope($kid); + $kid = $kid->first; + return 0 if $kid->name eq "gv" || $kid->name eq "padcv"; + return 0 if is_scalar($kid); + return is_subscriptable($kid); + } else { + return 0; + } +} + +sub elem_or_slice_array_name +{ + my $self = shift; + my ($array, $left, $padname, $allow_arrow) = @_; + + if ($array->name eq $padname) { + return $self->padany($array); + } elsif (is_scope($array)) { # ${expr}[0] + return "{" . $self->deparse($array, 0) . "}"; + } elsif ($array->name eq "gv") { + ($array, my $quoted) = + $self->stash_variable_name( + $left eq '[' ? '@' : '%', $self->gv_or_padgv($array) + ); + if (!$allow_arrow && $quoted) { + # This cannot happen. + die "Invalid variable name $array for slice"; + } + return $quoted ? "$array->" : $array; + } elsif (!$allow_arrow || is_scalar $array) { # $x[0], $$x[0], ... + return $self->deparse($array, 24); + } else { + return undef; + } +} + +sub elem_or_slice_single_index +{ + my $self = shift; + my ($idx) = @_; + + $idx = $self->deparse($idx, 1); + + # Outer parens in an array index will confuse perl + # if we're interpolating in a regular expression, i.e. + # /$x$foo[(-1)]/ is *not* the same as /$x$foo[-1]/ + # + # If $self->{parens}, then an initial '(' will + # definitely be paired with a final ')'. If + # !$self->{parens}, the misleading parens won't + # have been added in the first place. + # + # [You might think that we could get "(...)...(...)" + # where the initial and final parens do not match + # each other. But we can't, because the above would + # only happen if there's an infix binop between the + # two pairs of parens, and *that* means that the whole + # expression would be parenthesized as well.] + # + $idx =~ s/^\((.*)\)$/$1/ if $self->{'parens'}; + + # Hash-element braces will autoquote a bareword inside themselves. + # We need to make sure that C<$hash{warn()}> doesn't come out as + # C<$hash{warn}>, which has a quite different meaning. Currently + # B::Deparse will always quote strings, even if the string was a + # bareword in the original (i.e. the OPpCONST_BARE flag is ignored + # for constant strings.) So we can cheat slightly here - if we see + # a bareword, we know that it is supposed to be a function call. + # + $idx =~ s/^([A-Za-z_]\w*)$/$1()/; + + return $idx; +} + +sub elem { + my $self = shift; + my ($op, $cx, $left, $right, $padname) = @_; + my($array, $idx) = ($op->first, $op->first->sibling); + + $idx = $self->elem_or_slice_single_index($idx); + + unless ($array->name eq $padname) { # Maybe this has been fixed + $array = $array->first; # skip rv2av (or ex-rv2av in _53+) + } + if (my $array_name=$self->elem_or_slice_array_name + ($array, $left, $padname, 1)) { + return ($array_name =~ /->\z/ + ? $array_name + : $array_name eq '#' ? '${#}' : "\$" . $array_name) + . $left . $idx . $right; + } else { + # $x[20][3]{hi} or expr->[20] + my $arrow = is_subscriptable($array) ? "" : "->"; + return $self->deparse($array, 24) . $arrow . $left . $idx . $right; + } + +} + +# a simplified version of elem_or_slice_array_name() +# for the use of pp_multideref + +sub multideref_var_name { + my $self = shift; + my ($gv, $is_hash) = @_; + + my ($name, $quoted) = + $self->stash_variable_name( $is_hash ? '%' : '@', $gv); + return $quoted ? "$name->" + : $name eq '#' + ? '${#}' # avoid ${#}[1] => $#[1] + : '$' . $name; +} + + +# deparse an OP_MULTICONCAT. If $in_dq is 1, we're within +# a double-quoted string, so for example. +# "abc\Qdef$x\Ebar" +# might get compiled as +# multiconcat("abc", metaquote(multiconcat("def", $x)), "bar") +# and the inner multiconcat should be deparsed as C rather than +# the normal C +# Ditto if $in_dq is 2, handle qr/...\Qdef$x\E.../. + +sub do_multiconcat { + my $self = shift; + my($op, $cx, $in_dq) = @_; + + my $kid; + my @kids; + my $assign; + my $append; + my $lhs = ""; + + for ($kid = $op->first; !null $kid; $kid = $kid->sibling) { + # skip the consts and/or padsv we've optimised away + push @kids, $kid + unless $kid->type == OP_NULL + && ( $kid->targ == OP_PADSV + || $kid->targ == OP_CONST + || $kid->targ == OP_PUSHMARK); + } + + $append = ($op->private & OPpMULTICONCAT_APPEND); + + if ($op->private & OPpTARGET_MY) { + # '$lex = ...' or '$lex .= ....' or 'my $lex = ' + $lhs = $self->padname($op->targ); + $lhs = "my $lhs" if ($op->private & OPpLVAL_INTRO); + $assign = 1; + } + elsif ($op->flags & OPf_STACKED) { + # 'expr = ...' or 'expr .= ....' + my $expr = $append ? shift(@kids) : pop(@kids); + $lhs = $self->deparse($expr, 7); + $assign = 1; + } + + if ($assign) { + $lhs .= $append ? ' .= ' : ' = '; + } + + my ($nargs, $const_str, @const_lens) = $op->aux_list($self->{curcv}); + + my @consts; + my $i = 0; + for (@const_lens) { + if ($_ == -1) { + push @consts, undef; + } + else { + push @consts, substr($const_str, $i, $_); + my @args; + $i += $_; + } + } + + my $rhs = ""; + + if ( $in_dq + || (($op->private & OPpMULTICONCAT_STRINGIFY) && !$self->{'unquote'})) + { + # "foo=$foo bar=$bar " + my $not_first; + while (@consts) { + if ($not_first) { + my $s = $self->dq(shift(@kids), 18); + # don't deparse "a${$}b" as "a$$b" + $s = '${$}' if $s eq '$$'; + $rhs = dq_disambiguate($rhs, $s); + } + $not_first = 1; + my $c = shift @consts; + if (defined $c) { + if ($in_dq == 2) { + # in pattern: don't convert newline to '\n' etc etc + my $s = re_uninterp(escape_re(re_unback($c))); + $rhs = re_dq_disambiguate($rhs, $s) + } + else { + my $s = uninterp(escape_str(unback($c))); + $rhs = dq_disambiguate($rhs, $s) + } + } + } + return $rhs if $in_dq; + $rhs = single_delim("qq", '"', $rhs, $self); + } + elsif ($op->private & OPpMULTICONCAT_FAKE) { + # sprintf("foo=%s bar=%s ", $foo, $bar) + + my @all; + @consts = map { $_ //= ''; s/%/%%/g; $_ } @consts; + my $fmt = join '%s', @consts; + push @all, $self->quoted_const_str($fmt); + + # the following is a stripped down copy of sub listop {} + my $parens = $assign || ($cx >= 5) || $self->{'parens'}; + my $fullname = $self->keyword('sprintf'); + push @all, map $self->deparse($_, 6), @kids; + + $rhs = $parens + ? "$fullname(" . join(", ", @all) . ")" + : "$fullname " . join(", ", @all); + } + else { + # "foo=" . $foo . " bar=" . $bar + my @all; + my $not_first; + while (@consts) { + push @all, $self->deparse(shift(@kids), 18) if $not_first; + $not_first = 1; + my $c = shift @consts; + if (defined $c) { + push @all, $self->quoted_const_str($c); + } + } + $rhs .= join ' . ', @all; + } + + my $text = $lhs . $rhs; + + $text = "($text)" if ($cx >= (($assign) ? 7 : 18+1)) + || $self->{'parens'}; + + return $text; +} + + +sub pp_multiconcat { + my $self = shift; + $self->do_multiconcat(@_, 0); +} + + +sub pp_multideref { + my $self = shift; + my($op, $cx) = @_; + my $text = ""; + + if ($op->private & OPpMULTIDEREF_EXISTS) { + $text = $self->keyword("exists"). " "; + } + elsif ($op->private & OPpMULTIDEREF_DELETE) { + $text = $self->keyword("delete"). " "; + } + elsif ($op->private & OPpLVAL_INTRO) { + $text = $self->keyword("local"). " "; + } + + if ($op->first && ($op->first->flags & OPf_KIDS)) { + # arbitrary initial expression, e.g. f(1,2,3)->[...] + my $expr = $self->deparse($op->first, 24); + # stop "exists (expr)->{...}" being interpreted as + #"(exists (expr))->{...}" + $expr = "+$expr" if $expr =~ /^\(/; + $text .= $expr; + } + + my @items = $op->aux_list($self->{curcv}); + my $actions = shift @items; + + my $is_hash; + my $derefs = 0; + + while (1) { + if (($actions & MDEREF_ACTION_MASK) == MDEREF_reload) { + $actions = shift @items; + next; + } + + $is_hash = ( + ($actions & MDEREF_ACTION_MASK) == MDEREF_HV_pop_rv2hv_helem + || ($actions & MDEREF_ACTION_MASK) == MDEREF_HV_gvsv_vivify_rv2hv_helem + || ($actions & MDEREF_ACTION_MASK) == MDEREF_HV_padsv_vivify_rv2hv_helem + || ($actions & MDEREF_ACTION_MASK) == MDEREF_HV_vivify_rv2hv_helem + || ($actions & MDEREF_ACTION_MASK) == MDEREF_HV_padhv_helem + || ($actions & MDEREF_ACTION_MASK) == MDEREF_HV_gvhv_helem + ); + + if ( ($actions & MDEREF_ACTION_MASK) == MDEREF_AV_padav_aelem + || ($actions & MDEREF_ACTION_MASK) == MDEREF_HV_padhv_helem) + { + $derefs = 1; + $text .= '$' . substr($self->padname(shift @items), 1); + } + elsif ( ($actions & MDEREF_ACTION_MASK) == MDEREF_AV_gvav_aelem + || ($actions & MDEREF_ACTION_MASK) == MDEREF_HV_gvhv_helem) + { + $derefs = 1; + $text .= $self->multideref_var_name(shift @items, $is_hash); + } + else { + if ( ($actions & MDEREF_ACTION_MASK) == + MDEREF_AV_padsv_vivify_rv2av_aelem + || ($actions & MDEREF_ACTION_MASK) == + MDEREF_HV_padsv_vivify_rv2hv_helem) + { + $text .= $self->padname(shift @items); + } + elsif ( ($actions & MDEREF_ACTION_MASK) == + MDEREF_AV_gvsv_vivify_rv2av_aelem + || ($actions & MDEREF_ACTION_MASK) == + MDEREF_HV_gvsv_vivify_rv2hv_helem) + { + $text .= $self->multideref_var_name(shift @items, $is_hash); + } + elsif ( ($actions & MDEREF_ACTION_MASK) == + MDEREF_AV_pop_rv2av_aelem + || ($actions & MDEREF_ACTION_MASK) == + MDEREF_HV_pop_rv2hv_helem) + { + if ( ($op->flags & OPf_KIDS) + && ( _op_is_or_was($op->first, OP_RV2AV) + || _op_is_or_was($op->first, OP_RV2HV)) + && ($op->first->flags & OPf_KIDS) + && ( _op_is_or_was($op->first->first, OP_AELEM) + || _op_is_or_was($op->first->first, OP_HELEM)) + ) + { + $derefs++; + } + } + + $text .= '->' if !$derefs++; + } + + + if (($actions & MDEREF_INDEX_MASK) == MDEREF_INDEX_none) { + last; + } + + $text .= $is_hash ? '{' : '['; + + if (($actions & MDEREF_INDEX_MASK) == MDEREF_INDEX_const) { + my $key = shift @items; + if ($is_hash) { + $text .= $self->const($key, $cx); + } + else { + $text .= $key; + } + } + elsif (($actions & MDEREF_INDEX_MASK) == MDEREF_INDEX_padsv) { + $text .= $self->padname(shift @items); + } + elsif (($actions & MDEREF_INDEX_MASK) == MDEREF_INDEX_gvsv) { + $text .= '$' . ($self->stash_variable_name('$', shift @items))[0]; + } + + $text .= $is_hash ? '}' : ']'; + + if ($actions & MDEREF_FLAG_last) { + last; + } + $actions >>= MDEREF_SHIFT; + } + + return $text; +} + + +sub pp_aelem { maybe_local(@_, elem(@_, "[", "]", "padav")) } +sub pp_helem { maybe_local(@_, elem(@_, "{", "}", "padhv")) } + +sub pp_gelem { + my $self = shift; + my($op, $cx) = @_; + my($glob, $part) = ($op->first, $op->last); + $glob = $glob->first; # skip rv2gv + $glob = $glob->first if $glob->name eq "rv2gv"; # this one's a bug + my $scope = is_scope($glob); + $glob = $self->deparse($glob, 0); + $part = $self->deparse($part, 1); + $glob =~ s/::\z// unless $scope; + return "*" . ($scope ? "{$glob}" : $glob) . "{$part}"; +} + +sub slice { + my $self = shift; + my ($op, $cx, $left, $right, $regname, $padname) = @_; + my $last; + my(@elems, $kid, $array, $list); + if (class($op) eq "LISTOP") { + $last = $op->last; + } else { # ex-hslice inside delete() + for ($kid = $op->first; !null $kid->sibling; $kid = $kid->sibling) {} + $last = $kid; + } + $array = $last; + $array = $array->first + if $array->name eq $regname or $array->name eq "null"; + $array = $self->elem_or_slice_array_name($array,$left,$padname,0); + $kid = $op->first->sibling; # skip pushmark + if ($kid->name eq "list") { + $kid = $kid->first->sibling; # skip list, pushmark + for (; !null $kid; $kid = $kid->sibling) { + push @elems, $self->deparse($kid, 6); + } + $list = join(", ", @elems); + } else { + $list = $self->elem_or_slice_single_index($kid); + } + my $lead = ( _op_is_or_was($op, OP_KVHSLICE) + || _op_is_or_was($op, OP_KVASLICE)) + ? '%' : '@'; + return $lead . $array . $left . $list . $right; +} + +sub pp_aslice { maybe_local(@_, slice(@_, "[", "]", "rv2av", "padav")) } +sub pp_kvaslice { slice(@_, "[", "]", "rv2av", "padav") } +sub pp_hslice { maybe_local(@_, slice(@_, "{", "}", "rv2hv", "padhv")) } +sub pp_kvhslice { slice(@_, "{", "}", "rv2hv", "padhv") } + +sub pp_lslice { + my $self = shift; + my($op, $cx) = @_; + my $idx = $op->first; + my $list = $op->last; + my(@elems, $kid); + $list = $self->deparse($list, 1); + $idx = $self->deparse($idx, 1); + return "($list)" . "[$idx]"; +} + +sub want_scalar { + my $op = shift; + return ($op->flags & OPf_WANT) == OPf_WANT_SCALAR; +} + +sub want_list { + my $op = shift; + return ($op->flags & OPf_WANT) == OPf_WANT_LIST; +} + +sub _method { + my $self = shift; + my($op, $cx) = @_; + my $kid = $op->first->sibling; # skip pushmark + my($meth, $obj, @exprs); + if ($kid->name eq "list" and want_list $kid) { + # When an indirect object isn't a bareword but the args are in + # parens, the parens aren't part of the method syntax (the LLAFR + # doesn't apply), but they make a list with OPf_PARENS set that + # doesn't get flattened by the append_elem that adds the method, + # making a (object, arg1, arg2, ...) list where the object + # usually is. This can be distinguished from + # '($obj, $arg1, $arg2)->meth()' (which is legal if $arg2 is an + # object) because in the later the list is in scalar context + # as the left side of -> always is, while in the former + # the list is in list context as method arguments always are. + # (Good thing there aren't method prototypes!) + $meth = $kid->sibling; + $kid = $kid->first->sibling; # skip pushmark + $obj = $kid; + $kid = $kid->sibling; + for (; not null $kid; $kid = $kid->sibling) { + push @exprs, $kid; + } + } else { + $obj = $kid; + $kid = $kid->sibling; + for (; !null ($kid->sibling) && $kid->name!~/^method(?:_named)?\z/; + $kid = $kid->sibling) { + push @exprs, $kid + } + $meth = $kid; + } + + if ($meth->name eq "method_named") { + $meth = $self->meth_sv($meth)->PV; + } elsif ($meth->name eq "method_super") { + $meth = "SUPER::".$self->meth_sv($meth)->PV; + } elsif ($meth->name eq "method_redir") { + $meth = $self->meth_rclass_sv($meth)->PV.'::'.$self->meth_sv($meth)->PV; + } elsif ($meth->name eq "method_redir_super") { + $meth = $self->meth_rclass_sv($meth)->PV.'::SUPER::'. + $self->meth_sv($meth)->PV; + } else { + $meth = $meth->first; + if ($meth->name eq "const") { + # As of 5.005_58, this case is probably obsoleted by the + # method_named case above + $meth = $self->const_sv($meth)->PV; # needs to be bare + } + } + + return { method => $meth, variable_method => ref($meth), + object => $obj, args => \@exprs }, + $cx; +} + +# compat function only +sub method { + my $self = shift; + my $info = $self->_method(@_); + return $self->e_method( $self->_method(@_) ); +} + +sub e_method { + my ($self, $info, $cx) = @_; + my $obj = $self->deparse($info->{object}, 24); + + my $meth = $info->{method}; + $meth = $self->deparse($meth, 1) if $info->{variable_method}; + my $args = join(", ", map { $self->deparse($_, 6) } @{$info->{args}} ); + if ($info->{object}->name eq 'scope' && want_list $info->{object}) { + # method { $object } + # This must be deparsed this way to preserve list context + # of $object. + my $need_paren = $cx >= 6; + return '(' x $need_paren + . $meth . substr($obj,2) # chop off the "do" + . " $args" + . ')' x $need_paren; + } + my $kid = $obj . "->" . $meth; + if (length $args) { + return $kid . "(" . $args . ")"; # parens mandatory + } else { + return $kid; + } +} + +# returns "&" if the prototype doesn't match the args, +# or ("", $args_after_prototype_demunging) if it does. +sub check_proto { + my $self = shift; + return "&" if $self->{'noproto'}; + my ($proto, @args) = @_; + my $doneok = 0; + my @reals; + $proto =~ s/^\s+//; + while (length $proto) { + $proto =~ s/^(\\?[\$\@&%*]|\\\[[\$\@&%*]+\]|[_+;])\s*// + or return "&"; # malformed prototype + my $chr = $1; + if ($chr eq ";") { + $doneok = 1; + } elsif ($chr eq '@' or $chr eq '%') { + # An unbackslashed @ or % gobbles up the rest of the args + push @reals, map($self->deparse($_, 6), @args); + @args = (); + $proto = ''; + } elsif (!@args) { + last if $doneok; + return "&"; # too few args and no ';' + } else { + my $arg = shift @args; + if ($chr eq '$' || $chr eq '_') { + if (want_scalar $arg) { + push @reals, $self->deparse($arg, 6); + } else { + return "&"; + } + } elsif ($chr eq "&") { + if ($arg->name =~ /^(?:s?refgen|undef)\z/) { + push @reals, $self->deparse($arg, 6); + } else { + return "&"; + } + } elsif ($chr eq "*") { + if ($arg->name =~ /^s?refgen\z/ + and $arg->first->first->name eq "rv2gv") + { + my $real = $arg->first->first; # skip refgen, null + if ($real->first->name eq "gv") { + push @reals, $self->deparse($real, 6); + } else { + push @reals, $self->deparse($real->first, 6); + } + } else { + return "&"; + } + } elsif ($chr eq "+") { + my $real; + if ($arg->name =~ /^s?refgen\z/ and + !null($real = $arg->first) and + !null($real->first) and + $real->first->name =~ /^(?:rv2|pad)[ah]v\z/) + { + push @reals, $self->deparse($real, 6); + } elsif (want_scalar $arg) { + push @reals, $self->deparse($arg, 6); + } else { + return "&"; + } + } elsif (substr($chr, 0, 1) eq "\\") { + $chr =~ tr/\\[]//d; + my $real; + if ($arg->name =~ /^s?refgen\z/ and + !null($real = $arg->first) and + ($chr =~ /\$/ && is_scalar($real->first) + or ($chr =~ /@/ + && !null($real->first) + && $real->first->name =~ /^(?:rv2|pad)av\z/) + or ($chr =~ /%/ + && !null($real->first) + && $real->first->name =~ /^(?:rv2|pad)hv\z/) + #or ($chr =~ /&/ # This doesn't work + # && $real->first->name eq "rv2cv") + or ($chr =~ /\*/ + && $real->first->name eq "rv2gv"))) + { + push @reals, $self->deparse($real, 6); + } else { + return "&"; + } + } else { + # should not happen + return "&"; + } + } + } + return "&" if @args; # too many args + return ("", join ", ", @reals); +} + +sub retscalar { + my $name = $_[0]->name; + # XXX There has to be a better way of doing this scalar-op check. + # Currently PL_opargs is not exposed. + if ($name eq 'null') { + $name = substr B::ppname($_[0]->targ), 3 + } + $name =~ /^(?:scalar|pushmark|wantarray|const|gvsv|gv|padsv|rv2gv + |rv2sv|av2arylen|anoncode|prototype|srefgen|ref|bless + |regcmaybe|regcreset|regcomp|qr|subst|substcont|trans + |transr|sassign|chop|schop|chomp|schomp|defined|undef + |study|pos|preinc|i_preinc|predec|i_predec|postinc + |i_postinc|postdec|i_postdec|pow|multiply|i_multiply + |divide|i_divide|modulo|i_modulo|add|i_add|subtract + |i_subtract|concat|multiconcat|stringify|left_shift|right_shift|lt + |i_lt|gt|i_gt|le|i_le|ge|i_ge|eq|i_eq|ne|i_ne|ncmp|i_ncmp + |slt|sgt|sle|sge|seq|sne|scmp|[sn]?bit_(?:and|x?or)|negate + |i_negate|not|[sn]?complement|smartmatch|atan2|sin|cos + |rand|srand|exp|log|sqrt|int|hex|oct|abs|length|substr + |vec|index|rindex|sprintf|formline|ord|chr|crypt|ucfirst + |lcfirst|uc|lc|quotemeta|aelemfast|aelem|exists|helem + |pack|join|anonlist|anonhash|push|pop|shift|unshift|xor + |andassign|orassign|dorassign|warn|die|reset|nextstate + |dbstate|unstack|last|next|redo|dump|goto|exit|open|close + |pipe_op|fileno|umask|binmode|tie|untie|tied|dbmopen + |dbmclose|select|getc|read|enterwrite|prtf|print|say + |sysopen|sysseek|sysread|syswrite|eof|tell|seek|truncate + |fcntl|ioctl|flock|send|recv|socket|sockpair|bind|connect + |listen|accept|shutdown|gsockopt|ssockopt|getsockname + |getpeername|ftrread|ftrwrite|ftrexec|fteread|ftewrite + |fteexec|ftis|ftsize|ftmtime|ftatime|ftctime|ftrowned + |fteowned|ftzero|ftsock|ftchr|ftblk|ftfile|ftdir|ftpipe + |ftsuid|ftsgid|ftsvtx|ftlink|fttty|fttext|ftbinary|chdir + |chown|chroot|unlink|chmod|utime|rename|link|symlink + |readlink|mkdir|rmdir|open_dir|telldir|seekdir|rewinddir + |closedir|fork|wait|waitpid|system|exec|kill|getppid + |getpgrp|setpgrp|getpriority|setpriority|time|alarm|sleep + |shmget|shmctl|shmread|shmwrite|msgget|msgctl|msgsnd + |msgrcv|semop|semget|semctl|hintseval|shostent|snetent + |sprotoent|sservent|ehostent|enetent|eprotoent|eservent + |spwent|epwent|sgrent|egrent|getlogin|syscall|lock|runcv + |fc|padsv_store)\z/x +} + +sub pp_entersub { + my $self = shift; + my($op, $cx) = @_; + return $self->e_method($self->_method($op, $cx)) + unless null $op->first->sibling; + my $prefix = ""; + my $amper = ""; + my($kid, @exprs); + if ($op->private & OPpENTERSUB_AMPER) { + $amper = "&"; + } + $kid = $op->first; + $kid = $kid->first->sibling; # skip ex-list, pushmark + for (; not null $kid->sibling; $kid = $kid->sibling) { + push @exprs, $kid; + } + my $simple = 0; + my $proto = undef; + my $lexical; + if (is_scope($kid)) { + $amper = "&"; + $kid = "{" . $self->deparse($kid, 0) . "}"; + } elsif ($kid->first->name eq "gv") { + my $gv = $self->gv_or_padgv($kid->first); + my $cv; + if (class($gv) eq 'GV' && class($cv = $gv->CV) ne "SPECIAL" + || $gv->FLAGS & SVf_ROK && class($cv = $gv->RV) eq 'CV') { + $proto = $cv->PV if $cv->FLAGS & SVf_POK; + } + $simple = 1; # only calls of named functions can be prototyped + $kid = $self->maybe_qualify("!", $self->gv_name($gv)); + my $fq; + # Fully qualify any sub name that conflicts with a lexical. + if ($self->lex_in_scope("&$kid") + || $self->lex_in_scope("&$kid", 1)) + { + $fq++; + } elsif (!$amper) { + if ($kid eq 'main::') { + $kid = '::'; + } + else { + if ($kid !~ /::/ && $kid ne 'x') { + # Fully qualify any sub name that is also a keyword. While + # we could check the import flag, we cannot guarantee that + # the code deparsed so far would set that flag, so we qual- + # ify the names regardless of importation. + if (exists $feature_keywords{$kid}) { + $fq++ if $self->feature_enabled($kid); + } elsif (do { local $@; local $SIG{__DIE__}; + eval { () = prototype "CORE::$kid"; 1 } }) { + $fq++ + } + } + if ($kid !~ /^(?:\w|::)(?:[\w\d]|::(?!\z))*\z/) { + $kid = single_delim("q", "'", $kid, $self) . '->'; + } + } + } + $fq and substr $kid, 0, 0, = $self->{'curstash'}.'::'; + } elsif (is_scalar ($kid->first) && $kid->first->name ne 'rv2cv') { + $amper = "&"; + $kid = $self->deparse($kid, 24); + } else { + $prefix = ""; + my $grandkid = $kid->first; + my $arrow = ($lexical = $grandkid->name eq "padcv") + || is_subscriptable($grandkid) + ? "" + : "->"; + $kid = $self->deparse($kid, 24) . $arrow; + if ($lexical) { + my $padlist = $self->{'curcv'}->PADLIST; + my $padoff = $grandkid->targ; + my $padname = $padlist->ARRAYelt(0)->ARRAYelt($padoff); + my $protocv = $padname->FLAGS & SVpad_STATE + ? $padlist->ARRAYelt(1)->ARRAYelt($padoff) + : $padname->PROTOCV; + if ($protocv->FLAGS & SVf_POK) { + $proto = $protocv->PV + } + $simple = 1; + } + } + + # Doesn't matter how many prototypes there are, if + # they haven't happened yet! + my $declared = $lexical || exists $self->{'subs_declared'}{$kid}; + if (not $declared and $self->{'in_coderef2text'}) { + no strict 'refs'; + no warnings 'uninitialized'; + $declared = + ( + defined &{ ${$self->{'curstash'}."::"}{$kid} } + && !exists + $self->{'subs_deparsed'}{$self->{'curstash'}."::".$kid} + && defined prototype $self->{'curstash'}."::".$kid + ); + } + if (!$declared && defined($proto)) { + # Avoid "too early to check prototype" warning + ($amper, $proto) = ('&'); + } + + my $args; + my $listargs = 1; + if ($declared and defined $proto and not $amper) { + ($amper, $args) = $self->check_proto($proto, @exprs); + $listargs = $amper; + } + if ($listargs) { + $args = join(", ", map( + ($_->flags & OPf_WANT) == OPf_WANT_SCALAR + && !retscalar($_) + ? $self->maybe_parens_unop('scalar', $_, 6) + : $self->deparse($_, 6), + @exprs + )); + } + if ($prefix or $amper) { + if ($kid eq '&') { $kid = "{$kid}" } # &{&} cannot be written as && + if ($op->flags & OPf_STACKED) { + return $prefix . $amper . $kid . "(" . $args . ")"; + } else { + return $prefix . $amper. $kid; + } + } else { + # It's a syntax error to call CORE::GLOBAL::foo with a prefix, + # so it must have been translated from a keyword call. Translate + # it back. + $kid =~ s/^CORE::GLOBAL:://; + + if (!$declared) { + return "$kid(" . $args . ")"; + } + + my $dproto = defined($proto) ? $proto : "undefined"; + if ($dproto =~ /^\s*\z/) { + return $kid; + } + + my $scalar_proto = $dproto =~ /^ \s* (?: ;\s* )* (?: [\$*_+] |\\ \s* (?: [\$\@%&*] | \[ [^\]]+ \] ) ) \s* \z/x; + if ($scalar_proto and !@exprs || is_scalar($exprs[0])) { + # is_scalar is an excessively conservative test here: + # really, we should be comparing to the precedence of the + # top operator of $exprs[0] (ala unop()), but that would + # take some major code restructuring to do right. + return $self->maybe_parens_func($kid, $args, $cx, 16); + } elsif (not $scalar_proto and defined($proto) || $simple) { + return $self->maybe_parens_func($kid, $args, $cx, 5); + } else { + return "$kid(" . $args . ")"; + } + } +} + +sub pp_enterwrite { unop(@_, "write") } + +# escape things that cause interpolation in double quotes, +# but not character escapes +sub uninterp { + my($str) = @_; + $str =~ s/(^|\G|[^\\])((?:\\\\)*)([\$\@]|\\[uUlLQE])/$1$2\\$3/g; + return $str; +} + +{ +my $bal; +BEGIN { + use re "eval"; + # Matches any string which is balanced with respect to {braces} + $bal = qr( + (?: + [^\\{}] + | \\\\ + | \\[{}] + | \{(??{$bal})\} + )* + )x; +} + +# the same, but treat $|, $), $( and $ at the end of the string differently +# and leave comments unmangled for the sake of /x and (?x). +sub re_uninterp { + my($str) = @_; + + $str =~ s/ + ( ^|\G # $1 + | [^\\] + ) + + ( # $2 + (?:\\\\)* + ) + + ( # $3 + ( \(\?\??\{$bal\}\) # $4 (skip over (?{}) and (??{}) blocks) + | \#[^\n]* # (skip over comments) + ) + | [\$\@] + (?!\||\)|\(|$|\s) + | \\[uUlLQE] + ) + + /defined($4) && length($4) ? "$1$2$4" : "$1$2\\$3"/xeg; + + return $str; +} +} + +# character escapes, but not delimiters that might need to be escaped +sub escape_str { # ASCII, UTF8 + my($str) = @_; + $str =~ s/(.)/ord($1) > 255 ? sprintf("\\x{%x}", ord($1)) : $1/eg; + $str =~ s/\a/\\a/g; +# $str =~ s/\cH/\\b/g; # \b means something different in a regex; and \cH + # isn't a backspace in EBCDIC + $str =~ s/\t/\\t/g; + $str =~ s/\n/\\n/g; + $str =~ s/\e/\\e/g; + $str =~ s/\f/\\f/g; + $str =~ s/\r/\\r/g; + $str =~ s/([\cA-\cZ])/'\\c' . $unctrl{$1}/ge; + $str =~ s/([[:^print:]])/sprintf("\\%03o", ord($1))/age; + return $str; +} + +# For regexes. Leave whitespace unmangled in case of /x or (?x). +sub escape_re { + my($str) = @_; + $str =~ s/(.)/ord($1) > 255 ? sprintf("\\x{%x}", ord($1)) : $1/eg; + $str =~ s/([[:^print:]])/ + ($1 =~ y! \t\n!!) ? $1 : sprintf("\\%03o", ord($1))/age; + $str =~ s/\n/\n\f/g; + return $str; +} + +# Don't do this for regexen +sub unback { + my($str) = @_; + $str =~ s/\\/\\\\/g; + return $str; +} + +# Remove backslashes which precede literal control characters, +# to avoid creating ambiguity when we escape the latter. +# +# Don't remove a backslash from escaped whitespace: where the T represents +# a literal tab character, /T/x is not equivalent to /\T/x + +sub re_unback { + my($str) = @_; + + # the insane complexity here is due to the behaviour of "\c\" + $str =~ s/ + # these two lines ensure that the backslash we're about to + # remove isn't preceded by something which makes it part + # of a \c + + (^ | [^\\] | \\c\\) # $1 + (?'], ['{','}']) { + ($open, $close) = @$ar; + $fail = 0; $cnt = 0; $last_bs = 0; + for $c (@str) { + if ($c eq $open) { + $fail = 1 if $last_bs; + $cnt++; + } elsif ($c eq $close) { + $fail = 1 if $last_bs; + $cnt--; + if ($cnt < 0) { + # qq()() isn't ")(" + $fail = 1; + last; + } + } + $last_bs = $c eq '\\'; + } + $fail = 1 if $cnt != 0; + return ($open, "$open$str$close") if not $fail; + } + return ("", $str); +} + +sub single_delim { + my($q, $default, $str, $self) = @_; + return "$default$str$default" if $default and index($str, $default) == -1; + my $coreq = $self->keyword($q); # maybe CORE::q + if ($q ne 'qr') { + (my $succeed, $str) = balanced_delim($str); + return "$coreq$str" if $succeed; + } + for my $delim ('/', '"', '#') { + return "$coreq$delim" . $str . $delim if index($str, $delim) == -1; + } + if ($default) { + $str =~ s/$default/\\$default/g; + return "$default$str$default"; + } else { + $str =~ s[/][\\/]g; + return "$coreq/$str/"; + } +} + +my $max_prec; +BEGIN { $max_prec = int(0.999 + 8*length(pack("F", 42))*log(2)/log(10)); } + +# Split a floating point number into an integer mantissa and a binary +# exponent. Assumes you've already made sure the number isn't zero or +# some weird infinity or NaN. +sub split_float { + my($f) = @_; + my $exponent = 0; + if ($f == int($f)) { + while ($f % 2 == 0) { + $f /= 2; + $exponent++; + } + } else { + while ($f != int($f)) { + $f *= 2; + $exponent--; + } + } + my $mantissa = sprintf("%.0f", $f); + return ($mantissa, $exponent); +} + + +# suitably single- or double-quote a literal constant string + +sub quoted_const_str { + my ($self, $str) =@_; + if ($str =~ /[[:^print:]]/a) { + return single_delim("qq", '"', + uninterp(escape_str unback $str), $self); + } else { + return single_delim("q", "'", unback($str), $self); + } +} + + +sub const { + my $self = shift; + my($sv, $cx) = @_; + if ($self->{'use_dumper'}) { + return $self->const_dumper($sv, $cx); + } + if (class($sv) eq "SPECIAL") { + # PL_sv_undef etc + # return yes/no as boolean expressions rather than integers to + # preserve their boolean-ness + return + $$sv == 1 ? 'undef' : # PL_sv_undef + $$sv == 2 ? $self->maybe_parens("!0", $cx, 21) : # PL_sv_yes + $$sv == 3 ? $self->maybe_parens("!1", $cx, 21) : # PL_sv_no + $$sv == 7 ? '0' : # PL_sv_zero + '"???"'; + } + if (class($sv) eq "NULL") { + return 'undef'; + } + # convert a version object into the "v1.2.3" string in its V magic + if ($sv->FLAGS & SVs_RMG) { + for (my $mg = $sv->MAGIC; $mg; $mg = $mg->MOREMAGIC) { + return $mg->PTR if $mg->TYPE eq 'V'; + } + } + + if ($sv->FLAGS & SVf_IOK) { + my $str = $sv->int_value; + $str = $self->maybe_parens($str, $cx, 21) if $str < 0; + return $str; + } elsif ($sv->FLAGS & SVf_NOK) { + my $nv = $sv->NV; + if ($nv == 0) { + if (pack("F", $nv) eq pack("F", 0)) { + # positive zero + return "0.0"; + } else { + # negative zero + return $self->maybe_parens("-0.0", $cx, 21); + } + } elsif (1/$nv == 0) { + if ($nv > 0) { + # positive infinity + return $self->maybe_parens("9**9**9", $cx, 22); + } else { + # negative infinity + return $self->maybe_parens("-9**9**9", $cx, 21); + } + } elsif ($nv != $nv) { + # NaN + if (pack("F", $nv) eq pack("F", sin(9**9**9))) { + # the normal kind + return "sin(9**9**9)"; + } elsif (pack("F", $nv) eq pack("F", -sin(9**9**9))) { + # the inverted kind + return $self->maybe_parens("-sin(9**9**9)", $cx, 21); + } else { + # some other kind + my $hex = unpack("h*", pack("F", $nv)); + return qq'unpack("F", pack("h*", "$hex"))'; + } + } + # first, try the default stringification + my $str = "$nv"; + if ($str != $nv) { + # failing that, try using more precision + $str = sprintf("%.${max_prec}g", $nv); +# if (pack("F", $str) ne pack("F", $nv)) { + if ($str != $nv) { + # not representable in decimal with whatever sprintf() + # and atof() Perl is using here. + my($mant, $exp) = split_float($nv); + return $self->maybe_parens("$mant * 2**$exp", $cx, 19); + } + } + + # preserve NV-ness: output as NNN.0 rather than NNN + $str .= ".0" if $str =~ /^-?[0-9]+$/; + + $str = $self->maybe_parens($str, $cx, 21) if $nv < 0; + return $str; + } elsif ($sv->FLAGS & SVf_ROK && $sv->can("RV")) { + my $ref = $sv->RV; + my $class = class($ref); + if ($class eq "AV") { + return "[" . $self->list_const(2, $ref->ARRAY) . "]"; + } elsif ($class eq "HV") { + my %hash = $ref->ARRAY; + my @elts; + for my $k (sort keys %hash) { + push @elts, "$k => " . $self->const($hash{$k}, 6); + } + return "{" . join(", ", @elts) . "}"; + } elsif ($class eq "CV") { + no overloading; + if ($self->{curcv} && + $self->{curcv}->object_2svref == $ref->object_2svref) { + return $self->keyword("__SUB__"); + } + return $self->kw_sub_or_method($ref) . " " . $self->deparse_sub($ref); + } + if ($class ne 'SPECIAL' and $ref->FLAGS & SVs_SMG) { + for (my $mg = $ref->MAGIC; $mg; $mg = $mg->MOREMAGIC) { + if ($mg->TYPE eq 'r') { + my $re = re_uninterp(escape_re(re_unback($mg->precomp))); + return single_delim("qr", "", $re, $self); + } + } + } + + my $const = $self->const($ref, 20); + if ($self->{in_subst_repl} && $const =~ /^[0-9]/) { + $const = "($const)"; + } + return $self->maybe_parens("\\$const", $cx, 20); + } elsif ($sv->FLAGS & SVf_POK) { + my $str = $sv->PV; + return $self->quoted_const_str($str); + } else { + return "undef"; + } +} + +sub const_dumper { + my $self = shift; + my($sv, $cx) = @_; + my $ref = $sv->object_2svref(); + my $dumper = Data::Dumper->new([$$ref], ['$v']); + $dumper->Purity(1)->Terse(1)->Deparse(1)->Indent(0)->Useqq(1)->Sortkeys(1); + my $str = $dumper->Dump(); + if ($str =~ /^\$v/) { + return '${my ' . $str . ' \$v}'; + } else { + return $str; + } +} + +sub const_sv { + my $self = shift; + my $op = shift; + my $sv = $op->sv; + # the constant could be in the pad (under useithreads) + $sv = $self->padval($op->targ) unless $$sv; + return $sv; +} + +sub meth_sv { + my $self = shift; + my $op = shift; + my $sv = $op->meth_sv; + # the constant could be in the pad (under useithreads) + $sv = $self->padval($op->targ) unless $$sv; + return $sv; +} + +sub meth_rclass_sv { + my $self = shift; + my $op = shift; + my $sv = $op->rclass; + # the constant could be in the pad (under useithreads) + $sv = $self->padval($sv) unless ref $sv; + return $sv; +} + +sub pp_const { + my $self = shift; + my($op, $cx) = @_; +# if ($op->private & OPpCONST_BARE) { # trouble with '=>' autoquoting +# return $self->const_sv($op)->PV; +# } + my $sv = $self->const_sv($op); + + my $token = ($op->private & OPpCONST_TOKEN_MASK); + if ($token) { # handle __LINE__ etc + if ($token == OPpCONST_TOKEN_LINE) { + return "__LINE__"; + } + elsif ($token == OPpCONST_TOKEN_FILE) { + return "__FILE__"; + } + elsif ($token == OPpCONST_TOKEN_PACKAGE) { + return "__PACKAGE__"; + } + } + + return $self->const($sv, $cx); +} + + +# Join two components of a double-quoted string, disambiguating +# "${foo}bar", "${foo}{bar}", "${foo}[1]", "$foo\::bar" + +sub dq_disambiguate { + my ($first, $last) = @_; + ($last =~ /^[A-Z\\\^\[\]_?]/ && + $first =~ s/([\$@])\^$/${1}{^}/) # "${^}W" etc + || ($last =~ /^[:'{\[\w_]/ && #' + $first =~ s/([\$@])([A-Za-z_]\w*)$/${1}{$2}/); + return $first . $last; +} + + +# Deparse a double-quoted optree. For example, "$a[0]\Q$b\Efo\"o" gets +# compiled to concat(concat($[0],quotemeta($b)),const("fo\"o")), and this +# sub deparses it back to $a[0]\Q$b\Efo"o +# (It does not add delimiters) + +sub dq { + my $self = shift; + my $op = shift; + my $type = $op->name; + if ($type eq "const") { + return uninterp(escape_str(unback($self->const_sv($op)->as_string))); + } elsif ($type eq "concat") { + return dq_disambiguate($self->dq($op->first), $self->dq($op->last)); + } elsif ($type eq "multiconcat") { + return $self->do_multiconcat($op, 26, 1); + } elsif ($type eq "uc") { + return '\U' . $self->dq($op->first->sibling) . '\E'; + } elsif ($type eq "lc") { + return '\L' . $self->dq($op->first->sibling) . '\E'; + } elsif ($type eq "ucfirst") { + return '\u' . $self->dq($op->first->sibling); + } elsif ($type eq "lcfirst") { + return '\l' . $self->dq($op->first->sibling); + } elsif ($type eq "quotemeta") { + return '\Q' . $self->dq($op->first->sibling) . '\E'; + } elsif ($type eq "fc") { + return '\F' . $self->dq($op->first->sibling) . '\E'; + } elsif ($type eq "join") { + return $self->deparse($op->last, 26); # was join($", @ary) + } else { + return $self->deparse($op, 26); + } +} + +sub pp_backtick { + my $self = shift; + my($op, $cx) = @_; + # skip pushmark if it exists (readpipe() vs ``) + my $child = $op->first->sibling->isa('B::NULL') + ? $op->first : $op->first->sibling; + if ($self->pure_string($child)) { + return single_delim("qx", '`', $self->dq($child, 1), $self); + } + unop($self, @_, "readpipe"); +} + +sub dquote { + my $self = shift; + my($op, $cx) = @_; + my $kid = $op->first->sibling; # skip ex-stringify, pushmark + return $self->deparse($kid, $cx) if $self->{'unquote'}; + $self->maybe_targmy($kid, $cx, + sub {single_delim("qq", '"', $self->dq($_[1]), + $self)}); +} + +# OP_STRINGIFY is a listop, but it only ever has one arg +sub pp_stringify { + my ($self, $op, $cx) = @_; + my $kid = $op->first->sibling; + while ($kid->name eq 'null' && !null($kid->first)) { + $kid = $kid->first; + } + if ($kid->name =~ /^(?:const|padsv|rv2sv|av2arylen|gvsv|multideref + |aelemfast(?:_lex)?|[ah]elem|join|concat)\z/x) { + maybe_targmy(@_, \&dquote); + } + else { + # Actually an optimised join. + my $result = listop(@_,"join"); + $result =~ s/join([( ])/join$1$self->{'ex_const'}, /; + $result; + } +} + +# tr/// and s/// (and tr[][], tr[]//, tr###, etc) +# note that tr(from)/to/ is OK, but not tr/from/(to) +sub double_delim { + my($from, $to) = @_; + my($succeed, $delim); + if ($from !~ m[/] and $to !~ m[/]) { + return "/$from/$to/"; + } elsif (($succeed, $from) = balanced_delim($from) and $succeed) { + if (($succeed, $to) = balanced_delim($to) and $succeed) { + return "$from$to"; + } else { + for $delim ('/', '"', '#') { # note no "'" -- s''' is special + return "$from$delim$to$delim" if index($to, $delim) == -1; + } + $to =~ s[/][\\/]g; + return "$from/$to/"; + } + } else { + for $delim ('/', '"', '#') { # note no ' + return "$delim$from$delim$to$delim" + if index($to . $from, $delim) == -1; + } + $from =~ s[/][\\/]g; + $to =~ s[/][\\/]g; + return "/$from/$to/"; + } +} + +# Escape a characrter. +# Only used by tr///, so backslashes hyphens + +sub pchr { + my($n) = @_; + return sprintf("\\x{%X}", $n) if $n > 255; + return '\\\\' if $n == ord '\\'; + return "\\-" if $n == ord "-"; + # I'm presuming a regex is not ok here, otherwise we could have used + # /[[:print:]]/a to get here + return chr($n) if ( utf8::native_to_unicode($n) + >= utf8::native_to_unicode(ord(' ')) + and utf8::native_to_unicode($n) + <= utf8::native_to_unicode(ord('~'))); + + my $mnemonic_pos = index("\a\b\e\f\n\r\t", chr($n)); + return "\\" . substr("abefnrt", $mnemonic_pos, 1) if $mnemonic_pos >= 0; + + return '\\c' . $unctrl{chr $n} if $n >= ord("\cA") and $n <= ord("\cZ"); +# return '\x' . sprintf("%02x", $n); + return '\\' . sprintf("%03o", $n); +} + +# Convert a list of characters into a string suitable for tr/// search or +# replacement, with suitable escaping and collapsing of ranges + +sub collapse { + my(@chars) = @_; + my($str, $c, $tr) = (""); + for ($c = 0; $c < @chars; $c++) { + $tr = $chars[$c]; + $str .= pchr($tr); + if ($c <= $#chars - 2 and $chars[$c + 1] == $tr + 1 and + $chars[$c + 2] == $tr + 2) + { + for (; $c <= $#chars-1 and $chars[$c + 1] == $chars[$c] + 1; $c++) + {} + $str .= "-"; + $str .= pchr($chars[$c]); + } + } + return $str; +} + +sub tr_decode_byte { + my($table, $flags) = @_; + my $ssize_t = $Config{ptrsize} == 8 ? 'q' : 'l'; + my ($size, @table) = unpack("${ssize_t}s*", $table); + pop @table; # remove the wildcard final entry + + my($c, $tr, @from, @to, @delfrom, $delhyphen); + if ($table[ord "-"] != -1 and + $table[ord("-") - 1] == -1 || $table[ord("-") + 1] == -1) + { + $tr = $table[ord "-"]; + $table[ord "-"] = -1; + if ($tr >= 0) { + @from = ord("-"); + @to = $tr; + } else { # -2 ==> delete + $delhyphen = 1; + } + } + for ($c = 0; $c < @table; $c++) { + $tr = $table[$c]; + if ($tr >= 0) { + push @from, $c; push @to, $tr; + } elsif ($tr == -2) { + push @delfrom, $c; + } + } + @from = (@from, @delfrom); + + if ($flags & OPpTRANS_COMPLEMENT) { + unless ($flags & OPpTRANS_DELETE) { + @to = () if ("@from" eq "@to"); + } + + my @newfrom = (); + my %from; + @from{@from} = (1) x @from; + for ($c = 0; $c < 256; $c++) { + push @newfrom, $c unless $from{$c}; + } + @from = @newfrom; + } + unless ($flags & OPpTRANS_DELETE || !@to) { + pop @to while $#to and $to[$#to] == $to[$#to -1]; + } + my($from, $to); + $from = collapse(@from); + $to = collapse(@to); + $from .= "-" if $delhyphen; + return ($from, $to); +} + +my $infinity = ~0 >> 1; # IV_MAX + +sub tr_append_to_invlist { + my ($list_ref, $current, $next) = @_; + + # Appends the range $current..$next-1 to the inversion list $list_ref + + printf STDERR "%d: %d..%d %s", __LINE__, $current, $next, Dumper $list_ref if DEBUG; + + if (@$list_ref && $list_ref->[-1] == $current) { + + # The new range extends the current final one. If it is a finite + # rane, replace the current final by the new ending. + if (defined $next) { + $list_ref->[-1] = $next; + } + else { + # The new range extends to infinity, which means the current end + # of the inversion list is dangling. Removing it causes things to + # work. + pop @$list_ref; + } + } + else { # The new range starts after the current final one; add it as a + # new range + push @$list_ref, $current; + push @$list_ref, $next if defined $next; + } + + print STDERR __LINE__, ": ", Dumper $list_ref if DEBUG; +} + +sub tr_invlist_to_string { + my ($list_ref, $to_complement) = @_; + + # Stringify the inversion list $list_ref, possibly complementing it first. + # CAUTION: this can modify $list_ref. + + print STDERR __LINE__, ": ", Dumper $list_ref if DEBUG; + + if ($to_complement) { + + # Complementing an inversion list is done by prepending a 0 if it + # doesn't have one there already; otherwise removing the leading 0. + if ($list_ref->[0] == 0) { + shift @$list_ref; + } + else { + unshift @$list_ref, 0; + } + + print STDERR __LINE__, ": ", Dumper $list_ref if DEBUG; + } + + my $output = ""; + + # Every other element is in the list. + for (my $i = 0; $i < @$list_ref; $i += 2) { + my $base = $list_ref->[$i]; + $output .= pchr($base); + last unless defined $list_ref->[$i+1]; + + # The beginning of the next element starts the range of items not in + # the list. + my $upper = $list_ref->[$i+1] - 1; + my $range = $upper - $base; + $output .= '-' if $range > 1; # Adjacent characters don't have a + # minus, though it would be legal to do + # so + $output .= pchr($upper) if $range > 0; + } + + print STDERR __LINE__, ": tr_invlist_to_string() returning '$output'\n" + if DEBUG; + return $output; +} + +my $unmapped = ~0; +my $special_handling = ~0 - 1; + +sub dump_invmap { + my ($invlist_ref, $map_ref) = @_; + + for my $i (0 .. @$invlist_ref - 1) { + printf STDERR "[%d]\t%x\t", $i, $invlist_ref->[$i]; + my $map = $map_ref->[$i]; + if ($map == $unmapped) { + print STDERR "TR_UNMAPPED\n"; + } + elsif ($map == $special_handling) { + print STDERR "TR_SPECIAL\n"; + } + else { + printf STDERR "%x\n", $map; + } + } +} + +sub tr_decode_utf8 { + my($tr_av, $flags) = @_; + + printf STDERR "\n%s: %d: flags=0x%x\n", __FILE__, __LINE__, $flags if DEBUG; + + my $invlist = $tr_av->ARRAYelt(0); + my @invlist = unpack("J*", $invlist->PV); + my @map = unpack("J*", $tr_av->ARRAYelt(1)->PV); + + dump_invmap(\@invlist, \@map) if DEBUG; + + my @from; + my @to; + + # Go through the whole map + for (my $i = 0; $i < @invlist; $i++) { + my $map = $map[$i]; + printf STDERR "%d: i=%d, source=%x, map=%x\n", + __LINE__, $i, $invlist[$i], $map if DEBUG; + + # Ignore any lines that are unmapped + next if $map == $unmapped; + + # Calculate this component of the mapping; First the lhs + my $this_from = $invlist[$i]; + my $next_from = $invlist[$i+1] if $i < @invlist - 1; + + # The length of the rhs is the same as the lhs, except when special + my $next_map = $map - $this_from + $next_from + if $map != $special_handling && defined $next_from; + + if (DEBUG) { + printf STDERR "%d: i=%d, from=%x, to=%x", + __LINE__, $i, $this_from, $map; + printf STDERR ", next_from=%x,", $next_from if defined $next_from; + printf STDERR ", next_map=%x", $next_map if defined $next_map; + print STDERR "\n"; + } + + # Add the lhs. + tr_append_to_invlist(\@from, $this_from, $next_from); + + # And, the rhs; special handling doesn't get output as it really is an + # unmatched rhs + tr_append_to_invlist(\@to, $map, $next_map) if $map != $special_handling; + } + + # Done with the input. + + my $to; + if (join("", @from) eq join("", @to)) { + + # the rhs is suppressed if identical to the left. That's because + # tr/ABC/ABC/ can be written as tr/ABC//. (Do this comparison before + # any complementing) + $to = ""; + } + else { + $to = tr_invlist_to_string(\@to, 0); # rhs not complemented + } + + my $from = tr_invlist_to_string(\@from, + ($flags & OPpTRANS_COMPLEMENT) != 0); + + print STDERR "Returning ", escape_str($from), "/", + escape_str($to), "\n" if DEBUG; + return (escape_str($from), escape_str($to)); +} + +sub pp_trans { + my $self = shift; + my($op, $cx, $morflags) = @_; + my($from, $to); + my $class = class($op); + my $priv_flags = $op->private; + if ($class eq "PVOP") { + ($from, $to) = tr_decode_byte($op->pv, $priv_flags); + } elsif ($class eq "PADOP") { + ($from, $to) + = tr_decode_utf8($self->padval($op->padix), $priv_flags); + } else { # class($op) eq "SVOP" + ($from, $to) = tr_decode_utf8($op->sv, $priv_flags); + } + my $flags = ""; + $flags .= "c" if $priv_flags & OPpTRANS_COMPLEMENT; + $flags .= "d" if $priv_flags & OPpTRANS_DELETE; + $to = "" if $from eq $to and $flags eq ""; + $flags .= "s" if $priv_flags & OPpTRANS_SQUASH; + $flags .= $morflags if defined $morflags; + my $ret = $self->keyword("tr") . double_delim($from, $to) . $flags; + if (my $targ = $op->targ) { + return $self->maybe_parens($self->padname($targ) . " =~ $ret", + $cx, 20); + } + return $ret; +} + +sub pp_transr { push @_, 'r'; goto &pp_trans } + +# Join two components of a double-quoted re, disambiguating +# "${foo}bar", "${foo}{bar}", "${foo}[1]". + +sub re_dq_disambiguate { + my ($first, $last) = @_; + ($last =~ /^[A-Z\\\^\[\]_?]/ && + $first =~ s/([\$@])\^$/${1}{^}/) # "${^}W" etc + || ($last =~ /^[{\[\w_]/ && + $first =~ s/([\$@])([A-Za-z_]\w*)$/${1}{$2}/); + return $first . $last; +} + +# Like dq(), but different +sub re_dq { + my $self = shift; + my ($op) = @_; + + my $type = $op->name; + if ($type eq "const") { + my $unbacked = re_unback($self->const_sv($op)->as_string); + return re_uninterp(escape_re($unbacked)); + } elsif ($type eq "concat") { + my $first = $self->re_dq($op->first); + my $last = $self->re_dq($op->last); + return re_dq_disambiguate($first, $last); + } elsif ($type eq "multiconcat") { + return $self->do_multiconcat($op, 26, 2); + } elsif ($type eq "uc") { + return '\U' . $self->re_dq($op->first->sibling) . '\E'; + } elsif ($type eq "lc") { + return '\L' . $self->re_dq($op->first->sibling) . '\E'; + } elsif ($type eq "ucfirst") { + return '\u' . $self->re_dq($op->first->sibling); + } elsif ($type eq "lcfirst") { + return '\l' . $self->re_dq($op->first->sibling); + } elsif ($type eq "quotemeta") { + return '\Q' . $self->re_dq($op->first->sibling) . '\E'; + } elsif ($type eq "fc") { + return '\F' . $self->re_dq($op->first->sibling) . '\E'; + } elsif ($type eq "join") { + return $self->deparse($op->last, 26); # was join($", @ary) + } else { + my $ret = $self->deparse($op, 26); + $ret =~ s/^\$([(|)])\z/\${$1}/ # $( $| $) need braces + or $ret =~ s/^\@([-+])\z/\@{$1}/; # @- @+ need braces + return $ret; + } +} + +sub pure_string { + my ($self, $op) = @_; + return 0 if null $op; + my $type = $op->name; + + if ($type eq 'const' || $type eq 'av2arylen') { + return 1; + } + elsif ($type =~ /^(?:[ul]c(first)?|fc)$/ || $type eq 'quotemeta') { + return $self->pure_string($op->first->sibling); + } + elsif ($type eq 'join') { + my $join_op = $op->first->sibling; # Skip pushmark + return 0 unless $join_op->name eq 'null' && $join_op->targ == OP_RV2SV; + + my $gvop = $join_op->first; + return 0 unless $gvop->name eq 'gvsv'; + return 0 unless '"' eq $self->gv_name($self->gv_or_padgv($gvop)); + + return 0 unless ${$join_op->sibling} eq ${$op->last}; + return 0 unless $op->last->name =~ /^(?:[ah]slice|(?:rv2|pad)av)$/; + } + elsif ($type eq 'concat') { + return $self->pure_string($op->first) + && $self->pure_string($op->last); + } + elsif ($type eq 'multiconcat') { + my ($kid, @kids); + for ($kid = $op->first; !null $kid; $kid = $kid->sibling) { + # skip the consts and/or padsv we've optimised away + push @kids, $kid + unless $kid->type == OP_NULL + && ( $kid->targ == OP_PADSV + || $kid->targ == OP_CONST + || $kid->targ == OP_PUSHMARK); + } + + if ($op->flags & OPf_STACKED) { + # remove expr from @kids where 'expr = ...' or 'expr .= ....' + if ($op->private & OPpMULTICONCAT_APPEND) { + shift(@kids); + } + else { + pop(@kids); + } + } + for (@kids) { + return 0 unless $self->pure_string($_); + } + return 1; + } + elsif (is_scalar($op) || $type =~ /^[ah]elem$/) { + return 1; + } + elsif ($type eq "null" and $op->can('first') and not null $op->first) { + my $first = $op->first; + + return 1 if $first->name eq "multideref"; + return 1 if $first->name eq "aelemfast_lex"; + + if ( $first->name eq "null" + and $first->can('first') + and not null $first->first + and $first->first->name eq "aelemfast" + ) + { + return 1; + } + } + + return 0; +} + +sub code_list { + my ($self,$op,$cv) = @_; + + # localise stuff relating to the current sub + $cv and + local($self->{'curcv'}) = $cv, + local($self->{'curcvlex'}), + local(@$self{qw'curstash warnings hints hinthash curcop'}) + = @$self{qw'curstash warnings hints hinthash curcop'}; + + my $re = ""; + for ($op = $op->first->sibling; !null($op); $op = $op->sibling) { + if ($op->name eq 'null' and $op->flags & OPf_SPECIAL) { + my $scope = $op->first; + # 0 context (last arg to scopeop) means statement context, so + # the contents of the block will not be wrapped in do{...}. + my $block = scopeop($scope->first->name eq "enter", $self, + $scope, 0); + # next op is the source code of the block + $op = $op->sibling; + $re .= ($self->const_sv($op)->PV =~ m|^(\(\?\??\{)|)[0]; + my $multiline = $block =~ /\n/; + $re .= $multiline ? "\n\t" : ' '; + $re .= $block; + $re .= $multiline ? "\n\b})" : " })"; + } else { + $re = re_dq_disambiguate($re, $self->re_dq($op)); + } + } + $re; +} + +sub regcomp { + my $self = shift; + my($op, $cx) = @_; + my $kid = $op->first; + $kid = $kid->first if $kid->name eq "regcmaybe"; + $kid = $kid->first if $kid->name eq "regcreset"; + my $kname = $kid->name; + if ($kname eq "null" and !null($kid->first) + and $kid->first->name eq 'pushmark') + { + my $str = ''; + $kid = $kid->first->sibling; + while (!null($kid)) { + my $first = $str; + my $last = $self->re_dq($kid); + $str = re_dq_disambiguate($first, $last); + $kid = $kid->sibling; + } + return $str, 1; + } + + return ($self->re_dq($kid), 1) + if $kname =~ /^(?:rv2|pad)av/ or $self->pure_string($kid); + return ($self->deparse($kid, $cx), 0); +} + +sub pp_regcomp { + my ($self, $op, $cx) = @_; + return (($self->regcomp($op, $cx, 0))[0]); +} + +sub re_flags { + my ($self, $op) = @_; + my $flags = ''; + my $pmflags = $op->pmflags; + if (!$pmflags) { + my $re = $op->pmregexp; + if ($$re) { + $pmflags = $re->compflags; + } + } + $flags .= "g" if $pmflags & PMf_GLOBAL; + $flags .= "i" if $pmflags & PMf_FOLD; + $flags .= "m" if $pmflags & PMf_MULTILINE; + $flags .= "o" if $pmflags & PMf_KEEP; + $flags .= "s" if $pmflags & PMf_SINGLELINE; + $flags .= "x" if $pmflags & PMf_EXTENDED; + $flags .= "x" if $pmflags & PMf_EXTENDED_MORE; + $flags .= "p" if $pmflags & PMf_KEEPCOPY; + $flags .= "n" if $pmflags & PMf_NOCAPTURE; + if (my $charset = $pmflags & PMf_CHARSET) { + # Hardcoding this is fragile, but B does not yet export the + # constants we need. + $flags .= qw(d l u a aa)[$charset >> 7] + } + # The /d flag is indicated by 0; only show it if necessary. + elsif ($self->{hinthash} and + $self->{hinthash}{reflags_charset} + || $self->{hinthash}{feature_unicode} + or $self->{hints} & $feature::hint_mask + && ($self->{hints} & $feature::hint_mask) + != $feature::hint_mask + && $self->{hints} & $feature::hint_uni8bit + ) { + $flags .= 'd'; + } + $flags; +} + +# osmic acid -- see osmium tetroxide + +my %matchwords; +map($matchwords{join "", sort split //, $_} = $_, 'cig', 'cog', 'cos', 'cogs', + 'cox', 'go', 'is', 'ism', 'iso', 'mig', 'mix', 'osmic', 'ox', 'sic', + 'sig', 'six', 'smog', 'so', 'soc', 'sog', 'xi', 'soup', 'soupmix'); + +# When deparsing a regular expression with code blocks, we have to look in +# various places to find the blocks. +# +# For qr/(?{...})/ without interpolation, the CV is under $qr->qr_anoncv +# and the code list (list of blocks and constants, maybe vars) is under +# $cv->ROOT->first->code_list: +# ./perl -Ilib -MB -e 'use O "Concise", B::svref_2object(sub {qr/(?{die})/})->ROOT->first->first->sibling->pmregexp->qr_anoncv->object_2svref' +# +# For qr/$a(?{...})/ with interpolation, the code list is more accessible, +# under $pmop->code_list, but the $cv is something you have to dig for in +# the regcomp op’s kids: +# ./perl -Ilib -mO=Concise -e 'qr/$a(?{die})/' +# +# For m// and split //, things are much simpler. There is no CV. The code +# list is under $pmop->code_list. + +sub matchop { + my $self = shift; + my($op, $cx, $name, $delim) = @_; + my $kid = $op->first; + my ($binop, $var, $re) = ("", "", ""); + if ($op->name ne 'split' && $op->flags & OPf_STACKED) { + $binop = 1; + $var = $self->deparse($kid, 20); + $var = "($var)" + if $kid->name eq 'not' + and $kid->flags & OPf_PARENS + and $var !~ /\(/; + $kid = $kid->sibling; + } + # not $name; $name will be 'm' for both match and split + elsif ($op->name eq 'match' and my $targ = $op->targ) { + $binop = 1; + $var = $self->padname($targ); + } + my $quote = 1; + my $pmflags = $op->pmflags; + my $rhs_bound_to_defsv; + my ($cv, $bregexp); + my $have_kid = !null $kid; + # Check for code blocks first + if (not null my $code_list = $op->code_list) { + $re = $self->code_list($code_list, + $op->name eq 'qr' + ? $self->padval( + $kid->first # ex-list + ->first # pushmark + ->sibling # entersub + ->first # ex-list + ->first # pushmark + ->sibling # anoncode + ->targ + ) + : undef); + } elsif (${$bregexp = $op->pmregexp} && ${$cv = $bregexp->qr_anoncv}) { + my $patop = $cv->ROOT # leavesub + ->first # qr + ->code_list;# list + $re = $self->code_list($patop, $cv); + } elsif (!$have_kid) { + $re = re_uninterp(escape_re(re_unback($op->precomp))); + } elsif ($kid->name ne 'regcomp') { + if ($op->name eq 'split') { + # split has other kids, not just regcomp + $re = re_uninterp(escape_re(re_unback($op->precomp))); + } + else { + carp("found ".$kid->name." where regcomp expected"); + } + } else { + ($re, $quote) = $self->regcomp($kid, 21); + } + if ($have_kid and $kid->name eq 'regcomp') { + my $matchop = $kid->first; + if ($matchop->name eq 'regcreset') { + $matchop = $matchop->first; + } + if ($matchop->name =~ /^(?:match|transr?|subst)\z/ + && $matchop->flags & OPf_SPECIAL) { + $rhs_bound_to_defsv = 1; + } + } + my $flags = ""; + $flags .= "c" if $pmflags & PMf_CONTINUE; + $flags .= $self->re_flags($op); + $flags = join '', sort split //, $flags; + $flags = $matchwords{$flags} if $matchwords{$flags}; + if ($pmflags & PMf_ONCE) { # only one kind of delimiter works here + $re =~ s/\?/\\?/g; + $re = $self->keyword("m") . "?$re?"; # explicit 'm' is required + } elsif ($quote) { + $re = single_delim($name, $delim, $re, $self); + } + $re = $re . $flags if $quote; + if ($binop) { + return + $self->maybe_parens( + $rhs_bound_to_defsv + ? "$var =~ (\$_ =~ $re)" + : "$var =~ $re", + $cx, 20 + ); + } else { + return $re; + } +} + +sub pp_match { matchop(@_, "m", "/") } +sub pp_qr { matchop(@_, "qr", "") } + +sub pp_runcv { unop(@_, "__SUB__"); } + +sub pp_split { + my $self = shift; + my($op, $cx) = @_; + my($kid, @exprs, $ary, $expr); + my $stacked = $op->flags & OPf_STACKED; + + $kid = $op->first; + $kid = $kid->sibling if $kid->name eq 'regcomp'; + for (; !null($kid); $kid = $kid->sibling) { + push @exprs, $self->deparse($kid, 6); + } + + unshift @exprs, $self->matchop($op, $cx, "m", "/"); + + if ($op->private & OPpSPLIT_ASSIGN) { + # With C<@array = split(/pat/, str);>, + # array is stored in split's pmreplroot; either + # as an integer index into the pad (for a lexical array) + # or as GV for a package array (which will be a pad index + # on threaded builds) + # With my/our @array = split(/pat/, str), the array is instead + # accessed via an extra padav/rv2av op at the end of the + # split's kid ops. + + if ($stacked) { + $ary = pop @exprs; + } + else { + if ($op->private & OPpSPLIT_LEX) { + $ary = $self->padname($op->pmreplroot); + } + else { + # union with op_pmtargetoff, op_pmtargetgv + my $gv = $op->pmreplroot; + $gv = $self->padval($gv) if !ref($gv); + $ary = $self->maybe_local(@_, + $self->stash_variable('@', + $self->gv_name($gv), + $cx)) + } + if ($op->private & OPpLVAL_INTRO) { + $ary = $op->private & OPpSPLIT_LEX ? "my $ary" : "local $ary"; + } + } + } + + # handle special case of split(), and split(' ') that compiles to /\s+/ + $exprs[0] = q{' '} if ($op->reflags // 0) & RXf_SKIPWHITE(); + + $expr = "split(" . join(", ", @exprs) . ")"; + if ($ary) { + return $self->maybe_parens("$ary = $expr", $cx, 7); + } else { + return $expr; + } +} + +# oxime -- any of various compounds obtained chiefly by the action of +# hydroxylamine on aldehydes and ketones and characterized by the +# bivalent grouping C=NOH [Webster's Tenth] + +my %substwords; +map($substwords{join "", sort split //, $_} = $_, 'ego', 'egoism', 'em', + 'es', 'ex', 'exes', 'gee', 'go', 'goes', 'ie', 'ism', 'iso', 'me', + 'meese', 'meso', 'mig', 'mix', 'os', 'ox', 'oxime', 'see', 'seem', + 'seg', 'sex', 'sig', 'six', 'smog', 'sog', 'some', 'xi', 'rogue', + 'sir', 'rise', 'smore', 'more', 'seer', 'rome', 'gore', 'grim', 'grime', + 'or', 'rose', 'rosie'); + +sub pp_subst { + my $self = shift; + my($op, $cx) = @_; + my $kid = $op->first; + my($binop, $var, $re, $repl) = ("", "", "", ""); + if ($op->flags & OPf_STACKED) { + $binop = 1; + $var = $self->deparse($kid, 20); + $var = "($var)" + if $kid->name eq 'not' + and $kid->flags & OPf_PARENS + and $var !~ /\(/; + $kid = $kid->sibling; + } + elsif (my $targ = $op->targ) { + $binop = 1; + $var = $self->padname($targ); + } + my $flags = ""; + my $pmflags = $op->pmflags; + if (null($op->pmreplroot)) { + $repl = $kid; + $kid = $kid->sibling; + } else { + $repl = $op->pmreplroot->first; # skip substcont + } + while ($repl->name eq "entereval") { + $repl = $repl->first; + $flags .= "e"; + } + { + local $self->{in_subst_repl} = 1; + if ($pmflags & PMf_EVAL) { + $repl = $self->deparse($repl->first, 0); + } else { + $repl = $self->dq($repl); + } + } + if (not null my $code_list = $op->code_list) { + $re = $self->code_list($code_list); + } elsif (null $kid) { + $re = re_uninterp(escape_re(re_unback($op->precomp))); + } else { + ($re) = $self->regcomp($kid, 1); + } + $flags .= "r" if $pmflags & PMf_NONDESTRUCT; + $flags .= "e" if $pmflags & PMf_EVAL; + $flags .= $self->re_flags($op); + $flags = join '', sort split //, $flags; + $flags = $substwords{$flags} if $substwords{$flags}; + my $core_s = $self->keyword("s"); # maybe CORE::s + if ($binop) { + return $self->maybe_parens("$var =~ $core_s" + . double_delim($re, $repl) . $flags, + $cx, 20); + } else { + return "$core_s". double_delim($re, $repl) . $flags; + } +} + +sub is_lexical_subs { + my (@ops) = shift; + for my $op (@ops) { + return 0 if $op->name !~ /\A(?:introcv|clonecv)\z/; + } + return 1; +} + +# Pretend these two ops do not exist. The perl parser adds them to the +# beginning of any block containing my-sub declarations, whereas we handle +# the subs in pad_subs and next_todo. +*pp_clonecv = *pp_introcv; +sub pp_introcv { + my $self = shift; + my($op, $cx) = @_; + # For now, deparsing doesn't worry about the distinction between introcv + # and clonecv, so pretend this op doesn't exist: + return ''; +} + +sub pp_padcv { + my $self = shift; + my($op, $cx) = @_; + return $self->padany($op); +} + +my %lvref_funnies = ( + OPpLVREF_SV, => '$', + OPpLVREF_AV, => '@', + OPpLVREF_HV, => '%', + OPpLVREF_CV, => '&', +); + +sub pp_refassign { + my ($self, $op, $cx) = @_; + my $left; + if ($op->private & OPpLVREF_ELEM) { + $left = $op->first->sibling; + $left = maybe_local(@_, elem($self, $left, undef, + $left->targ == OP_AELEM + ? qw([ ] padav) + : qw({ } padhv))); + } elsif ($op->flags & OPf_STACKED) { + $left = maybe_local(@_, + $lvref_funnies{$op->private & OPpLVREF_TYPE} + . $self->deparse($op->first->sibling)); + } else { + $left = &pp_padsv; + } + my $right = $self->deparse_binop_right($op, $op->first, 7); + return $self->maybe_parens("\\$left = $right", $cx, 7); +} + +sub pp_lvref { + my ($self, $op, $cx) = @_; + my $code; + if ($op->private & OPpLVREF_ELEM) { + $code = $op->first->name =~ /av\z/ ? &pp_aelem : &pp_helem; + } elsif ($op->flags & OPf_STACKED) { + $code = maybe_local(@_, + $lvref_funnies{$op->private & OPpLVREF_TYPE} + . $self->deparse($op->first)); + } else { + $code = &pp_padsv; + } + "\\$code"; +} + +sub pp_lvrefslice { + my ($self, $op, $cx) = @_; + '\\' . ($op->last->name =~ /av\z/ ? &pp_aslice : &pp_hslice); +} + +sub pp_lvavref { + my ($self, $op, $cx) = @_; + '\\(' . ($op->flags & OPf_STACKED + ? maybe_local(@_, rv2x(@_, "\@")) + : &pp_padsv) . ')' +} + + +sub pp_argcheck { + my $self = shift; + my($op, $cx) = @_; + my ($params, $opt_params, $slurpy) = $op->aux_list($self->{curcv}); + my $mandatory = $params - $opt_params; + my $check = ''; + + $check .= < 0; +die sprintf("Too few arguments for subroutine at %s line %d.\\n", (caller)[1, 2]) unless \@_ >= $mandatory; +EOF + + my $cond = ($params & 1) ? 'unless' : 'if'; + $check .= < $params && ((\@_ - $params) & 1); +EOF + + $check =~ s/;\n\z//; + return $check; +} + + +sub pp_argelem { + my $self = shift; + my($op, $cx) = @_; + my $var = $self->padname($op->targ); + my $ix = $op->string($self->{curcv}); + my $expr; + if ($op->flags & OPf_KIDS) { + $expr = $self->deparse($op->first, 7); + } + elsif ($var =~ /^[@%]/) { + $expr = $ix ? "\@_[$ix .. \$#_]" : '@_'; + } + else { + $expr = "\$_[$ix]"; + } + return "my $var = $expr"; +} + + +sub pp_argdefelem { + my $self = shift; + my($op, $cx) = @_; + my $ix = $op->targ; + my $expr = "\@_ >= " . ($ix+1) . " ? \$_[$ix] : "; + my $def = $self->deparse($op->first, 7); + $def = "($def)" if $op->first->flags & OPf_PARENS; + $expr .= $self->deparse($op->first, $cx); + return $expr; +} + + +sub pp_pushdefer { + my $self = shift; + my($op, $cx) = @_; + # defer block body is stored in the ->first of an OP_NULL that is + # ->first of OP_PUSHDEFER + my $body = $self->deparse($op->first->first); + return "defer {\n\t$body\n\b}\cK"; +} + +sub builtin1 { + my $self = shift; + my ($op, $cx, $name) = @_; + my $arg = $self->deparse($op->first, 6); + # TODO: work out if lexical alias is present somehow... + return "builtin::$name($arg)"; +} + +sub pp_is_bool { builtin1(@_, "is_bool"); } +sub pp_is_weak { builtin1(@_, "is_weak"); } +sub pp_weaken { builtin1(@_, "weaken"); } +sub pp_unweaken { builtin1(@_, "unweaken"); } +sub pp_blessed { builtin1(@_, "blessed"); } +sub pp_refaddr { $_[0]->maybe_targmy(@_[1,2], \&builtin1, "refaddr"); } +sub pp_reftype { $_[0]->maybe_targmy(@_[1,2], \&builtin1, "reftype"); } +sub pp_ceil { $_[0]->maybe_targmy(@_[1,2], \&builtin1, "ceil"); } +sub pp_floor { $_[0]->maybe_targmy(@_[1,2], \&builtin1, "floor"); } +sub pp_is_tainted { builtin1(@_, "is_tainted"); } + +1; +__END__ + +=head1 NAME + +B::Deparse - Perl compiler backend to produce perl code + +=head1 SYNOPSIS + +B B<-MO=Deparse>[B<,-d>][B<,-f>I][B<,-p>][B<,-q>][B<,-l>] + [B<,-s>I][B<,-x>I] I + +=head1 DESCRIPTION + +B::Deparse is a backend module for the Perl compiler that generates +perl source code, based on the internal compiled structure that perl +itself creates after parsing a program. The output of B::Deparse won't +be exactly the same as the original source, since perl doesn't keep +track of comments or whitespace, and there isn't a one-to-one +correspondence between perl's syntactical constructions and their +compiled form, but it will often be close. When you use the B<-p> +option, the output also includes parentheses even when they are not +required by precedence, which can make it easy to see if perl is +parsing your expressions the way you intended. + +While B::Deparse goes to some lengths to try to figure out what your +original program was doing, some parts of the language can still trip +it up; it still fails even on some parts of Perl's own test suite. If +you encounter a failure other than the most common ones described in +the BUGS section below, you can help contribute to B::Deparse's +ongoing development by submitting a bug report with a small +example. + +=head1 OPTIONS + +As with all compiler backend options, these must follow directly after +the '-MO=Deparse', separated by a comma but not any white space. + +=over 4 + +=item B<-d> + +Output data values (when they appear as constants) using Data::Dumper. +Without this option, B::Deparse will use some simple routines of its +own for the same purpose. Currently, Data::Dumper is better for some +kinds of data (such as complex structures with sharing and +self-reference) while the built-in routines are better for others +(such as odd floating-point values). + +=item B<-f>I + +Normally, B::Deparse deparses the main code of a program, and all the subs +defined in the same file. To include subs defined in +other files, pass the B<-f> option with the filename. +You can pass the B<-f> option several times, to +include more than one secondary file. (Most of the time you don't want to +use it at all.) You can also use this option to include subs which are +defined in the scope of a B<#line> directive with two parameters. + +=item B<-l> + +Add '#line' declarations to the output based on the line and file +locations of the original code. + +=item B<-p> + +Print extra parentheses. Without this option, B::Deparse includes +parentheses in its output only when they are needed, based on the +structure of your program. With B<-p>, it uses parentheses (almost) +whenever they would be legal. This can be useful if you are used to +LISP, or if you want to see how perl parses your input. If you say + + if ($var & 0x7f == 65) {print "Gimme an A!"} + print ($which ? $a : $b), "\n"; + $name = $ENV{USER} or "Bob"; + +C will print + + if (($var & 0)) { + print('Gimme an A!') + }; + (print(($which ? $a : $b)), '???'); + (($name = $ENV{'USER'}) or '???') + +which probably isn't what you intended (the C<'???'> is a sign that +perl optimized away a constant value). + +=item B<-P> + +Disable prototype checking. With this option, all function calls are +deparsed as if no prototype was defined for them. In other words, + + perl -MO=Deparse,-P -e 'sub foo (\@) { 1 } foo @x' + +will print + + sub foo (\@) { + 1; + } + &foo(\@x); + +making clear how the parameters are actually passed to C. + +=item B<-q> + +Expand double-quoted strings into the corresponding combinations of +concatenation, uc, ucfirst, lc, lcfirst, quotemeta, and join. For +instance, print + + print "Hello, $world, @ladies, \u$gentlemen\E, \u\L$me!"; + +as + + print 'Hello, ' . $world . ', ' . join($", @ladies) . ', ' + . ucfirst($gentlemen) . ', ' . ucfirst(lc $me . '!'); + +Note that the expanded form represents the way perl handles such +constructions internally -- this option actually turns off the reverse +translation that B::Deparse usually does. On the other hand, note that +C<$x = "$y"> is not the same as C<$x = $y>: the former makes the value +of $y into a string before doing the assignment. + +=item B<-s>I + +Tweak the style of B::Deparse's output. The letters should follow +directly after the 's', with no space or punctuation. The following +options are available: + +=over 4 + +=item B + +Cuddle C, C, and C blocks. For example, print + + if (...) { + ... + } else { + ... + } + +instead of + + if (...) { + ... + } + else { + ... + } + +The default is not to cuddle. + +=item BI + +Indent lines by multiples of I columns. The default is 4 columns. + +=item B + +Use tabs for each 8 columns of indent. The default is to use only spaces. +For instance, if the style options are B<-si4T>, a line that's indented +3 times will be preceded by one tab and four spaces; if the options were +B<-si8T>, the same line would be preceded by three tabs. + +=item BIB<.> + +Print I for the value of a constant that can't be determined +because it was optimized away (mnemonic: this happens when a constant +is used in Boid context). The end of the string is marked by a period. +The string should be a valid perl expression, generally a constant. +Note that unless it's a number, it probably needs to be quoted, and on +a command line quotes need to be protected from the shell. Some +conventional values include 0, 1, 42, '', 'foo', and +'Useless use of constant omitted' (which may need to be +B<-sv"'Useless use of constant omitted'."> +or something similar depending on your shell). The default is '???'. +If you're using B::Deparse on a module or other file that's require'd, +you shouldn't use a value that evaluates to false, since the customary +true constant at the end of a module will be in void context when the +file is compiled as a main program. + +=back + +=item B<-x>I + +Expand conventional syntax constructions into equivalent ones that expose +their internal operation. I should be a digit, with higher values +meaning more expansion. As with B<-q>, this actually involves turning off +special cases in B::Deparse's normal operations. + +If I is at least 3, C loops will be translated into equivalent +while loops with continue blocks; for instance + + for ($i = 0; $i < 10; ++$i) { + print $i; + } + +turns into + + $i = 0; + while ($i < 10) { + print $i; + } continue { + ++$i + } + +Note that in a few cases this translation can't be perfectly carried back +into the source code -- if the loop's initializer declares a my variable, +for instance, it won't have the correct scope outside of the loop. + +If I is at least 5, C declarations will be translated into +C blocks containing calls to C and C; for +instance, + + use strict 'refs'; + +turns into + + sub BEGIN { + require strict; + do { + 'strict'->import('refs') + }; + } + +If I is at least 7, C statements will be translated into +equivalent expressions using C<&&>, C and C; for instance + + print 'hi' if $nice; + if ($nice) { + print 'hi'; + } + if ($nice) { + print 'hi'; + } else { + print 'bye'; + } + +turns into + + $nice and print 'hi'; + $nice and do { print 'hi' }; + $nice ? do { print 'hi' } : do { print 'bye' }; + +Long sequences of elsifs will turn into nested ternary operators, which +B::Deparse doesn't know how to indent nicely. + +=back + +=head1 USING B::Deparse AS A MODULE + +=head2 Synopsis + + use B::Deparse; + $deparse = B::Deparse->new("-p", "-sC"); + $body = $deparse->coderef2text(\&func); + eval "sub func $body"; # the inverse operation + +=head2 Description + +B::Deparse can also be used on a sub-by-sub basis from other perl +programs. + +=head2 new + + $deparse = B::Deparse->new(OPTIONS) + +Create an object to store the state of a deparsing operation and any +options. The options are the same as those that can be given on the +command line (see L); options that are separated by commas +after B<-MO=Deparse> should be given as separate strings. + +=head2 ambient_pragmas + + $deparse->ambient_pragmas(strict => 'all', '$[' => $[); + +The compilation of a subroutine can be affected by a few compiler +directives, B. These are: + +=over 4 + +=item * + +use strict; + +=item * + +use warnings; + +=item * + +Assigning to the special variable $[ + +=item * + +use integer; + +=item * + +use bytes; + +=item * + +use utf8; + +=item * + +use re; + +=back + +Ordinarily, if you use B::Deparse on a subroutine which has +been compiled in the presence of one or more of these pragmas, +the output will include statements to turn on the appropriate +directives. So if you then compile the code returned by coderef2text, +it will behave the same way as the subroutine which you deparsed. + +However, you may know that you intend to use the results in a +particular context, where some pragmas are already in scope. In +this case, you use the B method to describe the +assumptions you wish to make. + +Not all of the options currently have any useful effect. See +L for more details. + +The parameters it accepts are: + +=over 4 + +=item strict + +Takes a string, possibly containing several values separated +by whitespace. The special values "all" and "none" mean what you'd +expect. + + $deparse->ambient_pragmas(strict => 'subs refs'); + +=item $[ + +Takes a number, the value of the array base $[. +Obsolete: cannot be non-zero. + +=item bytes + +=item utf8 + +=item integer + +If the value is true, then the appropriate pragma is assumed to +be in the ambient scope, otherwise not. + +=item re + +Takes a string, possibly containing a whitespace-separated list of +values. The values "all" and "none" are special. It's also permissible +to pass an array reference here. + + $deparser->ambient_pragmas(re => 'eval'); + + +=item warnings + +Takes a string, possibly containing a whitespace-separated list of +values. The values "all" and "none" are special, again. It's also +permissible to pass an array reference here. + + $deparser->ambient_pragmas(warnings => [qw[void io]]); + +If one of the values is the string "FATAL", then all the warnings +in that list will be considered fatal, just as with the B +pragma itself. Should you need to specify that some warnings are +fatal, and others are merely enabled, you can pass the B +parameter twice: + + $deparser->ambient_pragmas( + warnings => 'all', + warnings => [FATAL => qw/void io/], + ); + +See L for more information about lexical warnings. + +=item hint_bits + +=item warning_bits + +These two parameters are used to specify the ambient pragmas in +the format used by the special variables $^H and ${^WARNING_BITS}. + +They exist principally so that you can write code like: + + { my ($hint_bits, $warning_bits); + BEGIN {($hint_bits, $warning_bits) = ($^H, ${^WARNING_BITS})} + $deparser->ambient_pragmas ( + hint_bits => $hint_bits, + warning_bits => $warning_bits, + '$[' => 0 + $[ + ); } + +which specifies that the ambient pragmas are exactly those which +are in scope at the point of calling. + +=item %^H + +This parameter is used to specify the ambient pragmas which are +stored in the special hash %^H. + +=back + +=head2 coderef2text + + $body = $deparse->coderef2text(\&func) + $body = $deparse->coderef2text(sub ($$) { ... }) + +Return source code for the body of a subroutine (a block, optionally +preceded by a prototype in parens), given a reference to the +sub. Because a subroutine can have no names, or more than one name, +this method doesn't return a complete subroutine definition -- if you +want to eval the result, you should prepend "sub subname ", or "sub " +for an anonymous function constructor. Unless the sub was defined in +the main:: package, the code will include a package declaration. + +=head1 BUGS + +=over 4 + +=item * + +The only pragmas to +be completely supported are: C, +C, C, C +and C. + +Excepting those listed above, we're currently unable to guarantee that +B::Deparse will produce a pragma at the correct point in the program. +(Specifically, pragmas at the beginning of a block often appear right +before the start of the block instead.) +Since the effects of pragmas are often lexically scoped, this can mean +that the pragma holds sway over a different portion of the program +than in the input file. + +=item * + +In fact, the above is a specific instance of a more general problem: +we can't guarantee to produce BEGIN blocks or C declarations in +exactly the right place. So if you use a module which affects compilation +(such as by over-riding keywords, overloading constants or whatever) +then the output code might not work as intended. + +=item * + +Some constants don't print correctly either with or without B<-d>. +For instance, neither B::Deparse nor Data::Dumper know how to print +dual-valued scalars correctly, as in: + + use constant E2BIG => ($!=7); $y = E2BIG; print $y, 0+$y; + + use constant H => { "#" => 1 }; H->{"#"}; + +=item * + +An input file that uses source filtering probably won't be deparsed into +runnable code, because it will still include the B declaration +for the source filtering module, even though the code that is +produced is already ordinary Perl which shouldn't be filtered again. + +=item * + +Optimized-away statements are rendered as +'???'. This includes statements that +have a compile-time side-effect, such as the obscure + + my $x if 0; + +which is not, consequently, deparsed correctly. + + foreach my $i (@_) { 0 } + => + foreach my $i (@_) { '???' } + +=item * + +Lexical (my) variables declared in scopes external to a subroutine +appear in coderef2text output text as package variables. This is a tricky +problem, as perl has no native facility for referring to a lexical variable +defined within a different scope, although L is a good start. + +See also L, which combines B::Deparse and +L to serialize closures properly. + +=item * + +There are probably many more bugs on non-ASCII platforms (EBCDIC). + +=back + +=head1 AUTHOR + +Stephen McCamant , based on an earlier version +by Malcolm Beattie , with contributions from +Gisle Aas, James Duncan, Albert Dvornik, Robin Houston, Dave Mitchell, +Hugo van der Sanden, Gurusamy Sarathy, Nick Ing-Simmons, and Rafael +Garcia-Suarez. + +=cut diff --git a/git/usr/share/perl5/core_perl/B/Op_private.pm b/git/usr/share/perl5/core_perl/B/Op_private.pm new file mode 100644 index 0000000000000000000000000000000000000000..1255c38241cdf620075eddc444418d31069a8609 --- /dev/null +++ b/git/usr/share/perl5/core_perl/B/Op_private.pm @@ -0,0 +1,984 @@ +# -*- mode: Perl; buffer-read-only: t -*- +# +# lib/B/Op_private.pm +# +# Copyright (C) 2014 by Larry Wall and others +# +# You may distribute under the terms of either the GNU General Public +# License or the Artistic License, as specified in the README file. +# +# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! +# This file is built by regen/opcode.pl from data in +# regen/op_private and pod embedded in regen/opcode.pl. +# Any changes made here will be lost! + +=head1 NAME + +B::Op_private - OP op_private flag definitions + +=head1 SYNOPSIS + + use B::Op_private; + + # flag details for bit 7 of OP_AELEM's op_private: + my $name = $B::Op_private::bits{aelem}{7}; # OPpLVAL_INTRO + my $value = $B::Op_private::defines{$name}; # 128 + my $label = $B::Op_private::labels{$name}; # LVINTRO + + # the bit field at bits 5..6 of OP_AELEM's op_private: + my $bf = $B::Op_private::bits{aelem}{6}; + my $mask = $bf->{bitmask}; # etc + +=head1 DESCRIPTION + +This module provides four global hashes: + + %B::Op_private::bits + %B::Op_private::defines + %B::Op_private::labels + %B::Op_private::ops_using + +which contain information about the per-op meanings of the bits in the +op_private field. + +=head2 C<%bits> + +This is indexed by op name and then bit number (0..7). For single bit flags, +it returns the name of the define (if any) for that bit: + + $B::Op_private::bits{aelem}{7} eq 'OPpLVAL_INTRO'; + +For bit fields, it returns a hash ref containing details about the field. +The same reference will be returned for all bit positions that make +up the bit field; so for example these both return the same hash ref: + + $bitfield = $B::Op_private::bits{aelem}{5}; + $bitfield = $B::Op_private::bits{aelem}{6}; + +The general format of this hash ref is + + { + # The bit range and mask; these are always present. + bitmin => 5, + bitmax => 6, + bitmask => 0x60, + + # (The remaining keys are optional) + + # The names of any defines that were requested: + mask_def => 'OPpFOO_MASK', + baseshift_def => 'OPpFOO_SHIFT', + bitcount_def => 'OPpFOO_BITS', + + # If present, Concise etc will display the value with a 'FOO=' + # prefix. If it equals '-', then Concise will treat the bit + # field as raw bits and not try to interpret it. + label => 'FOO', + + # If present, specifies the names of some defines and the + # display labels that are used to assign meaning to particu- + # lar integer values within the bit field; e.g. 3 is dis- + # played as 'C'. + enum => [ qw( + 1 OPpFOO_A A + 2 OPpFOO_B B + 3 OPpFOO_C C + )], + + }; + + +=head2 C<%defines> + +This gives the value of every C define, e.g. + + $B::Op_private::defines{OPpLVAL_INTRO} == 128; + +=head2 C<%labels> + +This gives the short display label for each define, as used by C +and C, e.g. + + $B::Op_private::labels{OPpLVAL_INTRO} eq 'LVINTRO'; + +If the label equals '-', then Concise will treat the bit as a raw bit and +not try to display it symbolically. + +=head2 C<%ops_using> + +For each define, this gives a reference to an array of op names that use +the flag. + + @ops_using_lvintro = @{ $B::Op_private::ops_using{OPp_LVAL_INTRO} }; + +=cut + +package B::Op_private; + +our %bits; + + +our $VERSION = "5.042002"; + +$bits{$_}{3} = 'OPpENTERSUB_AMPER' for qw(entersub rv2cv); +$bits{$_}{6} = 'OPpENTERSUB_DB' for qw(entersub rv2cv); +$bits{$_}{2} = 'OPpENTERSUB_HASTARG' for qw(ceil entersub floor goto refaddr reftype rv2cv); +$bits{$_}{6} = 'OPpFLIP_LINENUM' for qw(flip flop); +$bits{$_}{1} = 'OPpFT_ACCESS' for qw(fteexec fteread ftewrite ftrexec ftrread ftrwrite); +$bits{$_}{4} = 'OPpFT_AFTER_t' for qw(ftatime ftbinary ftblk ftchr ftctime ftdir fteexec fteowned fteread ftewrite ftfile ftis ftlink ftmtime ftpipe ftrexec ftrowned ftrread ftrwrite ftsgid ftsize ftsock ftsuid ftsvtx fttext fttty ftzero); +$bits{$_}{2} = 'OPpFT_STACKED' for qw(ftatime ftbinary ftblk ftchr ftctime ftdir fteexec fteowned fteread ftewrite ftfile ftis ftlink ftmtime ftpipe ftrexec ftrowned ftrread ftrwrite ftsgid ftsize ftsock ftsuid ftsvtx fttext fttty ftzero); +$bits{$_}{3} = 'OPpFT_STACKING' for qw(ftatime ftbinary ftblk ftchr ftctime ftdir fteexec fteowned fteread ftewrite ftfile ftis ftlink ftmtime ftpipe ftrexec ftrowned ftrread ftrwrite ftsgid ftsize ftsock ftsuid ftsvtx fttext fttty ftzero); +$bits{$_}{1} = 'OPpHINT_STRICT_REFS' for qw(entersub multideref rv2av rv2cv rv2gv rv2hv rv2sv); +$bits{$_}{5} = 'OPpHUSH_VMSISH' for qw(dbstate nextstate); +$bits{$_}{6} = 'OPpINDEX_BOOLNEG' for qw(index rindex); +$bits{$_}{1} = 'OPpITER_REVERSED' for qw(enteriter iter); +$bits{$_}{7} = 'OPpLVALUE' for qw(leave leaveloop); +$bits{$_}{6} = 'OPpLVAL_DEFER' for qw(aelem helem multideref); +$bits{$_}{7} = 'OPpLVAL_INTRO' for qw(aelem aslice cond_expr delete emptyavhv enteriter entersub gvsv helem hslice list lvavref lvref lvrefslice multiconcat multideref padav padhv padrange padsv padsv_store pushmark refassign rv2av rv2gv rv2hv rv2sv split undef); +$bits{$_}{2} = 'OPpLVREF_ELEM' for qw(lvref refassign); +$bits{$_}{3} = 'OPpLVREF_ITER' for qw(lvref refassign); +$bits{$_}{3} = 'OPpMAYBE_LVSUB' for qw(aassign aelem akeys aslice av2arylen avhvswitch helem hslice keys kvaslice kvhslice multideref padav padhv pos rv2av rv2gv rv2hv substr values vec); +$bits{$_}{4} = 'OPpMAYBE_TRUEBOOL' for qw(blessed padhv ref rv2hv); +$bits{$_}{1} = 'OPpMETH_NO_BAREWORD_IO' for qw(method method_named method_redir method_redir_super method_super); +$bits{$_}{7} = 'OPpOFFBYONE' for qw(caller runcv wantarray); +$bits{$_}{5} = 'OPpOPEN_IN_CRLF' for qw(backtick open); +$bits{$_}{4} = 'OPpOPEN_IN_RAW' for qw(backtick open); +$bits{$_}{7} = 'OPpOPEN_OUT_CRLF' for qw(backtick open); +$bits{$_}{6} = 'OPpOPEN_OUT_RAW' for qw(backtick open); +$bits{$_}{6} = 'OPpOUR_INTRO' for qw(enteriter gvsv rv2av rv2hv rv2sv split); +$bits{$_}{6} = 'OPpPAD_STATE' for qw(emptyavhv lvavref lvref padav padhv padsv padsv_store pushmark refassign undef); +$bits{$_}{7} = 'OPpPV_IS_UTF8' for qw(dump goto last next redo); +$bits{$_}{6} = 'OPpREFCOUNTED' for qw(leave leaveeval leavesub leavesublv leavewrite); +$bits{$_}{2} = 'OPpSLICEWARNING' for qw(aslice hslice padav padhv rv2av rv2hv); +$bits{$_}{4} = 'OPpTARGET_MY' for qw(abs add atan2 ceil chmod chomp chown chr chroot concat cos crypt divide emptyavhv exec exp flock floor getpgrp getppid getpriority hex i_add i_divide i_modulo i_multiply i_negate i_subtract index int kill left_shift length link log mkdir modulo multiconcat multiply nbit_and nbit_or nbit_xor ncomplement negate oct ord pow push rand refaddr reftype rename right_shift rindex rmdir schomp scomplement setpgrp setpriority sin sleep sqrt srand stringify substr_left subtract symlink system time undef unlink unshift utime wait waitpid); +$bits{$_}{5} = 'OPpTRANS_COMPLEMENT' for qw(trans transr); +$bits{$_}{7} = 'OPpTRANS_DELETE' for qw(trans transr); +$bits{$_}{2} = 'OPpTRANS_IDENTICAL' for qw(trans transr); +$bits{$_}{3} = 'OPpTRANS_SQUASH' for qw(trans transr); +$bits{$_}{6} = 'OPpTRANS_USE_SVOP' for qw(trans transr); +$bits{$_}{5} = 'OPpTRUEBOOL' for qw(blessed grepwhile index length padav padhv pos ref rindex rv2av rv2hv subst); +$bits{$_}{2} = 'OPpUSEINT' for qw(bit_and bit_or bit_xor complement left_shift nbit_and nbit_or nbit_xor ncomplement right_shift sbit_and sbit_or sbit_xor); + +my @bf = ( + { + label => '-', + mask_def => 'OPpARG1_MASK', + bitmin => 0, + bitmax => 0, + bitmask => 1, + }, + { + label => '-', + mask_def => 'OPpARG2_MASK', + bitmin => 0, + bitmax => 1, + bitmask => 3, + }, + { + label => 'TRANS', + mask_def => 'OPpTRANS_MASK', + baseshift_def => 'OPpTRANS_SHIFT', + bitcount_def => 'OPpTRANS_BITS', + bitmin => 0, + bitmax => 1, + bitmask => 3, + enum => [ + 1, 'OPpTRANS_ONLY_UTF8_INVARIANTS', 'ONLY_UTF8_INVARIANTS', + 2, 'OPpTRANS_CAN_FORCE_UTF8', 'CAN_FORCE_UTF8', + 3, 'OPpTRANS_GROWS', 'GROWS', + ], + }, + { + label => 'offset', + mask_def => 'OPpAVHVSWITCH_MASK', + bitmin => 0, + bitmax => 1, + bitmask => 3, + }, + { + label => '-', + mask_def => 'OPpARG3_MASK', + bitmin => 0, + bitmax => 2, + bitmask => 7, + }, + { + label => '-', + mask_def => 'OPpARG4_MASK', + bitmin => 0, + bitmax => 3, + bitmask => 15, + }, + { + label => 'range', + mask_def => 'OPpPADRANGE_COUNTMASK', + bitcount_def => 'OPpPADRANGE_COUNTSHIFT', + bitmin => 0, + bitmax => 6, + bitmask => 127, + }, + { + label => 'key', + bitmin => 0, + bitmax => 7, + bitmask => 255, + }, + { + mask_def => 'OPpARGELEM_MASK', + bitmin => 1, + bitmax => 2, + bitmask => 6, + enum => [ + 0, 'OPpARGELEM_SV', 'SV', + 1, 'OPpARGELEM_AV', 'AV', + 2, 'OPpARGELEM_HV', 'HV', + ], + }, + { + mask_def => 'OPpDEREF', + bitmin => 4, + bitmax => 5, + bitmask => 48, + enum => [ + 1, 'OPpDEREF_AV', 'DREFAV', + 2, 'OPpDEREF_HV', 'DREFHV', + 3, 'OPpDEREF_SV', 'DREFSV', + ], + }, + { + mask_def => 'OPpLVREF_TYPE', + bitmin => 4, + bitmax => 5, + bitmask => 48, + enum => [ + 0, 'OPpLVREF_SV', 'SV', + 1, 'OPpLVREF_AV', 'AV', + 2, 'OPpLVREF_HV', 'HV', + 3, 'OPpLVREF_CV', 'CV', + ], + }, + { + label => 'TOKEN', + mask_def => 'OPpCONST_TOKEN_MASK', + baseshift_def => 'OPpCONST_TOKEN_SHIFT', + bitcount_def => 'OPpCONST_TOKEN_BITS', + bitmin => 6, + bitmax => 7, + bitmask => 192, + enum => [ + 1, 'OPpCONST_TOKEN_LINE', 'LINE', + 2, 'OPpCONST_TOKEN_FILE', 'FILE', + 3, 'OPpCONST_TOKEN_PACKAGE', 'PACKAGE', + ], + }, +); + +@{$bits{aassign}}{6,5,4,2,1,0} = ('OPpASSIGN_COMMON_SCALAR', 'OPpASSIGN_COMMON_RC1', 'OPpASSIGN_COMMON_AGG', 'OPpASSIGN_TRUEBOOL', $bf[1], $bf[1]); +$bits{abs}{0} = $bf[0]; +@{$bits{accept}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{add}}{1,0} = ($bf[1], $bf[1]); +$bits{aeach}{0} = $bf[0]; +@{$bits{aelem}}{5,4,1,0} = ($bf[9], $bf[9], $bf[1], $bf[1]); +@{$bits{aelemfast}}{7,6,5,4,3,2,1,0} = ($bf[7], $bf[7], $bf[7], $bf[7], $bf[7], $bf[7], $bf[7], $bf[7]); +@{$bits{aelemfast_lex}}{7,6,5,4,3,2,1,0} = ($bf[7], $bf[7], $bf[7], $bf[7], $bf[7], $bf[7], $bf[7], $bf[7]); +@{$bits{aelemfastlex_store}}{7,6,5,4,3,2,1,0} = ($bf[7], $bf[7], $bf[7], $bf[7], $bf[7], $bf[7], $bf[7], $bf[7]); +$bits{akeys}{0} = $bf[0]; +$bits{alarm}{0} = $bf[0]; +$bits{and}{0} = $bf[0]; +$bits{andassign}{0} = $bf[0]; +$bits{anonconst}{0} = $bf[0]; +@{$bits{anonhash}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{anonlist}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{anywhile}{0} = $bf[0]; +$bits{argcheck}{0} = $bf[0]; +@{$bits{argdefelem}}{7,6,0} = ('OPpARG_IF_UNDEF', 'OPpARG_IF_FALSE', $bf[0]); +@{$bits{argelem}}{2,1,0} = ($bf[8], $bf[8], $bf[0]); +@{$bits{atan2}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{av2arylen}{0} = $bf[0]; +$bits{avalues}{0} = $bf[0]; +@{$bits{avhvswitch}}{1,0} = ($bf[3], $bf[3]); +$bits{backtick}{0} = $bf[0]; +@{$bits{bind}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{binmode}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{bless}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{blessed}{0} = $bf[0]; +@{$bits{caller}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{catch}{0} = $bf[0]; +$bits{ceil}{0} = $bf[0]; +@{$bits{chdir}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{chmod}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{chomp}{0} = $bf[0]; +$bits{chop}{0} = $bf[0]; +@{$bits{chown}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{chr}{0} = $bf[0]; +$bits{chroot}{0} = $bf[0]; +@{$bits{close}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{closedir}{0} = $bf[0]; +$bits{cmpchain_and}{0} = $bf[0]; +$bits{cmpchain_dup}{0} = $bf[0]; +@{$bits{concat}}{6,1,0} = ('OPpCONCAT_NESTED', $bf[1], $bf[1]); +$bits{cond_expr}{0} = $bf[0]; +@{$bits{connect}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{const}}{7,6,5,4,3,2,1} = ($bf[11], $bf[11], 'OPpCONST_BARE', 'OPpCONST_ENTERED', 'OPpCONST_STRICT', 'OPpCONST_SHORTCIRCUIT', 'OPpCONST_NOVER'); +@{$bits{coreargs}}{7,6,1,0} = ('OPpCOREARGS_PUSHMARK', 'OPpCOREARGS_SCALARMOD', 'OPpCOREARGS_DEREF2', 'OPpCOREARGS_DEREF1'); +$bits{cos}{0} = $bf[0]; +@{$bits{crypt}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{dbmclose}{0} = $bf[0]; +@{$bits{dbmopen}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{defined}{0} = $bf[0]; +@{$bits{delete}}{6,5,0} = ('OPpSLICE', 'OPpKVSLICE', $bf[0]); +@{$bits{die}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{divide}}{1,0} = ($bf[1], $bf[1]); +$bits{dofile}{0} = $bf[0]; +$bits{dor}{0} = $bf[0]; +$bits{dorassign}{0} = $bf[0]; +$bits{dump}{0} = $bf[0]; +$bits{each}{0} = $bf[0]; +@{$bits{emptyavhv}}{5,3,2,1,0} = ('OPpEMPTYAVHV_IS_HV', $bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{entereval}}{6,5,4,3,2,1,0} = ('OPpEVAL_EVALSV', 'OPpEVAL_RE_REPARSING', 'OPpEVAL_COPHH', 'OPpEVAL_BYTES', 'OPpEVAL_UNICODE', 'OPpEVAL_HAS_HH', $bf[0]); +$bits{entergiven}{0} = $bf[0]; +$bits{enteriter}{3} = 'OPpITER_DEF'; +@{$bits{entersub}}{5,4,0} = ($bf[9], $bf[9], 'OPpENTERSUB_INARGS'); +$bits{entertry}{0} = $bf[0]; +$bits{entertrycatch}{0} = $bf[0]; +$bits{enterwhen}{0} = $bf[0]; +@{$bits{enterwrite}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{eof}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{eq}}{1,0} = ($bf[1], $bf[1]); +@{$bits{exec}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{exists}}{6,0} = ('OPpEXISTS_SUB', $bf[0]); +@{$bits{exit}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{exp}{0} = $bf[0]; +$bits{fc}{0} = $bf[0]; +@{$bits{fcntl}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{fileno}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{flip}{0} = $bf[0]; +@{$bits{flock}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{floor}{0} = $bf[0]; +$bits{flop}{0} = $bf[0]; +@{$bits{formline}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{ftatime}{0} = $bf[0]; +$bits{ftbinary}{0} = $bf[0]; +$bits{ftblk}{0} = $bf[0]; +$bits{ftchr}{0} = $bf[0]; +$bits{ftctime}{0} = $bf[0]; +$bits{ftdir}{0} = $bf[0]; +$bits{fteexec}{0} = $bf[0]; +$bits{fteowned}{0} = $bf[0]; +$bits{fteread}{0} = $bf[0]; +$bits{ftewrite}{0} = $bf[0]; +$bits{ftfile}{0} = $bf[0]; +$bits{ftis}{0} = $bf[0]; +$bits{ftlink}{0} = $bf[0]; +$bits{ftmtime}{0} = $bf[0]; +$bits{ftpipe}{0} = $bf[0]; +$bits{ftrexec}{0} = $bf[0]; +$bits{ftrowned}{0} = $bf[0]; +$bits{ftrread}{0} = $bf[0]; +$bits{ftrwrite}{0} = $bf[0]; +$bits{ftsgid}{0} = $bf[0]; +$bits{ftsize}{0} = $bf[0]; +$bits{ftsock}{0} = $bf[0]; +$bits{ftsuid}{0} = $bf[0]; +$bits{ftsvtx}{0} = $bf[0]; +$bits{fttext}{0} = $bf[0]; +$bits{fttty}{0} = $bf[0]; +$bits{ftzero}{0} = $bf[0]; +@{$bits{ge}}{1,0} = ($bf[1], $bf[1]); +@{$bits{gelem}}{1,0} = ($bf[1], $bf[1]); +@{$bits{getc}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{getpeername}{0} = $bf[0]; +@{$bits{getpgrp}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{getpriority}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{getsockname}{0} = $bf[0]; +$bits{ggrgid}{0} = $bf[0]; +$bits{ggrnam}{0} = $bf[0]; +@{$bits{ghbyaddr}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{ghbyname}{0} = $bf[0]; +@{$bits{glob}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{gmtime}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{gnbyaddr}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{gnbyname}{0} = $bf[0]; +$bits{goto}{0} = $bf[0]; +$bits{gpbyname}{0} = $bf[0]; +@{$bits{gpbynumber}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{gpwnam}{0} = $bf[0]; +$bits{gpwuid}{0} = $bf[0]; +$bits{grepstart}{0} = $bf[0]; +$bits{grepwhile}{0} = $bf[0]; +@{$bits{gsbyname}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{gsbyport}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{gsockopt}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{gt}}{1,0} = ($bf[1], $bf[1]); +$bits{gv}{5} = 'OPpEARLY_CV'; +@{$bits{helem}}{5,4,1,0} = ($bf[9], $bf[9], $bf[1], $bf[1]); +@{$bits{helemexistsor}}{7,0} = ('OPpHELEMEXISTSOR_DELETE', $bf[0]); +$bits{hex}{0} = $bf[0]; +@{$bits{i_add}}{1,0} = ($bf[1], $bf[1]); +@{$bits{i_divide}}{1,0} = ($bf[1], $bf[1]); +@{$bits{i_eq}}{1,0} = ($bf[1], $bf[1]); +@{$bits{i_ge}}{1,0} = ($bf[1], $bf[1]); +@{$bits{i_gt}}{1,0} = ($bf[1], $bf[1]); +@{$bits{i_le}}{1,0} = ($bf[1], $bf[1]); +@{$bits{i_lt}}{1,0} = ($bf[1], $bf[1]); +@{$bits{i_modulo}}{1,0} = ($bf[1], $bf[1]); +@{$bits{i_multiply}}{1,0} = ($bf[1], $bf[1]); +@{$bits{i_ncmp}}{1,0} = ($bf[1], $bf[1]); +@{$bits{i_ne}}{1,0} = ($bf[1], $bf[1]); +$bits{i_negate}{0} = $bf[0]; +$bits{i_postdec}{0} = $bf[0]; +$bits{i_postinc}{0} = $bf[0]; +$bits{i_predec}{0} = $bf[0]; +$bits{i_preinc}{0} = $bf[0]; +@{$bits{i_subtract}}{1,0} = ($bf[1], $bf[1]); +@{$bits{index}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{initfield}}{2,1,0} = ('OPpINITFIELD_HV', 'OPpINITFIELD_AV', $bf[0]); +$bits{int}{0} = $bf[0]; +@{$bits{ioctl}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{is_bool}{0} = $bf[0]; +$bits{is_tainted}{0} = $bf[0]; +$bits{is_weak}{0} = $bf[0]; +@{$bits{isa}}{1,0} = ($bf[1], $bf[1]); +$bits{iter}{2} = 'OPpITER_INDEXED'; +@{$bits{join}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{keys}{0} = $bf[0]; +@{$bits{kill}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{last}{0} = $bf[0]; +$bits{lc}{0} = $bf[0]; +$bits{lcfirst}{0} = $bf[0]; +@{$bits{le}}{1,0} = ($bf[1], $bf[1]); +$bits{leaveeval}{0} = $bf[0]; +$bits{leavegiven}{0} = $bf[0]; +@{$bits{leaveloop}}{1,0} = ($bf[1], $bf[1]); +$bits{leavesub}{0} = $bf[0]; +$bits{leavesublv}{0} = $bf[0]; +$bits{leavewhen}{0} = $bf[0]; +$bits{leavewrite}{0} = $bf[0]; +$bits{length}{0} = $bf[0]; +@{$bits{link}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{list}{6} = 'OPpLIST_GUESSED'; +@{$bits{listen}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{localtime}{0} = $bf[0]; +$bits{lock}{0} = $bf[0]; +$bits{log}{0} = $bf[0]; +@{$bits{lslice}}{1,0} = ($bf[1], $bf[1]); +$bits{lstat}{0} = $bf[0]; +@{$bits{lt}}{1,0} = ($bf[1], $bf[1]); +$bits{lvavref}{0} = $bf[0]; +@{$bits{lvref}}{5,4,0} = ($bf[10], $bf[10], $bf[0]); +$bits{mapstart}{0} = $bf[0]; +$bits{mapwhile}{0} = $bf[0]; +$bits{method}{0} = $bf[0]; +$bits{method_named}{0} = $bf[0]; +$bits{method_redir}{0} = $bf[0]; +$bits{method_redir_super}{0} = $bf[0]; +$bits{method_super}{0} = $bf[0]; +@{$bits{methstart}}{7,0} = ('OPpINITFIELDS', $bf[0]); +@{$bits{mkdir}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{modulo}}{1,0} = ($bf[1], $bf[1]); +@{$bits{msgctl}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{msgget}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{msgrcv}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{msgsnd}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{multiconcat}}{6,5,3,0} = ('OPpMULTICONCAT_APPEND', 'OPpMULTICONCAT_FAKE', 'OPpMULTICONCAT_STRINGIFY', $bf[0]); +@{$bits{multideref}}{5,4,0} = ('OPpMULTIDEREF_DELETE', 'OPpMULTIDEREF_EXISTS', $bf[0]); +@{$bits{multiply}}{1,0} = ($bf[1], $bf[1]); +@{$bits{ncmp}}{1,0} = ($bf[1], $bf[1]); +@{$bits{ne}}{1,0} = ($bf[1], $bf[1]); +$bits{negate}{0} = $bf[0]; +$bits{next}{0} = $bf[0]; +$bits{not}{0} = $bf[0]; +$bits{oct}{0} = $bf[0]; +$bits{once}{0} = $bf[0]; +@{$bits{open}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{open_dir}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{or}{0} = $bf[0]; +$bits{orassign}{0} = $bf[0]; +$bits{ord}{0} = $bf[0]; +@{$bits{pack}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{padhv}{0} = 'OPpPADHV_ISKEYS'; +@{$bits{padrange}}{6,5,4,3,2,1,0} = ($bf[6], $bf[6], $bf[6], $bf[6], $bf[6], $bf[6], $bf[6]); +@{$bits{padsv}}{5,4} = ($bf[9], $bf[9]); +$bits{padsv_store}{0} = $bf[0]; +@{$bits{pipe_op}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{pop}{0} = $bf[0]; +$bits{pos}{0} = $bf[0]; +$bits{postdec}{0} = $bf[0]; +$bits{postinc}{0} = $bf[0]; +@{$bits{pow}}{1,0} = ($bf[1], $bf[1]); +$bits{predec}{0} = $bf[0]; +$bits{preinc}{0} = $bf[0]; +$bits{prototype}{0} = $bf[0]; +@{$bits{push}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{pushdefer}}{7,0} = ('OPpDEFER_FINALLY', $bf[0]); +$bits{quotemeta}{0} = $bf[0]; +@{$bits{rand}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{range}{0} = $bf[0]; +@{$bits{read}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{readdir}{0} = $bf[0]; +$bits{readline}{0} = $bf[0]; +$bits{readlink}{0} = $bf[0]; +@{$bits{recv}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{redo}{0} = $bf[0]; +$bits{ref}{0} = $bf[0]; +$bits{refaddr}{0} = $bf[0]; +@{$bits{refassign}}{5,4,1,0} = ($bf[10], $bf[10], $bf[1], $bf[1]); +$bits{refgen}{0} = $bf[0]; +$bits{reftype}{0} = $bf[0]; +$bits{regcmaybe}{0} = $bf[0]; +$bits{regcomp}{0} = $bf[0]; +$bits{regcreset}{0} = $bf[0]; +@{$bits{rename}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{repeat}}{6,1,0} = ('OPpREPEAT_DOLIST', $bf[1], $bf[1]); +$bits{require}{0} = $bf[0]; +@{$bits{reset}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{reverse}}{3,0} = ('OPpREVERSE_INPLACE', $bf[0]); +$bits{rewinddir}{0} = $bf[0]; +@{$bits{rindex}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{rmdir}{0} = $bf[0]; +$bits{rv2av}{0} = $bf[0]; +@{$bits{rv2cv}}{7,5,0} = ('OPpENTERSUB_NOPAREN', 'OPpMAY_RETURN_CONSTANT', $bf[0]); +@{$bits{rv2gv}}{6,5,4,2,0} = ('OPpALLOW_FAKE', $bf[9], $bf[9], 'OPpDONT_INIT_GV', $bf[0]); +$bits{rv2hv}{0} = 'OPpRV2HV_ISKEYS'; +@{$bits{rv2sv}}{5,4,0} = ($bf[9], $bf[9], $bf[0]); +@{$bits{sassign}}{7,6,1,0} = ('OPpASSIGN_CV_TO_GV', 'OPpASSIGN_BACKWARDS', $bf[1], $bf[1]); +$bits{scalar}{0} = $bf[0]; +$bits{schomp}{0} = $bf[0]; +$bits{schop}{0} = $bf[0]; +@{$bits{scmp}}{1,0} = ($bf[1], $bf[1]); +$bits{scomplement}{0} = $bf[0]; +@{$bits{seek}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{seekdir}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{select}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{semctl}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{semget}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{semop}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{send}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{seq}}{1,0} = ($bf[1], $bf[1]); +@{$bits{setpgrp}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{setpriority}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{sge}}{1,0} = ($bf[1], $bf[1]); +@{$bits{sgt}}{1,0} = ($bf[1], $bf[1]); +$bits{shift}{0} = $bf[0]; +@{$bits{shmctl}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{shmget}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{shmread}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{shmwrite}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{shostent}{0} = $bf[0]; +@{$bits{shutdown}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{sin}{0} = $bf[0]; +@{$bits{sle}}{1,0} = ($bf[1], $bf[1]); +@{$bits{sleep}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{slt}}{1,0} = ($bf[1], $bf[1]); +@{$bits{smartmatch}}{1,0} = ($bf[1], $bf[1]); +@{$bits{sne}}{1,0} = ($bf[1], $bf[1]); +$bits{snetent}{0} = $bf[0]; +@{$bits{socket}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{sockpair}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{sort}}{4,3,2,1,0} = ('OPpSORT_DESCEND', 'OPpSORT_INPLACE', 'OPpSORT_REVERSE', 'OPpSORT_INTEGER', 'OPpSORT_NUMERIC'); +@{$bits{splice}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{split}}{4,3,2} = ('OPpSPLIT_ASSIGN', 'OPpSPLIT_LEX', 'OPpSPLIT_IMPLIM'); +@{$bits{sprintf}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{sprotoent}{0} = $bf[0]; +$bits{sqrt}{0} = $bf[0]; +@{$bits{srand}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{srefgen}{0} = $bf[0]; +@{$bits{sselect}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{sservent}{0} = $bf[0]; +@{$bits{ssockopt}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{stat}{0} = $bf[0]; +@{$bits{stringify}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{study}{0} = $bf[0]; +$bits{substcont}{0} = $bf[0]; +@{$bits{substr}}{4,2,1,0} = ('OPpSUBSTR_REPL_FIRST', $bf[4], $bf[4], $bf[4]); +@{$bits{substr_left}}{2,1,0} = ($bf[4], $bf[4], $bf[4]); +@{$bits{subtract}}{1,0} = ($bf[1], $bf[1]); +@{$bits{symlink}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{syscall}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{sysopen}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{sysread}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{sysseek}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{system}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{syswrite}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{tell}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{telldir}{0} = $bf[0]; +@{$bits{tie}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{tied}{0} = $bf[0]; +@{$bits{trans}}{1,0} = ($bf[2], $bf[2]); +@{$bits{transr}}{1,0} = ($bf[2], $bf[2]); +@{$bits{truncate}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{uc}{0} = $bf[0]; +$bits{ucfirst}{0} = $bf[0]; +@{$bits{umask}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{undef}}{5,0} = ('OPpUNDEF_KEEP_PV', $bf[0]); +@{$bits{unlink}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{unpack}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{unshift}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{untie}{0} = $bf[0]; +$bits{unweaken}{0} = $bf[0]; +@{$bits{utime}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{values}{0} = $bf[0]; +@{$bits{vec}}{1,0} = ($bf[1], $bf[1]); +@{$bits{waitpid}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +@{$bits{warn}}{3,2,1,0} = ($bf[5], $bf[5], $bf[5], $bf[5]); +$bits{weaken}{0} = $bf[0]; +@{$bits{xor}}{1,0} = ($bf[1], $bf[1]); + + +our %defines = ( + OPpALLOW_FAKE => 64, + OPpARG1_MASK => 1, + OPpARG2_MASK => 3, + OPpARG3_MASK => 7, + OPpARG4_MASK => 15, + OPpARGELEM_AV => 2, + OPpARGELEM_HV => 4, + OPpARGELEM_MASK => 6, + OPpARGELEM_SV => 0, + OPpARG_IF_FALSE => 64, + OPpARG_IF_UNDEF => 128, + OPpASSIGN_BACKWARDS => 64, + OPpASSIGN_COMMON_AGG => 16, + OPpASSIGN_COMMON_RC1 => 32, + OPpASSIGN_COMMON_SCALAR => 64, + OPpASSIGN_CV_TO_GV => 128, + OPpASSIGN_TRUEBOOL => 4, + OPpAVHVSWITCH_MASK => 3, + OPpCONCAT_NESTED => 64, + OPpCONST_BARE => 32, + OPpCONST_ENTERED => 16, + OPpCONST_NOVER => 2, + OPpCONST_SHORTCIRCUIT => 4, + OPpCONST_STRICT => 8, + OPpCONST_TOKEN_BITS => 2, + OPpCONST_TOKEN_FILE => 128, + OPpCONST_TOKEN_LINE => 64, + OPpCONST_TOKEN_MASK => 192, + OPpCONST_TOKEN_PACKAGE => 192, + OPpCONST_TOKEN_SHIFT => 6, + OPpCOREARGS_DEREF1 => 1, + OPpCOREARGS_DEREF2 => 2, + OPpCOREARGS_PUSHMARK => 128, + OPpCOREARGS_SCALARMOD => 64, + OPpDEFER_FINALLY => 128, + OPpDEREF => 48, + OPpDEREF_AV => 16, + OPpDEREF_HV => 32, + OPpDEREF_SV => 48, + OPpDONT_INIT_GV => 4, + OPpEARLY_CV => 32, + OPpEMPTYAVHV_IS_HV => 32, + OPpENTERSUB_AMPER => 8, + OPpENTERSUB_DB => 64, + OPpENTERSUB_HASTARG => 4, + OPpENTERSUB_INARGS => 1, + OPpENTERSUB_NOPAREN => 128, + OPpEVAL_BYTES => 8, + OPpEVAL_COPHH => 16, + OPpEVAL_EVALSV => 64, + OPpEVAL_HAS_HH => 2, + OPpEVAL_RE_REPARSING => 32, + OPpEVAL_UNICODE => 4, + OPpEXISTS_SUB => 64, + OPpFLIP_LINENUM => 64, + OPpFT_ACCESS => 2, + OPpFT_AFTER_t => 16, + OPpFT_STACKED => 4, + OPpFT_STACKING => 8, + OPpHELEMEXISTSOR_DELETE => 128, + OPpHINT_STRICT_REFS => 2, + OPpHUSH_VMSISH => 32, + OPpINDEX_BOOLNEG => 64, + OPpINITFIELDS => 128, + OPpINITFIELD_AV => 2, + OPpINITFIELD_HV => 4, + OPpITER_DEF => 8, + OPpITER_INDEXED => 4, + OPpITER_REVERSED => 2, + OPpKVSLICE => 32, + OPpLIST_GUESSED => 64, + OPpLVALUE => 128, + OPpLVAL_DEFER => 64, + OPpLVAL_INTRO => 128, + OPpLVREF_AV => 16, + OPpLVREF_CV => 48, + OPpLVREF_ELEM => 4, + OPpLVREF_HV => 32, + OPpLVREF_ITER => 8, + OPpLVREF_SV => 0, + OPpLVREF_TYPE => 48, + OPpMAYBE_LVSUB => 8, + OPpMAYBE_TRUEBOOL => 16, + OPpMAY_RETURN_CONSTANT => 32, + OPpMETH_NO_BAREWORD_IO => 2, + OPpMULTICONCAT_APPEND => 64, + OPpMULTICONCAT_FAKE => 32, + OPpMULTICONCAT_STRINGIFY => 8, + OPpMULTIDEREF_DELETE => 32, + OPpMULTIDEREF_EXISTS => 16, + OPpOFFBYONE => 128, + OPpOPEN_IN_CRLF => 32, + OPpOPEN_IN_RAW => 16, + OPpOPEN_OUT_CRLF => 128, + OPpOPEN_OUT_RAW => 64, + OPpOUR_INTRO => 64, + OPpPADHV_ISKEYS => 1, + OPpPADRANGE_COUNTMASK => 127, + OPpPADRANGE_COUNTSHIFT => 7, + OPpPAD_STATE => 64, + OPpPV_IS_UTF8 => 128, + OPpREFCOUNTED => 64, + OPpREPEAT_DOLIST => 64, + OPpREVERSE_INPLACE => 8, + OPpRV2HV_ISKEYS => 1, + OPpSLICE => 64, + OPpSLICEWARNING => 4, + OPpSORT_DESCEND => 16, + OPpSORT_INPLACE => 8, + OPpSORT_INTEGER => 2, + OPpSORT_NUMERIC => 1, + OPpSORT_REVERSE => 4, + OPpSPLIT_ASSIGN => 16, + OPpSPLIT_IMPLIM => 4, + OPpSPLIT_LEX => 8, + OPpSUBSTR_REPL_FIRST => 16, + OPpTARGET_MY => 16, + OPpTRANS_BITS => 2, + OPpTRANS_CAN_FORCE_UTF8 => 2, + OPpTRANS_COMPLEMENT => 32, + OPpTRANS_DELETE => 128, + OPpTRANS_GROWS => 3, + OPpTRANS_IDENTICAL => 4, + OPpTRANS_MASK => 3, + OPpTRANS_ONLY_UTF8_INVARIANTS => 1, + OPpTRANS_SHIFT => 0, + OPpTRANS_SQUASH => 8, + OPpTRANS_USE_SVOP => 64, + OPpTRUEBOOL => 32, + OPpUNDEF_KEEP_PV => 32, + OPpUSEINT => 4, +); + +our %labels = ( + OPpALLOW_FAKE => 'FAKE', + OPpARGELEM_AV => 'AV', + OPpARGELEM_HV => 'HV', + OPpARGELEM_SV => 'SV', + OPpARG_IF_FALSE => 'IF_FALSE', + OPpARG_IF_UNDEF => 'IF_UNDEF', + OPpASSIGN_BACKWARDS => 'BKWARD', + OPpASSIGN_COMMON_AGG => 'COM_AGG', + OPpASSIGN_COMMON_RC1 => 'COM_RC1', + OPpASSIGN_COMMON_SCALAR => 'COM_SCALAR', + OPpASSIGN_CV_TO_GV => 'CV2GV', + OPpASSIGN_TRUEBOOL => 'BOOL', + OPpCONCAT_NESTED => 'NESTED', + OPpCONST_BARE => 'BARE', + OPpCONST_ENTERED => 'ENTERED', + OPpCONST_NOVER => 'NOVER', + OPpCONST_SHORTCIRCUIT => 'SHORT', + OPpCONST_STRICT => 'STRICT', + OPpCONST_TOKEN_FILE => 'FILE', + OPpCONST_TOKEN_LINE => 'LINE', + OPpCONST_TOKEN_PACKAGE => 'PACKAGE', + OPpCOREARGS_DEREF1 => 'DEREF1', + OPpCOREARGS_DEREF2 => 'DEREF2', + OPpCOREARGS_PUSHMARK => 'MARK', + OPpCOREARGS_SCALARMOD => '$MOD', + OPpDEFER_FINALLY => 'FINALLY', + OPpDEREF_AV => 'DREFAV', + OPpDEREF_HV => 'DREFHV', + OPpDEREF_SV => 'DREFSV', + OPpDONT_INIT_GV => 'NOINIT', + OPpEARLY_CV => 'EARLYCV', + OPpEMPTYAVHV_IS_HV => 'ANONHASH', + OPpENTERSUB_AMPER => 'AMPER', + OPpENTERSUB_DB => 'DBG', + OPpENTERSUB_HASTARG => 'TARG', + OPpENTERSUB_INARGS => 'INARGS', + OPpENTERSUB_NOPAREN => 'NO()', + OPpEVAL_BYTES => 'BYTES', + OPpEVAL_COPHH => 'COPHH', + OPpEVAL_EVALSV => 'EVALSV', + OPpEVAL_HAS_HH => 'HAS_HH', + OPpEVAL_RE_REPARSING => 'REPARSE', + OPpEVAL_UNICODE => 'UNI', + OPpEXISTS_SUB => 'SUB', + OPpFLIP_LINENUM => 'LINENUM', + OPpFT_ACCESS => 'FTACCESS', + OPpFT_AFTER_t => 'FTAFTERt', + OPpFT_STACKED => 'FTSTACKED', + OPpFT_STACKING => 'FTSTACKING', + OPpHELEMEXISTSOR_DELETE => 'DELETE', + OPpHINT_STRICT_REFS => 'STRICT', + OPpHUSH_VMSISH => 'HUSH', + OPpINDEX_BOOLNEG => 'NEG', + OPpINITFIELDS => 'INITFIELDS', + OPpINITFIELD_AV => 'INITFIELD_AV', + OPpINITFIELD_HV => 'INITFIELD_HV', + OPpITER_DEF => 'DEF', + OPpITER_INDEXED => 'INDEXED', + OPpITER_REVERSED => 'REVERSED', + OPpKVSLICE => 'KVSLICE', + OPpLIST_GUESSED => 'GUESSED', + OPpLVALUE => 'LV', + OPpLVAL_DEFER => 'LVDEFER', + OPpLVAL_INTRO => 'LVINTRO', + OPpLVREF_AV => 'AV', + OPpLVREF_CV => 'CV', + OPpLVREF_ELEM => 'ELEM', + OPpLVREF_HV => 'HV', + OPpLVREF_ITER => 'ITER', + OPpLVREF_SV => 'SV', + OPpMAYBE_LVSUB => 'LVSUB', + OPpMAYBE_TRUEBOOL => 'BOOL?', + OPpMAY_RETURN_CONSTANT => 'CONST', + OPpMETH_NO_BAREWORD_IO => 'NO_BAREWORD_IO', + OPpMULTICONCAT_APPEND => 'APPEND', + OPpMULTICONCAT_FAKE => 'FAKE', + OPpMULTICONCAT_STRINGIFY => 'STRINGIFY', + OPpMULTIDEREF_DELETE => 'DELETE', + OPpMULTIDEREF_EXISTS => 'EXISTS', + OPpOFFBYONE => '+1', + OPpOPEN_IN_CRLF => 'INCR', + OPpOPEN_IN_RAW => 'INBIN', + OPpOPEN_OUT_CRLF => 'OUTCR', + OPpOPEN_OUT_RAW => 'OUTBIN', + OPpOUR_INTRO => 'OURINTR', + OPpPADHV_ISKEYS => 'KEYS', + OPpPAD_STATE => 'STATE', + OPpPV_IS_UTF8 => 'UTF', + OPpREFCOUNTED => 'REFC', + OPpREPEAT_DOLIST => 'DOLIST', + OPpREVERSE_INPLACE => 'INPLACE', + OPpRV2HV_ISKEYS => 'KEYS', + OPpSLICE => 'SLICE', + OPpSLICEWARNING => 'SLICEWARN', + OPpSORT_DESCEND => 'DESC', + OPpSORT_INPLACE => 'INPLACE', + OPpSORT_INTEGER => 'INT', + OPpSORT_NUMERIC => 'NUM', + OPpSORT_REVERSE => 'REV', + OPpSPLIT_ASSIGN => 'ASSIGN', + OPpSPLIT_IMPLIM => 'IMPLIM', + OPpSPLIT_LEX => 'LEX', + OPpSUBSTR_REPL_FIRST => 'REPL1ST', + OPpTARGET_MY => 'TARGMY', + OPpTRANS_CAN_FORCE_UTF8 => 'CAN_FORCE_UTF8', + OPpTRANS_COMPLEMENT => 'COMPL', + OPpTRANS_DELETE => 'DEL', + OPpTRANS_GROWS => 'GROWS', + OPpTRANS_IDENTICAL => 'IDENT', + OPpTRANS_ONLY_UTF8_INVARIANTS => 'ONLY_UTF8_INVARIANTS', + OPpTRANS_SQUASH => 'SQUASH', + OPpTRANS_USE_SVOP => 'USE_SVOP', + OPpTRUEBOOL => 'BOOL', + OPpUNDEF_KEEP_PV => 'KEEP_PV', + OPpUSEINT => 'USEINT', +); + + +our %ops_using = ( + OPpALLOW_FAKE => [qw(rv2gv)], + OPpARG_IF_FALSE => [qw(argdefelem)], + OPpASSIGN_BACKWARDS => [qw(sassign)], + OPpASSIGN_COMMON_AGG => [qw(aassign)], + OPpCONCAT_NESTED => [qw(concat)], + OPpCONST_BARE => [qw(const)], + OPpCOREARGS_DEREF1 => [qw(coreargs)], + OPpDEFER_FINALLY => [qw(pushdefer)], + OPpEARLY_CV => [qw(gv)], + OPpEMPTYAVHV_IS_HV => [qw(emptyavhv)], + OPpENTERSUB_AMPER => [qw(entersub rv2cv)], + OPpENTERSUB_HASTARG => [qw(ceil entersub floor goto refaddr reftype rv2cv)], + OPpENTERSUB_INARGS => [qw(entersub)], + OPpENTERSUB_NOPAREN => [qw(rv2cv)], + OPpEVAL_BYTES => [qw(entereval)], + OPpEXISTS_SUB => [qw(exists)], + OPpFLIP_LINENUM => [qw(flip flop)], + OPpFT_ACCESS => [qw(fteexec fteread ftewrite ftrexec ftrread ftrwrite)], + OPpFT_AFTER_t => [qw(ftatime ftbinary ftblk ftchr ftctime ftdir fteexec fteowned fteread ftewrite ftfile ftis ftlink ftmtime ftpipe ftrexec ftrowned ftrread ftrwrite ftsgid ftsize ftsock ftsuid ftsvtx fttext fttty ftzero)], + OPpHELEMEXISTSOR_DELETE => [qw(helemexistsor)], + OPpHINT_STRICT_REFS => [qw(entersub multideref rv2av rv2cv rv2gv rv2hv rv2sv)], + OPpHUSH_VMSISH => [qw(dbstate nextstate)], + OPpINDEX_BOOLNEG => [qw(index rindex)], + OPpINITFIELDS => [qw(methstart)], + OPpINITFIELD_AV => [qw(initfield)], + OPpITER_DEF => [qw(enteriter)], + OPpITER_INDEXED => [qw(iter)], + OPpITER_REVERSED => [qw(enteriter iter)], + OPpKVSLICE => [qw(delete)], + OPpLIST_GUESSED => [qw(list)], + OPpLVALUE => [qw(leave leaveloop)], + OPpLVAL_DEFER => [qw(aelem helem multideref)], + OPpLVAL_INTRO => [qw(aelem aslice cond_expr delete emptyavhv enteriter entersub gvsv helem hslice list lvavref lvref lvrefslice multiconcat multideref padav padhv padrange padsv padsv_store pushmark refassign rv2av rv2gv rv2hv rv2sv split undef)], + OPpLVREF_ELEM => [qw(lvref refassign)], + OPpMAYBE_LVSUB => [qw(aassign aelem akeys aslice av2arylen avhvswitch helem hslice keys kvaslice kvhslice multideref padav padhv pos rv2av rv2gv rv2hv substr values vec)], + OPpMAYBE_TRUEBOOL => [qw(blessed padhv ref rv2hv)], + OPpMETH_NO_BAREWORD_IO => [qw(method method_named method_redir method_redir_super method_super)], + OPpMULTICONCAT_APPEND => [qw(multiconcat)], + OPpMULTIDEREF_DELETE => [qw(multideref)], + OPpOFFBYONE => [qw(caller runcv wantarray)], + OPpOPEN_IN_CRLF => [qw(backtick open)], + OPpOUR_INTRO => [qw(enteriter gvsv rv2av rv2hv rv2sv split)], + OPpPADHV_ISKEYS => [qw(padhv)], + OPpPAD_STATE => [qw(emptyavhv lvavref lvref padav padhv padsv padsv_store pushmark refassign undef)], + OPpPV_IS_UTF8 => [qw(dump goto last next redo)], + OPpREFCOUNTED => [qw(leave leaveeval leavesub leavesublv leavewrite)], + OPpREPEAT_DOLIST => [qw(repeat)], + OPpREVERSE_INPLACE => [qw(reverse)], + OPpRV2HV_ISKEYS => [qw(rv2hv)], + OPpSLICEWARNING => [qw(aslice hslice padav padhv rv2av rv2hv)], + OPpSORT_DESCEND => [qw(sort)], + OPpSPLIT_ASSIGN => [qw(split)], + OPpSUBSTR_REPL_FIRST => [qw(substr)], + OPpTARGET_MY => [qw(abs add atan2 ceil chmod chomp chown chr chroot concat cos crypt divide emptyavhv exec exp flock floor getpgrp getppid getpriority hex i_add i_divide i_modulo i_multiply i_negate i_subtract index int kill left_shift length link log mkdir modulo multiconcat multiply nbit_and nbit_or nbit_xor ncomplement negate oct ord pow push rand refaddr reftype rename right_shift rindex rmdir schomp scomplement setpgrp setpriority sin sleep sqrt srand stringify substr_left subtract symlink system time undef unlink unshift utime wait waitpid)], + OPpTRANS_COMPLEMENT => [qw(trans transr)], + OPpTRUEBOOL => [qw(blessed grepwhile index length padav padhv pos ref rindex rv2av rv2hv subst)], + OPpUNDEF_KEEP_PV => [qw(undef)], + OPpUSEINT => [qw(bit_and bit_or bit_xor complement left_shift nbit_and nbit_or nbit_xor ncomplement right_shift sbit_and sbit_or sbit_xor)], +); + +$ops_using{OPpARG_IF_UNDEF} = $ops_using{OPpARG_IF_FALSE}; +$ops_using{OPpASSIGN_COMMON_RC1} = $ops_using{OPpASSIGN_COMMON_AGG}; +$ops_using{OPpASSIGN_COMMON_SCALAR} = $ops_using{OPpASSIGN_COMMON_AGG}; +$ops_using{OPpASSIGN_CV_TO_GV} = $ops_using{OPpASSIGN_BACKWARDS}; +$ops_using{OPpASSIGN_TRUEBOOL} = $ops_using{OPpASSIGN_COMMON_AGG}; +$ops_using{OPpCONST_ENTERED} = $ops_using{OPpCONST_BARE}; +$ops_using{OPpCONST_NOVER} = $ops_using{OPpCONST_BARE}; +$ops_using{OPpCONST_SHORTCIRCUIT} = $ops_using{OPpCONST_BARE}; +$ops_using{OPpCONST_STRICT} = $ops_using{OPpCONST_BARE}; +$ops_using{OPpCOREARGS_DEREF2} = $ops_using{OPpCOREARGS_DEREF1}; +$ops_using{OPpCOREARGS_PUSHMARK} = $ops_using{OPpCOREARGS_DEREF1}; +$ops_using{OPpCOREARGS_SCALARMOD} = $ops_using{OPpCOREARGS_DEREF1}; +$ops_using{OPpDONT_INIT_GV} = $ops_using{OPpALLOW_FAKE}; +$ops_using{OPpENTERSUB_DB} = $ops_using{OPpENTERSUB_AMPER}; +$ops_using{OPpEVAL_COPHH} = $ops_using{OPpEVAL_BYTES}; +$ops_using{OPpEVAL_EVALSV} = $ops_using{OPpEVAL_BYTES}; +$ops_using{OPpEVAL_HAS_HH} = $ops_using{OPpEVAL_BYTES}; +$ops_using{OPpEVAL_RE_REPARSING} = $ops_using{OPpEVAL_BYTES}; +$ops_using{OPpEVAL_UNICODE} = $ops_using{OPpEVAL_BYTES}; +$ops_using{OPpFT_STACKED} = $ops_using{OPpFT_AFTER_t}; +$ops_using{OPpFT_STACKING} = $ops_using{OPpFT_AFTER_t}; +$ops_using{OPpINITFIELD_HV} = $ops_using{OPpINITFIELD_AV}; +$ops_using{OPpLVREF_ITER} = $ops_using{OPpLVREF_ELEM}; +$ops_using{OPpMAY_RETURN_CONSTANT} = $ops_using{OPpENTERSUB_NOPAREN}; +$ops_using{OPpMULTICONCAT_FAKE} = $ops_using{OPpMULTICONCAT_APPEND}; +$ops_using{OPpMULTICONCAT_STRINGIFY} = $ops_using{OPpMULTICONCAT_APPEND}; +$ops_using{OPpMULTIDEREF_EXISTS} = $ops_using{OPpMULTIDEREF_DELETE}; +$ops_using{OPpOPEN_IN_RAW} = $ops_using{OPpOPEN_IN_CRLF}; +$ops_using{OPpOPEN_OUT_CRLF} = $ops_using{OPpOPEN_IN_CRLF}; +$ops_using{OPpOPEN_OUT_RAW} = $ops_using{OPpOPEN_IN_CRLF}; +$ops_using{OPpSLICE} = $ops_using{OPpKVSLICE}; +$ops_using{OPpSORT_INPLACE} = $ops_using{OPpSORT_DESCEND}; +$ops_using{OPpSORT_INTEGER} = $ops_using{OPpSORT_DESCEND}; +$ops_using{OPpSORT_NUMERIC} = $ops_using{OPpSORT_DESCEND}; +$ops_using{OPpSORT_REVERSE} = $ops_using{OPpSORT_DESCEND}; +$ops_using{OPpSPLIT_IMPLIM} = $ops_using{OPpSPLIT_ASSIGN}; +$ops_using{OPpSPLIT_LEX} = $ops_using{OPpSPLIT_ASSIGN}; +$ops_using{OPpTRANS_DELETE} = $ops_using{OPpTRANS_COMPLEMENT}; +$ops_using{OPpTRANS_IDENTICAL} = $ops_using{OPpTRANS_COMPLEMENT}; +$ops_using{OPpTRANS_SQUASH} = $ops_using{OPpTRANS_COMPLEMENT}; +$ops_using{OPpTRANS_USE_SVOP} = $ops_using{OPpTRANS_COMPLEMENT}; + +# ex: set ro ft=perl: diff --git a/git/usr/share/perl5/core_perl/Carp/Heavy.pm b/git/usr/share/perl5/core_perl/Carp/Heavy.pm new file mode 100644 index 0000000000000000000000000000000000000000..043e345620e9ef0e3dbdb45171af26b96ca55977 --- /dev/null +++ b/git/usr/share/perl5/core_perl/Carp/Heavy.pm @@ -0,0 +1,21 @@ +package Carp::Heavy; + +use Carp (); + +our $VERSION = '1.54'; +$VERSION =~ tr/_//d; + +# Carp::Heavy was merged into Carp in version 1.12. Any mismatched versions +# after this point are not significant and can be ignored. +if(($Carp::VERSION || 0) < 1.12) { + my $cv = defined($Carp::VERSION) ? $Carp::VERSION : "undef"; + die "Version mismatch between Carp $cv ($INC{q(Carp.pm)}) and Carp::Heavy $VERSION ($INC{q(Carp/Heavy.pm)}). Did you alter \@INC after Carp was loaded?\n"; +} + +1; + +# Most of the machinery of Carp used to be here. +# It has been moved in Carp.pm now, but this placeholder remains for +# the benefit of modules that like to preload Carp::Heavy directly. +# This must load Carp, because some modules rely on the historical +# behaviour of Carp::Heavy loading Carp. diff --git a/git/usr/share/perl5/core_perl/Class/Struct.pm b/git/usr/share/perl5/core_perl/Class/Struct.pm new file mode 100644 index 0000000000000000000000000000000000000000..a574734e5cbefe6e441e5022f672713eb76b097f --- /dev/null +++ b/git/usr/share/perl5/core_perl/Class/Struct.pm @@ -0,0 +1,637 @@ +package Class::Struct; + +## See POD after __END__ + +use 5.006_001; + +use strict; +use warnings::register; +our(@ISA, @EXPORT, $VERSION); + +use Carp; + +require Exporter; +@ISA = qw(Exporter); +@EXPORT = qw(struct); + +$VERSION = '0.68'; + +my $print = 0; +sub printem { + if (@_) { $print = shift } + else { $print++ } +} + +{ + package Class::Struct::Tie_ISA; + + sub TIEARRAY { + my $class = shift; + return bless [], $class; + } + + sub STORE { + my ($self, $index, $value) = @_; + Class::Struct::_subclass_error(); + } + + sub FETCH { + my ($self, $index) = @_; + $self->[$index]; + } + + sub FETCHSIZE { + my $self = shift; + return scalar(@$self); + } + + sub DESTROY { } +} + +sub import { + my $self = shift; + + if ( @_ == 0 ) { + $self->export_to_level( 1, $self, @EXPORT ); + } elsif ( @_ == 1 ) { + # This is admittedly a little bit silly: + # do we ever export anything else than 'struct'...? + $self->export_to_level( 1, $self, @_ ); + } else { + goto &struct; + } +} + +sub struct { + + # Determine parameter list structure, one of: + # struct( class => [ element-list ]) + # struct( class => { element-list }) + # struct( element-list ) + # Latter form assumes current package name as struct name. + + my ($class, @decls); + my $base_type = ref $_[1]; + if ( $base_type eq 'HASH' ) { + $class = shift; + @decls = %{shift()}; + _usage_error() if @_; + } + elsif ( $base_type eq 'ARRAY' ) { + $class = shift; + @decls = @{shift()}; + _usage_error() if @_; + } + else { + $base_type = 'ARRAY'; + $class = caller(); + @decls = @_; + } + + _usage_error() if @decls % 2 == 1; + + # Ensure we are not, and will not be, a subclass. + + my $isa = do { + no strict 'refs'; + \@{$class . '::ISA'}; + }; + _subclass_error() if @$isa; + tie @$isa, 'Class::Struct::Tie_ISA'; + + # Create constructor. + + croak "function 'new' already defined in package $class" + if do { no strict 'refs'; defined &{$class . "::new"} }; + + my @methods = (); + my %refs = (); + my %arrays = (); + my %hashes = (); + my %classes = (); + my $got_class = 0; + my $out = ''; + + $out = "{\n package $class;\n use Carp;\n sub new {\n"; + $out .= " my (\$class, \%init) = \@_;\n"; + $out .= " \$class = __PACKAGE__ unless \@_;\n"; + + my $cnt = 0; + my $idx = 0; + my( $cmt, $name, $type, $elem ); + + if( $base_type eq 'HASH' ){ + $out .= " my(\$r) = {};\n"; + $cmt = ''; + } + elsif( $base_type eq 'ARRAY' ){ + $out .= " my(\$r) = [];\n"; + } + + $out .= " bless \$r, \$class;\n\n"; + + while( $idx < @decls ){ + $name = $decls[$idx]; + $type = $decls[$idx+1]; + push( @methods, $name ); + if( $base_type eq 'HASH' ){ + $elem = "{'${class}::$name'}"; + } + elsif( $base_type eq 'ARRAY' ){ + $elem = "[$cnt]"; + ++$cnt; + $cmt = " # $name"; + } + if( $type =~ /^\*(.)/ ){ + $refs{$name}++; + $type = $1; + } + my $init = "defined(\$init{'$name'}) ? \$init{'$name'} :"; + if( $type eq '@' ){ + $out .= " croak 'Initializer for $name must be array reference'\n"; + $out .= " if defined(\$init{'$name'}) && ref(\$init{'$name'}) ne 'ARRAY';\n"; + $out .= " \$r->$name( $init [] );$cmt\n"; + $arrays{$name}++; + } + elsif( $type eq '%' ){ + $out .= " croak 'Initializer for $name must be hash reference'\n"; + $out .= " if defined(\$init{'$name'}) && ref(\$init{'$name'}) ne 'HASH';\n"; + $out .= " \$r->$name( $init {} );$cmt\n"; + $hashes{$name}++; + } + elsif ( $type eq '$') { + $out .= " \$r->$name( $init undef );$cmt\n"; + } + elsif( $type =~ /^\w+(?:::\w+)*$/ ){ + $out .= " if (defined(\$init{'$name'})) {\n"; + $out .= " if (ref \$init{'$name'} eq 'HASH')\n"; + $out .= " { \$r->$name( $type->new(\%{\$init{'$name'}}) ) } $cmt\n"; + $out .= " elsif (UNIVERSAL::isa(\$init{'$name'}, '$type'))\n"; + $out .= " { \$r->$name( \$init{'$name'} ) } $cmt\n"; + $out .= " else { croak 'Initializer for $name must be hash or $type reference' }\n"; + $out .= " }\n"; + $classes{$name} = $type; + $got_class = 1; + } + else{ + croak "'$type' is not a valid struct element type"; + } + $idx += 2; + } + + $out .= "\n \$r;\n}\n"; + + # Create accessor methods. + + my( $pre, $pst, $sel ); + $cnt = 0; + foreach $name (@methods){ + if ( do { no strict 'refs'; defined &{$class . "::$name"} } ) { + warnings::warnif("function '$name' already defined, overrides struct accessor method"); + } + else { + $pre = $pst = $cmt = $sel = ''; + if( defined $refs{$name} ){ + $pre = "\\("; + $pst = ")"; + $cmt = " # returns ref"; + } + $out .= " sub $name {$cmt\n my \$r = shift;\n"; + if( $base_type eq 'ARRAY' ){ + $elem = "[$cnt]"; + ++$cnt; + } + elsif( $base_type eq 'HASH' ){ + $elem = "{'${class}::$name'}"; + } + if( defined $arrays{$name} ){ + $out .= " my \$i;\n"; + $out .= " \@_ ? (\$i = shift) : return \$r->$elem;\n"; + $out .= " if (ref(\$i) eq 'ARRAY' && !\@_) { \$r->$elem = \$i; return \$r }\n"; + $sel = "->[\$i]"; + } + elsif( defined $hashes{$name} ){ + $out .= " my \$i;\n"; + $out .= " \@_ ? (\$i = shift) : return \$r->$elem;\n"; + $out .= " if (ref(\$i) eq 'HASH' && !\@_) { \$r->$elem = \$i; return \$r }\n"; + $sel = "->{\$i}"; + } + elsif( defined $classes{$name} ){ + $out .= " croak '$name argument is wrong class' if \@_ && ! UNIVERSAL::isa(\$_[0], '$classes{$name}');\n"; + } + $out .= " croak 'Too many args to $name' if \@_ > 1;\n"; + $out .= " \@_ ? ($pre\$r->$elem$sel = shift$pst) : $pre\$r->$elem$sel$pst;\n"; + $out .= " }\n"; + } + } + $out .= "}\n1;\n"; + + print $out if $print; + my $result = eval $out; + carp $@ if $@; +} + +sub _usage_error { + confess "struct usage error"; +} + +sub _subclass_error { + croak 'struct class cannot be a subclass (@ISA not allowed)'; +} + +1; # for require + + +__END__ + +=head1 NAME + +Class::Struct - declare struct-like datatypes as Perl classes + +=head1 SYNOPSIS + + use Class::Struct; + # declare struct, based on array: + struct( CLASS_NAME => [ ELEMENT_NAME => ELEMENT_TYPE, ... ]); + # declare struct, based on hash: + struct( CLASS_NAME => { ELEMENT_NAME => ELEMENT_TYPE, ... }); + + package CLASS_NAME; + use Class::Struct; + # declare struct, based on array, implicit class name: + struct( ELEMENT_NAME => ELEMENT_TYPE, ... ); + + # Declare struct at compile time + use Class::Struct CLASS_NAME => [ELEMENT_NAME => ELEMENT_TYPE, ...]; + use Class::Struct CLASS_NAME => {ELEMENT_NAME => ELEMENT_TYPE, ...}; + + # declare struct at compile time, based on array, implicit + # class name: + package CLASS_NAME; + use Class::Struct ELEMENT_NAME => ELEMENT_TYPE, ... ; + + package Myobj; + use Class::Struct; + # declare struct with four types of elements: + struct( s => '$', a => '@', h => '%', c => 'My_Other_Class' ); + + my $obj = Myobj->new; # constructor + + # scalar type accessor: + my $element_value = $obj->s; # element value + $obj->s('new value'); # assign to element + + # array type accessor: + my $ary_ref = $obj->a; # reference to whole array + my $ary_element_value = $obj->a(2); # array element value + $obj->a(2, 'new value'); # assign to array element + + # hash type accessor: + my $hash_ref = $obj->h; # reference to whole hash + my $hash_element_value = $obj->h('x'); # hash element value + $obj->h('x', 'new value'); # assign to hash element + + # class type accessor: + my $element_value = $obj->c; # object reference + $obj->c->method(...); # call method of object + $obj->c(new My_Other_Class); # assign a new object + +=head1 DESCRIPTION + +C exports a single function, C. +Given a list of element names and types, and optionally +a class name, C creates a Perl 5 class that implements +a "struct-like" data structure. + +The new class is given a constructor method, C, for creating +struct objects. + +Each element in the struct data has an accessor method, which is +used to assign to the element and to fetch its value. The +default accessor can be overridden by declaring a C of the +same name in the package. (See Example 2.) + +Each element's type can be scalar, array, hash, or class. + +=head2 The C function + +The C function has three forms of parameter-list. + + struct( CLASS_NAME => [ ELEMENT_LIST ]); + struct( CLASS_NAME => { ELEMENT_LIST }); + struct( ELEMENT_LIST ); + +The first and second forms explicitly identify the name of the +class being created. The third form assumes the current package +name as the class name. + +An object of a class created by the first and third forms is +based on an array, whereas an object of a class created by the +second form is based on a hash. The array-based forms will be +somewhat faster and smaller; the hash-based forms are more +flexible. + +The class created by C must not be a subclass of another +class other than C. + +It can, however, be used as a superclass for other classes. To facilitate +this, the generated constructor method uses a two-argument blessing. +Furthermore, if the class is hash-based, the key of each element is +prefixed with the class name (see I, Recipe 13.12). + +A function named C must not be explicitly defined in a class +created by C. + +The I has the form + + NAME => TYPE, ... + +Each name-type pair declares one element of the struct. Each +element name will be defined as an accessor method unless a +method by that name is explicitly defined; in the latter case, a +warning is issued if the warning flag (B<-w>) is set. + +=head2 Class Creation at Compile Time + +C can create your class at compile time. The main reason +for doing this is obvious, so your class acts like every other class in +Perl. Creating your class at compile time will make the order of events +similar to using any other class ( or Perl module ). + +There is no significant speed gain between compile time and run time +class creation, there is just a new, more standard order of events. + +=head2 Element Types and Accessor Methods + +The four element types -- scalar, array, hash, and class -- are +represented by strings -- C<'$'>, C<'@'>, C<'%'>, and a class name -- +optionally preceded by a C<'*'>. + +The accessor method provided by C for an element depends +on the declared type of the element. + +=over 4 + +=item Scalar (C<'$'> or C<'*$'>) + +The element is a scalar, and by default is initialized to C +(but see L). + +The accessor's argument, if any, is assigned to the element. + +If the element type is C<'$'>, the value of the element (after +assignment) is returned. If the element type is C<'*$'>, a reference +to the element is returned. + +=item Array (C<'@'> or C<'*@'>) + +The element is an array, initialized by default to C<()>. + +With no argument, the accessor returns a reference to the +element's whole array (whether or not the element was +specified as C<'@'> or C<'*@'>). + +With one or two arguments, the first argument is an index +specifying one element of the array; the second argument, if +present, is assigned to the array element. If the element type +is C<'@'>, the accessor returns the array element value. If the +element type is C<'*@'>, a reference to the array element is +returned. + +As a special case, when the accessor is called with an array reference +as the sole argument, this causes an assignment of the whole array element. +The object reference is returned. + +=item Hash (C<'%'> or C<'*%'>) + +The element is a hash, initialized by default to C<()>. + +With no argument, the accessor returns a reference to the +element's whole hash (whether or not the element was +specified as C<'%'> or C<'*%'>). + +With one or two arguments, the first argument is a key specifying +one element of the hash; the second argument, if present, is +assigned to the hash element. If the element type is C<'%'>, the +accessor returns the hash element value. If the element type is +C<'*%'>, a reference to the hash element is returned. + +As a special case, when the accessor is called with a hash reference +as the sole argument, this causes an assignment of the whole hash element. +The object reference is returned. + +=item Class (C<'Class_Name'> or C<'*Class_Name'>) + +The element's value must be a reference blessed to the named +class or to one of its subclasses. The element is not initialized +by default. + +The accessor's argument, if any, is assigned to the element. The +accessor will C if this is not an appropriate object +reference. + +If the element type does not start with a C<'*'>, the accessor +returns the element value (after assignment). If the element type +starts with a C<'*'>, a reference to the element itself is returned. + +=back + +=head2 Initializing with C + +C always creates a constructor called C. That constructor +may take a list of initializers for the various elements of the new +struct. + +Each initializer is a pair of values: IC< =E >I. +The initializer value for a scalar element is just a scalar value. The +initializer for an array element is an array reference. The initializer +for a hash is a hash reference. + +The initializer for a class element is an object of the corresponding class, +or of one of it's subclasses, or a reference to a hash containing named +arguments to be passed to the element's constructor. + +See Example 3 below for an example of initialization. + +=head1 EXAMPLES + +=over 4 + +=item Example 1 + +Giving a struct element a class type that is also a struct is how +structs are nested. Here, C represents a time (seconds and +microseconds), and C has two elements, each of which is of +type C. + + use Class::Struct; + + struct( Rusage => { + ru_utime => 'Timeval', # user time used + ru_stime => 'Timeval', # system time used + }); + + struct( Timeval => [ + tv_secs => '$', # seconds + tv_usecs => '$', # microseconds + ]); + + # create an object: + my $t = Rusage->new(ru_utime=>Timeval->new(), + ru_stime=>Timeval->new()); + + # $t->ru_utime and $t->ru_stime are objects of type Timeval. + # set $t->ru_utime to 100.0 sec and $t->ru_stime to 5.0 sec. + $t->ru_utime->tv_secs(100); + $t->ru_utime->tv_usecs(0); + $t->ru_stime->tv_secs(5); + $t->ru_stime->tv_usecs(0); + +=item Example 2 + +An accessor function can be redefined in order to provide +additional checking of values, etc. Here, we want the C +element always to be nonnegative, so we redefine the C +accessor accordingly. + + package MyObj; + use Class::Struct; + + # declare the struct + struct ( 'MyObj', { count => '$', stuff => '%' } ); + + # override the default accessor method for 'count' + sub count { + my $self = shift; + if ( @_ ) { + die 'count must be nonnegative' if $_[0] < 0; + $self->{'MyObj::count'} = shift; + warn "Too many args to count" if @_; + } + return $self->{'MyObj::count'}; + } + + package main; + $x = new MyObj; + print "\$x->count(5) = ", $x->count(5), "\n"; + # prints '$x->count(5) = 5' + + print "\$x->count = ", $x->count, "\n"; + # prints '$x->count = 5' + + print "\$x->count(-5) = ", $x->count(-5), "\n"; + # dies due to negative argument! + +=item Example 3 + +The constructor of a generated class can be passed a list +of I=>I pairs, with which to initialize the struct. +If no initializer is specified for a particular element, its default +initialization is performed instead. Initializers for non-existent +elements are silently ignored. + +Note that the initializer for a nested class may be specified as +an object of that class, or as a reference to a hash of initializers +that are passed on to the nested struct's constructor. + + use Class::Struct; + + struct Breed => + { + name => '$', + cross => '$', + }; + + struct Cat => + [ + name => '$', + kittens => '@', + markings => '%', + breed => 'Breed', + ]; + + + my $cat = Cat->new( name => 'Socks', + kittens => ['Monica', 'Kenneth'], + markings => { socks=>1, blaze=>"white" }, + breed => Breed->new(name=>'short-hair', cross=>1), + or: breed => {name=>'short-hair', cross=>1}, + ); + + print "Once a cat called ", $cat->name, "\n"; + print "(which was a ", $cat->breed->name, ")\n"; + print "had 2 kittens: ", join(' and ', @{$cat->kittens}), "\n"; + +=back + +=head1 Author and Modification History + +Modified by Damian Conway, 2001-09-10, v0.62. + + Modified implicit construction of nested objects. + Now will also take an object ref instead of requiring a hash ref. + Also default initializes nested object attributes to undef, rather + than calling object constructor without args + Original over-helpfulness was fraught with problems: + * the class's constructor might not be called 'new' + * the class might not have a hash-like-arguments constructor + * the class might not have a no-argument constructor + * "recursive" data structures didn't work well: + package Person; + struct { mother => 'Person', father => 'Person'}; + + +Modified by Casey West, 2000-11-08, v0.59. + + Added the ability for compile time class creation. + +Modified by Damian Conway, 1999-03-05, v0.58. + + Added handling of hash-like arg list to class ctor. + + Changed to two-argument blessing in ctor to support + derivation from created classes. + + Added classname prefixes to keys in hash-based classes + (refer to "Perl Cookbook", Recipe 13.12 for rationale). + + Corrected behaviour of accessors for '*@' and '*%' struct + elements. Package now implements documented behaviour when + returning a reference to an entire hash or array element. + Previously these were returned as a reference to a reference + to the element. + +Renamed to C and modified by Jim Miner, 1997-04-02. + + members() function removed. + Documentation corrected and extended. + Use of struct() in a subclass prohibited. + User definition of accessor allowed. + Treatment of '*' in element types corrected. + Treatment of classes as element types corrected. + Class name to struct() made optional. + Diagnostic checks added. + +Originally C by Dean Roehrich. + + # Template.pm --- struct/member template builder + # 12mar95 + # Dean Roehrich + # + # changes/bugs fixed since 28nov94 version: + # - podified + # changes/bugs fixed since 21nov94 version: + # - Fixed examples. + # changes/bugs fixed since 02sep94 version: + # - Moved to Class::Template. + # changes/bugs fixed since 20feb94 version: + # - Updated to be a more proper module. + # - Added "use strict". + # - Bug in build_methods, was using @var when @$var needed. + # - Now using my() rather than local(). + # + # Uses perl5 classes to create nested data types. + # This is offered as one implementation of Tom Christiansen's + # "structs.pl" idea. + +=cut diff --git a/git/usr/share/perl5/core_perl/Compress/Zlib.pm b/git/usr/share/perl5/core_perl/Compress/Zlib.pm new file mode 100644 index 0000000000000000000000000000000000000000..6f3e11a8be7d9898b96365e2119b157189171f9d --- /dev/null +++ b/git/usr/share/perl5/core_perl/Compress/Zlib.pm @@ -0,0 +1,1515 @@ + +package Compress::Zlib; + +require 5.006 ; +require Exporter; +use Carp ; +use IO::Handle ; +use Scalar::Util qw(dualvar); + +use IO::Compress::Base::Common 2.213 ; +use Compress::Raw::Zlib 2.213 ; +use IO::Compress::Gzip 2.213 ; +use IO::Uncompress::Gunzip 2.213 ; + +use strict ; +use warnings ; +use bytes ; +our ($VERSION, $XS_VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS); + +$VERSION = '2.213'; +$XS_VERSION = $VERSION; +$VERSION = eval $VERSION; + +@ISA = qw(Exporter); +# Items to export into callers namespace by default. Note: do not export +# names by default without a very good reason. Use EXPORT_OK instead. +# Do not simply export all your public functions/methods/constants. +@EXPORT = qw( + deflateInit inflateInit + + compress uncompress + + gzopen $gzerrno + ); + +push @EXPORT, @Compress::Raw::Zlib::EXPORT ; + +@EXPORT_OK = qw(memGunzip memGzip zlib_version); +%EXPORT_TAGS = ( + ALL => \@EXPORT +); + +BEGIN +{ + *zlib_version = \&Compress::Raw::Zlib::zlib_version; +} + +use constant FLAG_APPEND => 1 ; +use constant FLAG_CRC => 2 ; +use constant FLAG_ADLER => 4 ; +use constant FLAG_CONSUME_INPUT => 8 ; + +our (@my_z_errmsg); + +@my_z_errmsg = ( + "need dictionary", # Z_NEED_DICT 2 + "stream end", # Z_STREAM_END 1 + "", # Z_OK 0 + "file error", # Z_ERRNO (-1) + "stream error", # Z_STREAM_ERROR (-2) + "data error", # Z_DATA_ERROR (-3) + "insufficient memory", # Z_MEM_ERROR (-4) + "buffer error", # Z_BUF_ERROR (-5) + "incompatible version",# Z_VERSION_ERROR(-6) + ); + + +sub _set_gzerr +{ + my $value = shift ; + + if ($value == 0) { + $Compress::Zlib::gzerrno = 0 ; + } + elsif ($value == Z_ERRNO() || $value > 2) { + $Compress::Zlib::gzerrno = $! ; + } + else { + $Compress::Zlib::gzerrno = dualvar($value+0, $my_z_errmsg[2 - $value]); + } + + return $value ; +} + +sub _set_gzerr_undef +{ + _set_gzerr(@_); + return undef; +} + +sub _save_gzerr +{ + my $gz = shift ; + my $test_eof = shift ; + + my $value = $gz->errorNo() || 0 ; + my $eof = $gz->eof() ; + + if ($test_eof) { + # gzread uses Z_STREAM_END to denote a successful end + $value = Z_STREAM_END() if $gz->eof() && $value == 0 ; + } + + _set_gzerr($value) ; +} + +sub gzopen($$) +{ + my ($file, $mode) = @_ ; + + my $gz ; + my %defOpts = (Level => Z_DEFAULT_COMPRESSION(), + Strategy => Z_DEFAULT_STRATEGY(), + ); + + my $writing ; + $writing = ! ($mode =~ /r/i) ; + $writing = ($mode =~ /[wa]/i) ; + + $defOpts{Level} = $1 if $mode =~ /(\d)/; + $defOpts{Strategy} = Z_FILTERED() if $mode =~ /f/i; + $defOpts{Strategy} = Z_HUFFMAN_ONLY() if $mode =~ /h/i; + $defOpts{Append} = 1 if $mode =~ /a/i; + + my $infDef = $writing ? 'deflate' : 'inflate'; + my @params = () ; + + croak "gzopen: file parameter is not a filehandle or filename" + unless isaFilehandle $file || isaFilename $file || + (ref $file && ref $file eq 'SCALAR'); + + return undef unless $mode =~ /[rwa]/i ; + + _set_gzerr(0) ; + + if ($writing) { + $gz = IO::Compress::Gzip->new($file, Minimal => 1, AutoClose => 1, + %defOpts) + or $Compress::Zlib::gzerrno = $IO::Compress::Gzip::GzipError; + } + else { + $gz = IO::Uncompress::Gunzip->new($file, + Transparent => 1, + Append => 0, + AutoClose => 1, + MultiStream => 1, + Strict => 0) + or $Compress::Zlib::gzerrno = $IO::Uncompress::Gunzip::GunzipError; + } + + return undef + if ! defined $gz ; + + bless [$gz, $infDef], 'Compress::Zlib::gzFile'; +} + +sub Compress::Zlib::gzFile::gzread +{ + my $self = shift ; + + return _set_gzerr(Z_STREAM_ERROR()) + if $self->[1] ne 'inflate'; + + my $len = defined $_[1] ? $_[1] : 4096 ; + + my $gz = $self->[0] ; + if ($self->gzeof() || $len == 0) { + # Zap the output buffer to match ver 1 behaviour. + $_[0] = "" ; + _save_gzerr($gz, 1); + return 0 ; + } + + my $status = $gz->read($_[0], $len) ; + _save_gzerr($gz, 1); + return $status ; +} + +sub Compress::Zlib::gzFile::gzreadline +{ + my $self = shift ; + + my $gz = $self->[0] ; + { + # Maintain backward compatibility with 1.x behaviour + # It didn't support $/, so this can't either. + local $/ = "\n" ; + $_[0] = $gz->getline() ; + } + _save_gzerr($gz, 1); + return defined $_[0] ? length $_[0] : 0 ; +} + +sub Compress::Zlib::gzFile::gzwrite +{ + my $self = shift ; + my $gz = $self->[0] ; + + return _set_gzerr(Z_STREAM_ERROR()) + if $self->[1] ne 'deflate'; + + $] >= 5.008 and (utf8::downgrade($_[0], 1) + or croak "Wide character in gzwrite"); + + my $status = $gz->write($_[0]) ; + _save_gzerr($gz); + return $status ; +} + +sub Compress::Zlib::gzFile::gztell +{ + my $self = shift ; + my $gz = $self->[0] ; + my $status = $gz->tell() ; + _save_gzerr($gz); + return $status ; +} + +sub Compress::Zlib::gzFile::gzseek +{ + my $self = shift ; + my $offset = shift ; + my $whence = shift ; + + my $gz = $self->[0] ; + my $status ; + eval { local $SIG{__DIE__}; $status = $gz->seek($offset, $whence) ; }; + if ($@) + { + my $error = $@; + $error =~ s/^.*: /gzseek: /; + $error =~ s/ at .* line \d+\s*$//; + croak $error; + } + _save_gzerr($gz); + return $status ; +} + +sub Compress::Zlib::gzFile::gzflush +{ + my $self = shift ; + my $f = shift ; + + my $gz = $self->[0] ; + my $status = $gz->flush($f) ; + my $err = _save_gzerr($gz); + return $status ? 0 : $err; +} + +sub Compress::Zlib::gzFile::gzclose +{ + my $self = shift ; + my $gz = $self->[0] ; + + my $status = $gz->close() ; + my $err = _save_gzerr($gz); + return $status ? 0 : $err; +} + +sub Compress::Zlib::gzFile::gzeof +{ + my $self = shift ; + my $gz = $self->[0] ; + + return 0 + if $self->[1] ne 'inflate'; + + my $status = $gz->eof() ; + _save_gzerr($gz); + return $status ; +} + +sub Compress::Zlib::gzFile::gzsetparams +{ + my $self = shift ; + croak "Usage: Compress::Zlib::gzFile::gzsetparams(file, level, strategy)" + unless @_ eq 2 ; + + my $gz = $self->[0] ; + my $level = shift ; + my $strategy = shift; + + return _set_gzerr(Z_STREAM_ERROR()) + if $self->[1] ne 'deflate'; + + my $status = *$gz->{Compress}->deflateParams(-Level => $level, + -Strategy => $strategy); + _save_gzerr($gz); + return $status ; +} + +sub Compress::Zlib::gzFile::gzerror +{ + my $self = shift ; + my $gz = $self->[0] ; + + return $Compress::Zlib::gzerrno ; +} + + +sub compress($;$) +{ + my ($x, $output, $err, $in) =('', '', '', '') ; + + if (ref $_[0] ) { + $in = $_[0] ; + croak "not a scalar reference" unless ref $in eq 'SCALAR' ; + } + else { + $in = \$_[0] ; + } + + $] >= 5.008 and (utf8::downgrade($$in, 1) + or croak "Wide character in compress"); + + my $level = (@_ == 2 ? $_[1] : Z_DEFAULT_COMPRESSION() ); + + $x = Compress::Raw::Zlib::_deflateInit(FLAG_APPEND, + $level, + Z_DEFLATED, + MAX_WBITS, + MAX_MEM_LEVEL, + Z_DEFAULT_STRATEGY, + 4096, + '') + or return undef ; + + $err = $x->deflate($in, $output) ; + return undef unless $err == Z_OK() ; + + $err = $x->flush($output) ; + return undef unless $err == Z_OK() ; + + return $output ; +} + +sub uncompress($) +{ + my ($output, $in) =('', '') ; + + if (ref $_[0] ) { + $in = $_[0] ; + croak "not a scalar reference" unless ref $in eq 'SCALAR' ; + } + else { + $in = \$_[0] ; + } + + $] >= 5.008 and (utf8::downgrade($$in, 1) + or croak "Wide character in uncompress"); + + my ($obj, $status) = Compress::Raw::Zlib::_inflateInit(0, + MAX_WBITS, 4096, "") ; + + $status == Z_OK + or return undef; + + $obj->inflate($in, $output) == Z_STREAM_END + or return undef; + + return $output; +} + +sub deflateInit(@) +{ + my ($got) = ParseParameters(0, + { + 'bufsize' => [IO::Compress::Base::Common::Parse_unsigned, 4096], + 'level' => [IO::Compress::Base::Common::Parse_signed, Z_DEFAULT_COMPRESSION()], + 'method' => [IO::Compress::Base::Common::Parse_unsigned, Z_DEFLATED()], + 'windowbits' => [IO::Compress::Base::Common::Parse_signed, MAX_WBITS()], + 'memlevel' => [IO::Compress::Base::Common::Parse_unsigned, MAX_MEM_LEVEL()], + 'strategy' => [IO::Compress::Base::Common::Parse_unsigned, Z_DEFAULT_STRATEGY()], + 'dictionary' => [IO::Compress::Base::Common::Parse_any, ""], + }, @_ ) ; + + croak "Compress::Zlib::deflateInit: Bufsize must be >= 1, you specified " . + $got->getValue('bufsize') + unless $got->getValue('bufsize') >= 1; + + my $obj ; + + my $status = 0 ; + ($obj, $status) = + Compress::Raw::Zlib::_deflateInit(0, + $got->getValue('level'), + $got->getValue('method'), + $got->getValue('windowbits'), + $got->getValue('memlevel'), + $got->getValue('strategy'), + $got->getValue('bufsize'), + $got->getValue('dictionary')) ; + + my $x = ($status == Z_OK() ? bless $obj, "Zlib::OldDeflate" : undef) ; + return wantarray ? ($x, $status) : $x ; +} + +sub inflateInit(@) +{ + my ($got) = ParseParameters(0, + { + 'bufsize' => [IO::Compress::Base::Common::Parse_unsigned, 4096], + 'windowbits' => [IO::Compress::Base::Common::Parse_signed, MAX_WBITS()], + 'dictionary' => [IO::Compress::Base::Common::Parse_any, ""], + }, @_) ; + + + croak "Compress::Zlib::inflateInit: Bufsize must be >= 1, you specified " . + $got->getValue('bufsize') + unless $got->getValue('bufsize') >= 1; + + my $status = 0 ; + my $obj ; + ($obj, $status) = Compress::Raw::Zlib::_inflateInit(FLAG_CONSUME_INPUT, + $got->getValue('windowbits'), + $got->getValue('bufsize'), + $got->getValue('dictionary')) ; + + my $x = ($status == Z_OK() ? bless $obj, "Zlib::OldInflate" : undef) ; + + wantarray ? ($x, $status) : $x ; +} + +package Zlib::OldDeflate ; + +our (@ISA); +@ISA = qw(Compress::Raw::Zlib::deflateStream); + + +sub deflate +{ + my $self = shift ; + my $output ; + + my $status = $self->SUPER::deflate($_[0], $output) ; + wantarray ? ($output, $status) : $output ; +} + +sub flush +{ + my $self = shift ; + my $output ; + my $flag = shift || Compress::Zlib::Z_FINISH(); + my $status = $self->SUPER::flush($output, $flag) ; + + wantarray ? ($output, $status) : $output ; +} + +package Zlib::OldInflate ; + +our (@ISA); +@ISA = qw(Compress::Raw::Zlib::inflateStream); + +sub inflate +{ + my $self = shift ; + my $output ; + my $status = $self->SUPER::inflate($_[0], $output) ; + wantarray ? ($output, $status) : $output ; +} + +package Compress::Zlib ; + +use IO::Compress::Gzip::Constants 2.213 ; + +sub memGzip($) +{ + _set_gzerr(0); + my $x = Compress::Raw::Zlib::_deflateInit(FLAG_APPEND|FLAG_CRC, + Z_BEST_COMPRESSION, + Z_DEFLATED, + -MAX_WBITS(), + MAX_MEM_LEVEL, + Z_DEFAULT_STRATEGY, + 4096, + '') + or return undef ; + + # if the deflation buffer isn't a reference, make it one + my $string = (ref $_[0] ? $_[0] : \$_[0]) ; + + $] >= 5.008 and (utf8::downgrade($$string, 1) + or croak "Wide character in memGzip"); + + my $out; + my $status ; + + $x->deflate($string, $out) == Z_OK + or return undef ; + + $x->flush($out) == Z_OK + or return undef ; + + return IO::Compress::Gzip::Constants::GZIP_MINIMUM_HEADER . + $out . + pack("V V", $x->crc32(), $x->total_in()); +} + + +sub _removeGzipHeader($) +{ + my $string = shift ; + + return Z_DATA_ERROR() + if length($$string) < GZIP_MIN_HEADER_SIZE ; + + my ($magic1, $magic2, $method, $flags, $time, $xflags, $oscode) = + unpack ('CCCCVCC', $$string); + + return Z_DATA_ERROR() + unless $magic1 == GZIP_ID1 and $magic2 == GZIP_ID2 and + $method == Z_DEFLATED() and !($flags & GZIP_FLG_RESERVED) ; + substr($$string, 0, GZIP_MIN_HEADER_SIZE) = '' ; + + # skip extra field + if ($flags & GZIP_FLG_FEXTRA) + { + return Z_DATA_ERROR() + if length($$string) < GZIP_FEXTRA_HEADER_SIZE ; + + my ($extra_len) = unpack ('v', $$string); + $extra_len += GZIP_FEXTRA_HEADER_SIZE; + return Z_DATA_ERROR() + if length($$string) < $extra_len ; + + substr($$string, 0, $extra_len) = ''; + } + + # skip orig name + if ($flags & GZIP_FLG_FNAME) + { + my $name_end = index ($$string, GZIP_NULL_BYTE); + return Z_DATA_ERROR() + if $name_end == -1 ; + substr($$string, 0, $name_end + 1) = ''; + } + + # skip comment + if ($flags & GZIP_FLG_FCOMMENT) + { + my $comment_end = index ($$string, GZIP_NULL_BYTE); + return Z_DATA_ERROR() + if $comment_end == -1 ; + substr($$string, 0, $comment_end + 1) = ''; + } + + # skip header crc + if ($flags & GZIP_FLG_FHCRC) + { + return Z_DATA_ERROR() + if length ($$string) < GZIP_FHCRC_SIZE ; + substr($$string, 0, GZIP_FHCRC_SIZE) = ''; + } + + return Z_OK(); +} + +sub _ret_gun_error +{ + $Compress::Zlib::gzerrno = $IO::Uncompress::Gunzip::GunzipError; + return undef; +} + + +sub memGunzip($) +{ + # if the buffer isn't a reference, make it one + my $string = (ref $_[0] ? $_[0] : \$_[0]); + + $] >= 5.008 and (utf8::downgrade($$string, 1) + or croak "Wide character in memGunzip"); + + _set_gzerr(0); + + my $status = _removeGzipHeader($string) ; + $status == Z_OK() + or return _set_gzerr_undef($status); + + my $bufsize = length $$string > 4096 ? length $$string : 4096 ; + my $x = Compress::Raw::Zlib::_inflateInit(FLAG_CRC | FLAG_CONSUME_INPUT, + -MAX_WBITS(), $bufsize, '') + or return _ret_gun_error(); + + my $output = '' ; + $status = $x->inflate($string, $output); + + if ( $status == Z_OK() ) + { + _set_gzerr(Z_DATA_ERROR()); + return undef; + } + + return _ret_gun_error() + if ($status != Z_STREAM_END()); + + if (length $$string >= 8) + { + my ($crc, $len) = unpack ("VV", substr($$string, 0, 8)); + substr($$string, 0, 8) = ''; + return _set_gzerr_undef(Z_DATA_ERROR()) + unless $len == length($output) and + $crc == Compress::Raw::Zlib::crc32($output); + } + else + { + $$string = ''; + } + + return $output; +} + +# Autoload methods go after __END__, and are processed by the autosplit program. + +1; +__END__ + + +=head1 NAME + +Compress::Zlib - Interface to zlib compression library + +=head1 SYNOPSIS + + use Compress::Zlib ; + + ($d, $status) = deflateInit( [OPT] ) ; + $status = $d->deflate($input, $output) ; + $status = $d->flush([$flush_type]) ; + $d->deflateParams(OPTS) ; + $d->deflateTune(OPTS) ; + $d->dict_adler() ; + $d->crc32() ; + $d->adler32() ; + $d->total_in() ; + $d->total_out() ; + $d->msg() ; + $d->get_Strategy(); + $d->get_Level(); + $d->get_BufSize(); + + ($i, $status) = inflateInit( [OPT] ) ; + $status = $i->inflate($input, $output [, $eof]) ; + $status = $i->inflateSync($input) ; + $i->dict_adler() ; + $d->crc32() ; + $d->adler32() ; + $i->total_in() ; + $i->total_out() ; + $i->msg() ; + $d->get_BufSize(); + + $dest = compress($source) ; + $dest = uncompress($source) ; + + $gz = gzopen($filename or filehandle, $mode) ; + $bytesread = $gz->gzread($buffer [,$size]) ; + $bytesread = $gz->gzreadline($line) ; + $byteswritten = $gz->gzwrite($buffer) ; + $status = $gz->gzflush($flush) ; + $offset = $gz->gztell() ; + $status = $gz->gzseek($offset, $whence) ; + $status = $gz->gzclose() ; + $status = $gz->gzeof() ; + $status = $gz->gzsetparams($level, $strategy) ; + $errstring = $gz->gzerror() ; + $gzerrno + + $dest = Compress::Zlib::memGzip($buffer) ; + $dest = Compress::Zlib::memGunzip($buffer) ; + + $crc = adler32($buffer [,$crc]) ; + $crc = crc32($buffer [,$crc]) ; + + $crc = crc32_combine($crc1, $crc2, $len2); + $adler = adler32_combine($adler1, $adler2, $len2); + + my $version = Compress::Raw::Zlib::zlib_version(); + +=head1 DESCRIPTION + +The I module provides a Perl interface to the I +compression library (see L for details about where to get +I). + +The C module can be split into two general areas of +functionality, namely a simple read/write interface to I files +and a low-level in-memory compression/decompression interface. + +Each of these areas will be discussed in the following sections. + +=head2 Notes for users of Compress::Zlib version 1 + +The main change in C version 2.x is that it does not now +interface directly to the zlib library. Instead it uses the +C and C modules for +reading/writing gzip files, and the C module for some +low-level zlib access. + +The interface provided by version 2 of this module should be 100% backward +compatible with version 1. If you find a difference in the expected +behaviour please contact the author (See L). See L + +With the creation of the C and C modules no +new features are planned for C - the new modules do +everything that C does and then some. Development on +C will be limited to bug fixes only. + +If you are writing new code, your first port of call should be one of the +new C or C modules. + +=head1 GZIP INTERFACE + +A number of functions are supplied in I for reading and writing +I files that conform to RFC 1952. This module provides an interface +to most of them. + +If you have previously used C 1.x, the following +enhancements/changes have been made to the C interface: + +=over 5 + +=item 1 + +If you want to open either STDIN or STDOUT with C, you can now +optionally use the special filename "C<->" as a synonym for C<\*STDIN> and +C<\*STDOUT>. + +=item 2 + +In C version 1.x, C used the zlib library to open +the underlying file. This made things especially tricky when a Perl +filehandle was passed to C. Behind the scenes the numeric C file +descriptor had to be extracted from the Perl filehandle and this passed to +the zlib library. + +Apart from being non-portable to some operating systems, this made it +difficult to use C in situations where you wanted to extract/create +a gzip data stream that is embedded in a larger file, without having to +resort to opening and closing the file multiple times. + +It also made it impossible to pass a perl filehandle that wasn't associated +with a real filesystem file, like, say, an C. + +In C version 2.x, the C interface has been +completely rewritten to use the L +for writing gzip files and L +for reading gzip files. None of the limitations mentioned above apply. + +=item 3 + +Addition of C to provide a restricted C interface. + +=item 4. + +Added C. + +=back + +A more complete and flexible interface for reading/writing gzip +files/buffers is included with the module C. See +L and +L for more details. + +=over 5 + +=item B<$gz = gzopen($filename, $mode)> + +=item B<$gz = gzopen($filehandle, $mode)> + +This function opens either the I file C<$filename> for reading or +writing or attaches to the opened filehandle, C<$filehandle>. +It returns an object on success and C on failure. + +When writing a gzip file this interface will I create the smallest +possible gzip header (exactly 10 bytes). If you want greater control over +what gets stored in the gzip header (like the original filename or a +comment) use L instead. Similarly if +you want to read the contents of the gzip header use +L. + +The second parameter, C<$mode>, is used to specify whether the file is +opened for reading or writing and to optionally specify a compression +level and compression strategy when writing. The format of the C<$mode> +parameter is similar to the mode parameter to the 'C' function C, +so "rb" is used to open for reading, "wb" for writing and "ab" for +appending (writing at the end of the file). + +To specify a compression level when writing, append a digit between 0 +and 9 to the mode string -- 0 means no compression and 9 means maximum +compression. +If no compression level is specified Z_DEFAULT_COMPRESSION is used. + +To specify the compression strategy when writing, append 'f' for filtered +data, 'h' for Huffman only compression, or 'R' for run-length encoding. +If no strategy is specified Z_DEFAULT_STRATEGY is used. + +So, for example, "wb9" means open for writing with the maximum compression +using the default strategy and "wb4R" means open for writing with compression +level 4 and run-length encoding. + +Refer to the I documentation for the exact format of the C<$mode> +parameter. + +=item B<$bytesread = $gz-Egzread($buffer [, $size]) ;> + +Reads C<$size> bytes from the compressed file into C<$buffer>. If +C<$size> is not specified, it will default to 4096. If the scalar +C<$buffer> is not large enough, it will be extended automatically. + +Returns the number of bytes actually read. On EOF it returns 0 and in +the case of an error, -1. + +=item B<$bytesread = $gz-Egzreadline($line) ;> + +Reads the next line from the compressed file into C<$line>. + +Returns the number of bytes actually read. On EOF it returns 0 and in +the case of an error, -1. + +It is legal to intermix calls to C and C. + +To maintain backward compatibility with version 1.x of this module +C ignores the C<$/> variable - it I uses the string +C<"\n"> as the line delimiter. + +If you want to read a gzip file a line at a time and have it respect the +C<$/> variable (or C<$INPUT_RECORD_SEPARATOR>, or C<$RS> when C is +in use) see L. + +=item B<$byteswritten = $gz-Egzwrite($buffer) ;> + +Writes the contents of C<$buffer> to the compressed file. Returns the +number of bytes actually written, or 0 on error. + +=item B<$status = $gz-Egzflush($flush_type) ;> + +Flushes all pending output into the compressed file. + +This method takes an optional parameter, C<$flush_type>, that controls +how the flushing will be carried out. By default the C<$flush_type> +used is C. Other valid values for C<$flush_type> are +C, C, C and C. It is +strongly recommended that you only set the C parameter if +you fully understand the implications of what it does - overuse of C +can seriously degrade the level of compression achieved. See the C +documentation for details. + +Returns 0 on success. + +=item B<$offset = $gz-Egztell() ;> + +Returns the uncompressed file offset. + +=item B<$status = $gz-Egzseek($offset, $whence) ;> + +Provides a sub-set of the C functionality, with the restriction +that it is only legal to seek forward in the compressed file. +It is a fatal error to attempt to seek backward. + +When opened for writing, empty parts of the file will have NULL (0x00) +bytes written to them. + +The C<$whence> parameter should be one of SEEK_SET, SEEK_CUR or SEEK_END. + +Returns 1 on success, 0 on failure. + +=item B<$gz-Egzclose> + +Closes the compressed file. Any pending data is flushed to the file +before it is closed. + +Returns 0 on success. + +=item B<$gz-Egzsetparams($level, $strategy> + +Change settings for the deflate stream C<$gz>. + +The list of the valid options is shown below. Options not specified +will remain unchanged. + +Note: This method is only available if you are running zlib 1.0.6 or better. + +=over 5 + +=item B<$level> + +Defines the compression level. Valid values are 0 through 9, +C, C, C, and +C. + +=item B<$strategy> + +Defines the strategy used to tune the compression. The valid values are +C, C and C. + +=back + +=item B<$gz-Egzerror> + +Returns the I error message or number for the last operation +associated with C<$gz>. The return value will be the I error +number when used in a numeric context and the I error message +when used in a string context. The I error number constants, +shown below, are available for use. + + Z_OK + Z_STREAM_END + Z_ERRNO + Z_STREAM_ERROR + Z_DATA_ERROR + Z_MEM_ERROR + Z_BUF_ERROR + +=item B<$gzerrno> + +The C<$gzerrno> scalar holds the error code associated with the most +recent I routine. Note that unlike C, the error is +I associated with a particular file. + +As with C it returns an error number in numeric context and +an error message in string context. Unlike C though, the +error message will correspond to the I message when the error is +associated with I itself, or the UNIX error message when it is +not (i.e. I returned C). + +As there is an overlap between the error numbers used by I and +UNIX, C<$gzerrno> should only be used to check for the presence of +I error in numeric context. Use C to check for specific +I errors. The I example below shows how the variable can +be used safely. + +=back + +=head2 Examples + +Here is an example script which uses the interface. It implements a +I function. + + use strict ; + use warnings ; + + use Compress::Zlib ; + + # use stdin if no files supplied + @ARGV = '-' unless @ARGV ; + + foreach my $file (@ARGV) { + my $buffer ; + + my $gz = gzopen($file, "rb") + or die "Cannot open $file: $gzerrno\n" ; + + print $buffer while $gz->gzread($buffer) > 0 ; + + die "Error reading from $file: $gzerrno" . ($gzerrno+0) . "\n" + if $gzerrno != Z_STREAM_END ; + + $gz->gzclose() ; + } + +Below is a script which makes use of C. It implements a +very simple I like script. + + use strict ; + use warnings ; + + use Compress::Zlib ; + + die "Usage: gzgrep pattern [file...]\n" + unless @ARGV >= 1; + + my $pattern = shift ; + + # use stdin if no files supplied + @ARGV = '-' unless @ARGV ; + + foreach my $file (@ARGV) { + my $gz = gzopen($file, "rb") + or die "Cannot open $file: $gzerrno\n" ; + + while ($gz->gzreadline($_) > 0) { + print if /$pattern/ ; + } + + die "Error reading from $file: $gzerrno\n" + if $gzerrno != Z_STREAM_END ; + + $gz->gzclose() ; + } + +This script, I, does the opposite of the I script +above. It reads from standard input and writes a gzip data stream to +standard output. + + use strict ; + use warnings ; + + use Compress::Zlib ; + + binmode STDOUT; # gzopen only sets it on the fd + + my $gz = gzopen(\*STDOUT, "wb") + or die "Cannot open stdout: $gzerrno\n" ; + + while (<>) { + $gz->gzwrite($_) + or die "error writing: $gzerrno\n" ; + } + + $gz->gzclose ; + +=head2 Compress::Zlib::memGzip + +This function is used to create an in-memory gzip file with the minimum +possible gzip header (exactly 10 bytes). + + $dest = Compress::Zlib::memGzip($buffer) + or die "Cannot compress: $gzerrno\n"; + +If successful, it returns the in-memory gzip file. Otherwise it returns +C and the C<$gzerrno> variable will store the zlib error code. + +The C<$buffer> parameter can either be a scalar or a scalar reference. + +See L for an alternative way to +carry out in-memory gzip compression. + +=head2 Compress::Zlib::memGunzip + +This function is used to uncompress an in-memory gzip file. + + $dest = Compress::Zlib::memGunzip($buffer) + or die "Cannot uncompress: $gzerrno\n"; + +If successful, it returns the uncompressed gzip file. Otherwise it +returns C and the C<$gzerrno> variable will store the zlib error +code. + +The C<$buffer> parameter can either be a scalar or a scalar reference. The +contents of the C<$buffer> parameter are destroyed after calling this function. + +If C<$buffer> consists of multiple concatenated gzip data streams only the +first will be uncompressed. Use C with the C option in +the C module if you need to deal with concatenated +data streams. + +See L for an alternative way +to carry out in-memory gzip uncompression. + +=head1 COMPRESS/UNCOMPRESS + +Two functions are provided to perform in-memory compression/uncompression of +RFC 1950 data streams. They are called C and C. + +=over 5 + +=item B<$dest = compress($source [, $level] ) ;> + +Compresses C<$source>. If successful it returns the compressed +data. Otherwise it returns I. + +The source buffer, C<$source>, can either be a scalar or a scalar +reference. + +The C<$level> parameter defines the compression level. Valid values are +0 through 9, C, C, +C, and C. +If C<$level> is not specified C will be used. + +=item B<$dest = uncompress($source) ;> + +Uncompresses C<$source>. If successful it returns the uncompressed +data. Otherwise it returns I. + +The source buffer can either be a scalar or a scalar reference. + +=back + +Please note: the two functions defined above are I compatible with +the Unix commands of the same name. + +See L and L included with +this distribution for an alternative interface for reading/writing RFC 1950 +files/buffers. + +=head1 Deflate Interface + +This section defines an interface that allows in-memory compression using +the I interface provided by zlib. + +Here is a definition of the interface available: + +=head2 B<($d, $status) = deflateInit( [OPT] )> + +Initialises a deflation stream. + +It combines the features of the I functions C, +C and C. + +If successful, it will return the initialised deflation stream, C<$d> +and C<$status> of C in a list context. In scalar context it +returns the deflation stream, C<$d>, only. + +If not successful, the returned deflation stream (C<$d>) will be +I and C<$status> will hold the exact I error code. + +The function optionally takes a number of named options specified as +C<< -Name=>value >> pairs. This allows individual options to be +tailored without having to specify them all in the parameter list. + +For backward compatibility, it is also possible to pass the parameters +as a reference to a hash containing the name=>value pairs. + +The function takes one optional parameter, a reference to a hash. The +contents of the hash allow the deflation interface to be tailored. + +Here is a list of the valid options: + +=over 5 + +=item B<-Level> + +Defines the compression level. Valid values are 0 through 9, +C, C, C, and +C. + +The default is Z_DEFAULT_COMPRESSION. + +=item B<-Method> + +Defines the compression method. The only valid value at present (and +the default) is Z_DEFLATED. + +=item B<-WindowBits> + +To create an RFC 1950 data stream, set C to a positive number. + +To create an RFC 1951 data stream, set C to C<-MAX_WBITS>. + +For a full definition of the meaning and valid values for C refer +to the I documentation for I. + +Defaults to MAX_WBITS. + +=item B<-MemLevel> + +For a definition of the meaning and valid values for C +refer to the I documentation for I. + +Defaults to MAX_MEM_LEVEL. + +=item B<-Strategy> + +Defines the strategy used to tune the compression. The valid values are +C, C and C. + +The default is Z_DEFAULT_STRATEGY. + +=item B<-Dictionary> + +When a dictionary is specified I will automatically +call C directly after calling C. The +Adler32 value for the dictionary can be obtained by calling the method +C<< $d->dict_adler() >>. + +The default is no dictionary. + +=item B<-Bufsize> + +Sets the initial size for the deflation buffer. If the buffer has to be +reallocated to increase the size, it will grow in increments of +C. + +The default is 4096. + +=back + +Here is an example of using the C optional parameter list +to override the default buffer size and compression level. All other +options will take their default values. + + deflateInit( -Bufsize => 300, + -Level => Z_BEST_SPEED ) ; + +=head2 B<($out, $status) = $d-Edeflate($buffer)> + +Deflates the contents of C<$buffer>. The buffer can either be a scalar +or a scalar reference. When finished, C<$buffer> will be +completely processed (assuming there were no errors). If the deflation +was successful it returns the deflated output, C<$out>, and a status +value, C<$status>, of C. + +On error, C<$out> will be I and C<$status> will contain the +I error code. + +In a scalar context C will return C<$out> only. + +As with the I function in I, it is not necessarily the +case that any output will be produced by this method. So don't rely on +the fact that C<$out> is empty for an error test. + +=head2 B<($out, $status) = $d-Eflush()> +=head2 B<($out, $status) = $d-Eflush($flush_type)> + +Typically used to finish the deflation. Any pending output will be +returned via C<$out>. +C<$status> will have a value C if successful. + +In a scalar context C will return C<$out> only. + +Note that flushing can seriously degrade the compression ratio, so it +should only be used to terminate a decompression (using C) or +when you want to create a I (using C). + +By default the C used is C. Other valid values +for C are C, C, C +and C. It is strongly recommended that you only set the +C parameter if you fully understand the implications of +what it does. See the C documentation for details. + +=head2 B<$status = $d-EdeflateParams([OPT])> + +Change settings for the deflate stream C<$d>. + +The list of the valid options is shown below. Options not specified +will remain unchanged. + +=over 5 + +=item B<-Level> + +Defines the compression level. Valid values are 0 through 9, +C, C, C, and +C. + +=item B<-Strategy> + +Defines the strategy used to tune the compression. The valid values are +C, C and C. + +=back + +=head2 B<$d-Edict_adler()> + +Returns the adler32 value for the dictionary. + +=head2 B<$d-Emsg()> + +Returns the last error message generated by zlib. + +=head2 B<$d-Etotal_in()> + +Returns the total number of bytes uncompressed bytes input to deflate. + +=head2 B<$d-Etotal_out()> + +Returns the total number of compressed bytes output from deflate. + +=head2 Example + +Here is a trivial example of using C. It simply reads standard +input, deflates it and writes it to standard output. + + use strict ; + use warnings ; + + use Compress::Zlib ; + + binmode STDIN; + binmode STDOUT; + my $x = deflateInit() + or die "Cannot create a deflation stream\n" ; + + my ($output, $status) ; + while (<>) + { + ($output, $status) = $x->deflate($_) ; + + $status == Z_OK + or die "deflation failed\n" ; + + print $output ; + } + + ($output, $status) = $x->flush() ; + + $status == Z_OK + or die "deflation failed\n" ; + + print $output ; + +=head1 Inflate Interface + +This section defines the interface available that allows in-memory +uncompression using the I interface provided by zlib. + +Here is a definition of the interface: + +=head2 B<($i, $status) = inflateInit()> + +Initialises an inflation stream. + +In a list context it returns the inflation stream, C<$i>, and the +I status code in C<$status>. In a scalar context it returns the +inflation stream only. + +If successful, C<$i> will hold the inflation stream and C<$status> will +be C. + +If not successful, C<$i> will be I and C<$status> will hold the +I error code. + +The function optionally takes a number of named options specified as +C<< -Name=>value >> pairs. This allows individual options to be +tailored without having to specify them all in the parameter list. + +For backward compatibility, it is also possible to pass the parameters +as a reference to a hash containing the name=>value pairs. + +The function takes one optional parameter, a reference to a hash. The +contents of the hash allow the deflation interface to be tailored. + +Here is a list of the valid options: + +=over 5 + +=item B<-WindowBits> + +To uncompress an RFC 1950 data stream, set C to a positive number. + +To uncompress an RFC 1951 data stream, set C to C<-MAX_WBITS>. + +For a full definition of the meaning and valid values for C refer +to the I documentation for I. + +Defaults to MAX_WBITS. + +=item B<-Bufsize> + +Sets the initial size for the inflation buffer. If the buffer has to be +reallocated to increase the size, it will grow in increments of +C. + +Default is 4096. + +=item B<-Dictionary> + +The default is no dictionary. + +=back + +Here is an example of using the C optional parameter to +override the default buffer size. + + inflateInit( -Bufsize => 300 ) ; + +=head2 B<($out, $status) = $i-Einflate($buffer)> + +Inflates the complete contents of C<$buffer>. The buffer can either be +a scalar or a scalar reference. + +Returns C if successful and C if the end of the +compressed data has been successfully reached. +If not successful, C<$out> will be I and C<$status> will hold +the I error code. + +The C<$buffer> parameter is modified by C. On completion it +will contain what remains of the input buffer after inflation. This +means that C<$buffer> will be an empty string when the return status is +C. When the return status is C the C<$buffer> +parameter will contains what (if anything) was stored in the input +buffer after the deflated data stream. + +This feature is useful when processing a file format that encapsulates +a compressed data stream (e.g. gzip, zip). + +=head2 B<$status = $i-EinflateSync($buffer)> + +Scans C<$buffer> until it reaches either a I or the +end of the buffer. + +If a I is found, C is returned and C<$buffer> +will be have all data up to the flush point removed. This can then be +passed to the C method. + +Any other return code means that a flush point was not found. If more +data is available, C can be called repeatedly with more +compressed data until the flush point is found. + +=head2 B<$i-Edict_adler()> + +Returns the adler32 value for the dictionary. + +=head2 B<$i-Emsg()> + +Returns the last error message generated by zlib. + +=head2 B<$i-Etotal_in()> + +Returns the total number of bytes compressed bytes input to inflate. + +=head2 B<$i-Etotal_out()> + +Returns the total number of uncompressed bytes output from inflate. + +=head2 Example + +Here is an example of using C. + + use strict ; + use warnings ; + + use Compress::Zlib ; + + my $x = inflateInit() + or die "Cannot create a inflation stream\n" ; + + my $input = '' ; + binmode STDIN; + binmode STDOUT; + + my ($output, $status) ; + while (read(STDIN, $input, 4096)) + { + ($output, $status) = $x->inflate(\$input) ; + + print $output + if $status == Z_OK or $status == Z_STREAM_END ; + + last if $status != Z_OK ; + } + + die "inflation failed\n" + unless $status == Z_STREAM_END ; + +=head1 CHECKSUM FUNCTIONS + +Two functions are provided by I to calculate checksums. For the +Perl interface, the order of the two parameters in both functions has +been reversed. This allows both running checksums and one off +calculations to be done. + + $crc = adler32($buffer [,$crc]) ; + $crc = crc32($buffer [,$crc]) ; + +The buffer parameters can either be a scalar or a scalar reference. + +If the $crc parameters is C, the crc value will be reset. + +If you have built this module with zlib 1.2.3 or better, two more +CRC-related functions are available. + + $crc = crc32_combine($crc1, $crc2, $len2); + $adler = adler32_combine($adler1, $adler2, $len2); + +These functions allow checksums to be merged. +Refer to the I documentation for more details. + +=head1 Misc + +=head2 my $version = Compress::Zlib::zlib_version(); + +Returns the version of the zlib library. + +=head1 CONSTANTS + +All the I constants are automatically imported when you make use +of I. + +=head1 SUPPORT + +General feedback/questions/bug reports should be sent to +L (preferred) or +L. + +=head1 SEE ALSO + +L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L + +L + +L, L, +L, +L + +For RFC 1950, 1951 and 1952 see +L, +L and +L + +The I compression library was written by Jean-loup Gailly +C and Mark Adler C. + +The primary site for the I compression library is +L. + +The primary site for the I compression library is +L. + +The primary site for gzip is L. + +=head1 AUTHOR + +This module was written by Paul Marquess, C. + +=head1 MODIFICATION HISTORY + +See the Changes file. + +=head1 COPYRIGHT AND LICENSE + +Copyright (c) 1995-2024 Paul Marquess. All rights reserved. + +This program is free software; you can redistribute it and/or +modify it under the same terms as Perl itself. diff --git a/git/usr/share/perl5/core_perl/Config/Extensions.pm b/git/usr/share/perl5/core_perl/Config/Extensions.pm new file mode 100644 index 0000000000000000000000000000000000000000..b92ebf8ab8299d3a4741768a144bd9b1c45c9c99 --- /dev/null +++ b/git/usr/share/perl5/core_perl/Config/Extensions.pm @@ -0,0 +1,64 @@ +package Config::Extensions; +use strict; +our (%Extensions, $VERSION, @ISA, @EXPORT_OK); +use Config; +require Exporter; + +$VERSION = '0.03'; +@ISA = 'Exporter'; +@EXPORT_OK = '%Extensions'; + +foreach my $type (qw(static dynamic nonxs)) { + foreach (split /\s+/, $Config{$type . '_ext'}) { + s!/!::!g; + $Extensions{$_} = $type; + } +} + +1; +__END__ + +=head1 NAME + +Config::Extensions - hash lookup of which core extensions were built. + +=head1 SYNOPSIS + + use Config::Extensions '%Extensions'; + if ($Extensions{PerlIO::via}) { + # This perl has PerlIO::via built + } + +=head1 DESCRIPTION + +The Config::Extensions module provides a hash C<%Extensions> containing all +the core extensions that were enabled for this perl. The hash is keyed by +extension name, with each entry having one of 3 possible values: + +=over 4 + +=item dynamic + +The extension is dynamically linked + +=item nonxs + +The extension is pure perl, so doesn't need linking to the perl executable + +=item static + +The extension is statically linked to the perl binary + +=back + +As all values evaluate to true, a simple C test is good enough to determine +whether an extension is present. + +All the data uses to generate the C<%Extensions> hash is already present in +the C module, but not in such a convenient format to quickly reference. + +=head1 AUTHOR + +Nicholas Clark + +=cut diff --git a/git/usr/share/perl5/core_perl/DBM_Filter/compress.pm b/git/usr/share/perl5/core_perl/DBM_Filter/compress.pm new file mode 100644 index 0000000000000000000000000000000000000000..cb286a73bd00100279672cb248c71cc18ea86f16 --- /dev/null +++ b/git/usr/share/perl5/core_perl/DBM_Filter/compress.pm @@ -0,0 +1,53 @@ +package DBM_Filter::compress ; + +use strict; +use warnings; +use Carp; + +our $VERSION = '0.03'; + +BEGIN +{ + eval { require Compress::Zlib; Compress::Zlib->import() }; + + croak "Compress::Zlib module not found.\n" + if $@; +} + + + +sub Store { $_ = compress($_) } +sub Fetch { $_ = uncompress($_) } + +1; + +__END__ + +=head1 NAME + +DBM_Filter::compress - filter for DBM_Filter + +=head1 SYNOPSIS + + use SDBM_File; # or DB_File, GDBM_File, NDBM_File, ODBM_File + use DBM_Filter ; + + $db = tie %hash, ... + $db->Filter_Push('compress'); + +=head1 DESCRIPTION + +This DBM filter will compress all data before it is written to the database +and uncompressed it on reading. + +A fatal error will be thrown if the Compress::Zlib module is not +available. + +=head1 SEE ALSO + +L, L, L + +=head1 AUTHOR + +Paul Marquess pmqs@cpan.org + diff --git a/git/usr/share/perl5/core_perl/DBM_Filter/encode.pm b/git/usr/share/perl5/core_perl/DBM_Filter/encode.pm new file mode 100644 index 0000000000000000000000000000000000000000..907f51d73ee434a840da273119f00ee0ada63c7f --- /dev/null +++ b/git/usr/share/perl5/core_perl/DBM_Filter/encode.pm @@ -0,0 +1,86 @@ +package DBM_Filter::encode ; + +use strict; +use warnings; +use Carp; + +our $VERSION = '0.03'; + +BEGIN +{ + eval { require Encode; }; + + croak "Encode module not found.\n" + if $@; +} + + +sub Filter +{ + my $encoding_name = shift || "utf8"; + + my $encoding = Encode::find_encoding($encoding_name) ; + + croak "Encoding '$encoding_name' is not available" + unless $encoding; + + return { + Store => sub { + $_ = $encoding->encode($_) + if defined $_ ; + }, + Fetch => sub { + $_ = $encoding->decode($_) + if defined $_ ; + } + } ; +} + +1; + +__END__ + +=head1 NAME + +DBM_Filter::encode - filter for DBM_Filter + +=head1 SYNOPSIS + + use SDBM_File; # or DB_File, GDBM_File, NDBM_File, ODBM_File + use DBM_Filter ; + + $db = tie %hash, ... + $db->Filter_Push('encode' => 'iso-8859-16'); + +=head1 DESCRIPTION + +This DBM filter allows you to choose the character encoding will be +store in the DBM file. The usage is + + $db->Filter_Push('encode' => ENCODING); + +where "ENCODING" must be a valid encoding name that the Encode module +recognises. + +A fatal error will be thrown if: + +=over 5 + +=item 1 + +The Encode module is not available. + +=item 2 + +The encoding requested is not supported by the Encode module. + +=back + +=head1 SEE ALSO + +L, L, L + +=head1 AUTHOR + +Paul Marquess pmqs@cpan.org + diff --git a/git/usr/share/perl5/core_perl/DBM_Filter/int32.pm b/git/usr/share/perl5/core_perl/DBM_Filter/int32.pm new file mode 100644 index 0000000000000000000000000000000000000000..bedcebad660825c98bd9f4e2af627e122bd5a1b7 --- /dev/null +++ b/git/usr/share/perl5/core_perl/DBM_Filter/int32.pm @@ -0,0 +1,50 @@ +package DBM_Filter::int32 ; + +use strict; +use warnings; + +our $VERSION = '0.03'; + +# todo get Filter to figure endian. + +sub Store +{ + $_ = 0 if ! defined $_ || $_ eq "" ; + $_ = pack("i", $_); +} + +sub Fetch +{ + no warnings 'uninitialized'; + $_ = unpack("i", $_); +} + +1; + +__END__ + +=head1 NAME + +DBM_Filter::int32 - filter for DBM_Filter + +=head1 SYNOPSIS + + use SDBM_File; # or DB_File, GDBM_File, NDBM_File, or ODBM_File + use DBM_Filter ; + + $db = tie %hash, ... + $db->Filter_Push('int32'); + +=head1 DESCRIPTION + +This DBM filter is used when interoperating with a C/C++ application +that uses a C int as either the key and/or value in the DBM file. + +=head1 SEE ALSO + +L, L + +=head1 AUTHOR + +Paul Marquess pmqs@cpan.org + diff --git a/git/usr/share/perl5/core_perl/DBM_Filter/null.pm b/git/usr/share/perl5/core_perl/DBM_Filter/null.pm new file mode 100644 index 0000000000000000000000000000000000000000..d06ffac8f661f0e1c2de0187bb4a404d80d664b0 --- /dev/null +++ b/git/usr/share/perl5/core_perl/DBM_Filter/null.pm @@ -0,0 +1,52 @@ +package DBM_Filter::null ; + +use strict; +use warnings; + +our $VERSION = '0.03'; + +sub Store +{ + no warnings 'uninitialized'; + $_ .= "\x00" ; +} + +sub Fetch +{ + no warnings 'uninitialized'; + s/\x00$// ; +} + +1; + +__END__ + +=head1 NAME + +DBM_Filter::null - filter for DBM_Filter + +=head1 SYNOPSIS + + use SDBM_File; # or DB_File, GDBM_File, NDBM_File, or ODBM_File + use DBM_Filter ; + + $db = tie %hash, ... + $db->Filter_Push('null'); + +=head1 DESCRIPTION + +This filter ensures that all data written to the DBM file is null +terminated. This is useful when you have a perl script that needs +to interoperate with a DBM file that a C program also uses. A fairly +common issue is for the C application to include the terminating null +in a string when it writes to the DBM file. This filter will ensure that +all data written to the DBM file can be read by the C application. + + +=head1 SEE ALSO + +L, L + +=head1 AUTHOR + +Paul Marquess pmqs@cpan.org diff --git a/git/usr/share/perl5/core_perl/DBM_Filter/utf8.pm b/git/usr/share/perl5/core_perl/DBM_Filter/utf8.pm new file mode 100644 index 0000000000000000000000000000000000000000..56efd12f082ef0df8a9acd9da7cba26c1eb36b0e --- /dev/null +++ b/git/usr/share/perl5/core_perl/DBM_Filter/utf8.pm @@ -0,0 +1,51 @@ +package DBM_Filter::utf8 ; + +use strict; +use warnings; +use Carp; + +our $VERSION = '0.03'; + +BEGIN +{ + eval { require Encode; }; + + croak "Encode module not found.\n" + if $@; +} + +sub Store { $_ = Encode::encode_utf8($_) if defined $_ } + +sub Fetch { $_ = Encode::decode_utf8($_) if defined $_ } + +1; + +__END__ + +=head1 NAME + +DBM_Filter::utf8 - filter for DBM_Filter + +=head1 SYNOPSIS + + use SDBM_File; # or DB_File, GDBM_File, NDBM_File, or ODBM_File + use DBM_Filter; + + $db = tie %hash, ... + $db->Filter_Push('utf8'); + +=head1 DESCRIPTION + +This Filter will ensure that all data written to the DBM will be encoded +in UTF-8. + +This module uses the Encode module. + +=head1 SEE ALSO + +L, L, L + +=head1 AUTHOR + +Paul Marquess pmqs@cpan.org + diff --git a/git/usr/share/perl5/core_perl/Devel/SelfStubber.pm b/git/usr/share/perl5/core_perl/Devel/SelfStubber.pm new file mode 100644 index 0000000000000000000000000000000000000000..781dd9f3e971095ae2183b869249621a45bf0963 --- /dev/null +++ b/git/usr/share/perl5/core_perl/Devel/SelfStubber.pm @@ -0,0 +1,152 @@ +package Devel::SelfStubber; +use File::Spec; +require SelfLoader; +@ISA = qw(SelfLoader); +@EXPORT = 'AUTOLOAD'; +$JUST_STUBS = 1; +$VERSION = 1.06; +sub Version {$VERSION} + +# Use as +# perl -e 'use Devel::SelfStubber;Devel::SelfStubber->stub(MODULE_NAME,LIB)' +# (LIB defaults to '.') e.g. +# perl -e 'use Devel::SelfStubber;Devel::SelfStubber->stub('Math::BigInt')' +# would print out stubs needed if you added a __DATA__ before the subs. +# Setting $Devel::SelfStubber::JUST_STUBS to 0 will print out the whole +# module with the stubs entered just before the __DATA__ + +sub _add_to_cache { + my($self,$fullname,$pack,$lines, $prototype) = @_; + push(@DATA,@{$lines}); + if($fullname){push(@STUBS,"sub $fullname $prototype;\n")}; # stubs + '1;'; +} + +sub _package_defined { + my($self,$line) = @_; + push(@DATA,$line); +} + +sub stub { + my($self,$module,$lib) = @_; + my($line,$end_data,$fh,$mod_file,$found_selfloader); + $lib ||= File::Spec->curdir(); + ($mod_file = $module) =~ s,::,/,g; + $mod_file =~ tr|/|:| if $^O eq 'MacOS'; + + $mod_file = File::Spec->catfile($lib, "$mod_file.pm"); + $fh = "${module}::DATA"; + my (@BEFORE_DATA, @AFTER_DATA, @AFTER_END); + @DATA = @STUBS = (); + + open($fh,'<',$mod_file) || die "Unable to open $mod_file"; + local $/ = "\n"; + while(defined ($line = <$fh>) and $line !~ m/^__DATA__/) { + push(@BEFORE_DATA,$line); + $line =~ /use\s+SelfLoader/ && $found_selfloader++; + } + (defined ($line) && $line =~ m/^__DATA__/) + || die "$mod_file doesn't contain a __DATA__ token"; + $found_selfloader || + print 'die "\'use SelfLoader;\' statement NOT FOUND!!\n"',"\n"; + if ($JUST_STUBS) { + $self->_load_stubs($module); + } else { + $self->_load_stubs($module, \@AFTER_END); + } + if ( fileno($fh) ) { + $end_data = 1; + while(defined($line = <$fh>)) { + push(@AFTER_DATA,$line); + } + } + close($fh); + unless ($JUST_STUBS) { + print @BEFORE_DATA; + } + print @STUBS; + unless ($JUST_STUBS) { + print "1;\n__DATA__\n",@DATA; + if($end_data) { print "__END__ DATA\n",@AFTER_DATA; } + if(@AFTER_END) { print "__END__\n",@AFTER_END; } + } +} + +1; +__END__ + +=head1 NAME + +Devel::SelfStubber - generate stubs for a SelfLoading module + +=head1 SYNOPSIS + +To generate just the stubs: + + use Devel::SelfStubber; + Devel::SelfStubber->stub('MODULENAME','MY_LIB_DIR'); + +or to generate the whole module with stubs inserted correctly + + use Devel::SelfStubber; + $Devel::SelfStubber::JUST_STUBS=0; + Devel::SelfStubber->stub('MODULENAME','MY_LIB_DIR'); + +MODULENAME is the Perl module name, e.g. Devel::SelfStubber, +NOT 'Devel/SelfStubber' or 'Devel/SelfStubber.pm'. + +MY_LIB_DIR defaults to '.' if not present. + +=head1 DESCRIPTION + +Devel::SelfStubber prints the stubs you need to put in the module +before the __DATA__ token (or you can get it to print the entire +module with stubs correctly placed). The stubs ensure that if +a method is called, it will get loaded. They are needed specifically +for inherited autoloaded methods. + +This is best explained using the following example: + +Assume four classes, A,B,C & D. + +A is the root class, B is a subclass of A, C is a subclass of B, +and D is another subclass of A. + + A + / \ + B D + / + C + +If D calls an autoloaded method 'foo' which is defined in class A, +then the method is loaded into class A, then executed. If C then +calls method 'foo', and that method was reimplemented in class +B, but set to be autoloaded, then the lookup mechanism never gets to +the AUTOLOAD mechanism in B because it first finds the method +already loaded in A, and so erroneously uses that. If the method +foo had been stubbed in B, then the lookup mechanism would have +found the stub, and correctly loaded and used the sub from B. + +So, for classes and subclasses to have inheritance correctly +work with autoloading, you need to ensure stubs are loaded. + +The SelfLoader can load stubs automatically at module initialization +with the statement 'SelfLoader-Eload_stubs()';, but you may wish to +avoid having the stub loading overhead associated with your +initialization (though note that the SelfLoader::load_stubs method +will be called sooner or later - at latest when the first sub +is being autoloaded). In this case, you can put the sub stubs +before the __DATA__ token. This can be done manually, but this +module allows automatic generation of the stubs. + +By default it just prints the stubs, but you can set the +global $Devel::SelfStubber::JUST_STUBS to 0 and it will +print out the entire module with the stubs positioned correctly. + +At the very least, this is useful to see what the SelfLoader +thinks are stubs - in order to ensure future versions of the +SelfStubber remain in step with the SelfLoader, the +SelfStubber actually uses the SelfLoader to determine which +stubs are needed. + +=cut diff --git a/git/usr/share/perl5/core_perl/Digest/base.pm b/git/usr/share/perl5/core_perl/Digest/base.pm new file mode 100644 index 0000000000000000000000000000000000000000..539559b261ed8ac5b1c5dfe6e7d5d3bad6747cec --- /dev/null +++ b/git/usr/share/perl5/core_perl/Digest/base.pm @@ -0,0 +1,106 @@ +package Digest::base; + +use strict; +use warnings; + +our $VERSION = "1.20"; + +# subclass is supposed to implement at least these +sub new; +sub clone; +sub add; +sub digest; + +sub reset { + my $self = shift; + $self->new(@_); # ugly +} + +sub addfile { + my ( $self, $handle ) = @_; + + my $n; + my $buf = ""; + + while ( ( $n = read( $handle, $buf, 4 * 1024 ) ) ) { + $self->add($buf); + } + unless ( defined $n ) { + require Carp; + Carp::croak("Read failed: $!"); + } + + $self; +} + +sub add_bits { + my $self = shift; + my $bits; + my $nbits; + if ( @_ == 1 ) { + my $arg = shift; + $bits = pack( "B*", $arg ); + $nbits = length($arg); + } + else { + ( $bits, $nbits ) = @_; + } + if ( ( $nbits % 8 ) != 0 ) { + require Carp; + Carp::croak("Number of bits must be multiple of 8 for this algorithm"); + } + return $self->add( substr( $bits, 0, $nbits / 8 ) ); +} + +sub hexdigest { + my $self = shift; + return unpack( "H*", $self->digest(@_) ); +} + +sub b64digest { + my $self = shift; + my $b64 = $self->base64_padded_digest; + $b64 =~ s/=+$//; + return $b64; +} + +sub base64_padded_digest { + my $self = shift; + require MIME::Base64; + return MIME::Base64::encode( $self->digest(@_), "" ); +} + +1; + +__END__ + +=head1 NAME + +Digest::base - Digest base class + +=head1 SYNOPSIS + + package Digest::Foo; + use base 'Digest::base'; + +=head1 DESCRIPTION + +The C class provide implementations of the methods +C and C in terms of C, and of the methods +C and C in terms of C. + +Digest implementations might want to inherit from this class to get +this implementations of the alternative I and I methods. +A minimal subclass needs to implement the following methods by itself: + + new + clone + add + digest + +The arguments and expected behaviour of these methods are described in +L. + +=head1 SEE ALSO + +L diff --git a/git/usr/share/perl5/core_perl/Digest/file.pm b/git/usr/share/perl5/core_perl/Digest/file.pm new file mode 100644 index 0000000000000000000000000000000000000000..088fabf4b943111acb3f9dfb937f4501c46870ea --- /dev/null +++ b/git/usr/share/perl5/core_perl/Digest/file.pm @@ -0,0 +1,83 @@ +package Digest::file; + +use strict; +use warnings; + +use Exporter (); +use Carp qw(croak); +use Digest (); + +our $VERSION = "1.20"; +our @ISA = qw(Exporter); +our @EXPORT_OK = qw(digest_file_ctx digest_file digest_file_hex digest_file_base64); + +sub digest_file_ctx { + my $file = shift; + croak("No digest algorithm specified") unless @_; + open( my $fh, "<", $file ) || croak("Can't open '$file': $!"); + binmode($fh); + my $ctx = Digest->new(@_); + $ctx->addfile($fh); + close($fh); + return $ctx; +} + +sub digest_file { + digest_file_ctx(@_)->digest; +} + +sub digest_file_hex { + digest_file_ctx(@_)->hexdigest; +} + +sub digest_file_base64 { + digest_file_ctx(@_)->b64digest; +} + +1; + +__END__ + +=head1 NAME + +Digest::file - Calculate digests of files + +=head1 SYNOPSIS + + # Poor mans "md5sum" command + use Digest::file qw(digest_file_hex); + for (@ARGV) { + print digest_file_hex($_, "MD5"), " $_\n"; + } + +=head1 DESCRIPTION + +This module provide 3 convenience functions to calculate the digest +of files. The following functions are provided: + +=over + +=item digest_file( $file, $algorithm, [$arg,...] ) + +This function will calculate and return the binary digest of the bytes +of the given file. The function will croak if it fails to open or +read the file. + +The $algorithm is a string like "MD2", "MD5", "SHA-1", "SHA-512". +Additional arguments are passed to the constructor for the +implementation of the given algorithm. + +=item digest_file_hex( $file, $algorithm, [$arg,...] ) + +Same as digest_file(), but return the digest in hex form. + +=item digest_file_base64( $file, $algorithm, [$arg,...] ) + +Same as digest_file(), but return the digest as a base64 encoded +string. + +=back + +=head1 SEE ALSO + +L diff --git a/git/usr/share/perl5/core_perl/Encode/Changes.e2x b/git/usr/share/perl5/core_perl/Encode/Changes.e2x new file mode 100644 index 0000000000000000000000000000000000000000..5c67c55cb93b4091a71a5daa2f6504cb31cdd7c1 --- /dev/null +++ b/git/usr/share/perl5/core_perl/Encode/Changes.e2x @@ -0,0 +1,7 @@ +# +# $Id: Changes.e2x,v 2.0 2004/05/16 20:55:15 dankogai Exp $ +# Revision history for Perl extension Encode::$_Name_. +# + +0.01 $_Now_ + Autogenerated by enc2xs version $_Version_. diff --git a/git/usr/share/perl5/core_perl/Encode/ConfigLocal_PM.e2x b/git/usr/share/perl5/core_perl/Encode/ConfigLocal_PM.e2x new file mode 100644 index 0000000000000000000000000000000000000000..e203dfded5025f71791feaf154643361d0020544 --- /dev/null +++ b/git/usr/share/perl5/core_perl/Encode/ConfigLocal_PM.e2x @@ -0,0 +1,13 @@ +# +# Local demand-load module list +# +# You should not edit this file by hand! use "enc2xs -C" +# +package Encode::ConfigLocal; +our $VERSION = $_LocalVer_; + +use strict; + +$_ModLines_ + +1; diff --git a/git/usr/share/perl5/core_perl/Encode/Makefile_PL.e2x b/git/usr/share/perl5/core_perl/Encode/Makefile_PL.e2x new file mode 100644 index 0000000000000000000000000000000000000000..c17a5096f79137d24e54c47419914bfc2d8a5279 --- /dev/null +++ b/git/usr/share/perl5/core_perl/Encode/Makefile_PL.e2x @@ -0,0 +1,190 @@ +# +# This file is auto-generated by: +# enc2xs version $_Version_ +# $_Now_ +# +use 5.7.2; +use strict; +use ExtUtils::MakeMaker; +use Config; + +# Please edit the following to the taste! +my $name = '$_Name_'; +my %tables = ( + $_Name__t => [ $_TableFiles_ ], + ); + +#### DO NOT EDIT BEYOND THIS POINT! +require File::Spec; +my ($enc2xs, $encode_h) = (); +my @path_ext = (''); +@path_ext = split(';', $ENV{PATHEXT}) if $^O eq 'MSWin32'; +PATHLOOP: +for my $d (@Config{qw/bin sitebin vendorbin/}, + (split /$Config{path_sep}/o, $ENV{PATH})){ + for my $f (qw/enc2xs enc2xs5.7.3/){ + my $path = File::Spec->catfile($d, $f); + for my $ext (@path_ext) { + my $bin = "$path$ext"; + -r "$bin" and $enc2xs = $bin and last PATHLOOP; + } + } +} +$enc2xs or die "enc2xs not found!"; +print "enc2xs is $enc2xs\n"; +my %encode_h = (); +for my $d (@INC){ + my $dir = File::Spec->catfile($d, "Encode"); + my $file = File::Spec->catfile($dir, "encode.h"); + -f $file and $encode_h{$dir} = -M $file; +} +%encode_h or die "encode.h not found!"; +# find the latest one +($encode_h) = sort {$encode_h{$b} <=> $encode_h{$a}} keys %encode_h; +print "encode.h is at $encode_h\n"; + +WriteMakefile( + INC => "-I$encode_h", +#### END_OF_HEADER -- DO NOT EDIT THIS LINE BY HAND! #### + NAME => 'Encode::'.$name, + VERSION_FROM => "$name.pm", + OBJECT => '$(O_FILES)', + 'dist' => { + COMPRESS => 'gzip -9f', + SUFFIX => 'gz', + DIST_DEFAULT => 'all tardist', + }, + MAN3PODS => {}, + PREREQ_PM => { + 'Encode' => "1.41", + }, + # OS 390 winges about line numbers > 64K ??? + XSOPT => '-nolinenumbers', + ); + +package MY; + +sub post_initialize +{ + my ($self) = @_; + my %o; + my $x = $self->{'OBJ_EXT'}; + # Add the table O_FILES + foreach my $e (keys %tables) + { + $o{$e.$x} = 1; + } + $o{"$name$x"} = 1; + $self->{'O_FILES'} = [sort keys %o]; + my @files = ("$name.xs"); + $self->{'C'} = ["$name.c"]; + # The next two lines to make MacPerl Happy -- dankogai via pudge + $self->{SOURCE} .= " $name.c" + if $^O eq 'MacOS' && $self->{SOURCE} !~ /\b$name\.c\b/; + # $self->{'H'} = [$self->catfile($self->updir,'encode.h')]; + my %xs; + foreach my $table (sort keys %tables) { + push (@{$self->{'C'}},"$table.c"); + # Do NOT add $table.h etc. to H_FILES unless we own up as to how they + # get built. + foreach my $ext (qw($(OBJ_EXT) .c .h .exh .fnm)) { + push (@files,$table.$ext); + } + } + $self->{'XS'} = { "$name.xs" => "$name.c" }; + $self->{'clean'}{'FILES'} .= join(' ',@files); + open(XS,">$name.xs") || die "Cannot open $name.xs:$!"; + print XS <<'END'; +#include +#include +#include +#include "encode.h" +END + foreach my $table (sort keys %tables) { + print XS qq[#include "${table}.h"\n]; + } + print XS <<"END"; + +static void +Encode_XSEncoding(pTHX_ encode_t *enc) +{ + dSP; + HV *stash = gv_stashpv("Encode::XS", TRUE); + SV *iv = newSViv(PTR2IV(enc)); + SV *sv = sv_bless(newRV_noinc(iv),stash); + int i = 0; + /* with the SvLEN() == 0 hack, PVX won't be freed. We cast away name's + constness, in the hope that perl won't mess with it. */ + assert(SvTYPE(iv) >= SVt_PV); assert(SvLEN(iv) == 0); + SvFLAGS(iv) |= SVp_POK; + SvPVX(iv) = (char*) enc->name[0]; + PUSHMARK(sp); + XPUSHs(sv); + while (enc->name[i]) + { + const char *name = enc->name[i++]; + XPUSHs(sv_2mortal(newSVpvn(name,strlen(name)))); + } + PUTBACK; + call_pv("Encode::define_encoding",G_DISCARD); + SvREFCNT_dec(sv); +} + +MODULE = Encode::$name PACKAGE = Encode::$name +PROTOTYPES: DISABLE +BOOT: +{ +END + foreach my $table (sort keys %tables) { + print XS qq[#include "${table}.exh"\n]; + } + print XS "}\n"; + close(XS); + return "# Built $name.xs\n\n"; +} + +sub postamble +{ + my $self = shift; + my $dir = "."; # $self->catdir('Encode'); + my $str = "# $name\$(OBJ_EXT) depends on .h and .exh files not .c files - but all written by enc2xs\n"; + $str .= "$name.c : $name.xs "; + foreach my $table (sort keys %tables) + { + $str .= " $table.c"; + } + $str .= "\n\n"; + $str .= "$name\$(OBJ_EXT) : $name.c\n\n"; + + foreach my $table (sort keys %tables) + { + my $numlines = 1; + my $lengthsofar = length($str); + my $continuator = ''; + $str .= "$table.c : Makefile.PL"; + foreach my $file (@{$tables{$table}}) + { + $str .= $continuator.' '.$self->catfile($dir,$file); + if ( length($str)-$lengthsofar > 128*$numlines ) + { + $continuator .= " \\\n\t"; + $numlines++; + } else { + $continuator = ''; + } + } + my $plib = $self->{PERL_CORE} ? '"-I$(PERL_LIB)"' : ''; + my $ucopts = '-"Q"'; + $str .= + qq{\n\t\$(PERL) $plib $enc2xs $ucopts -o \$\@ -f $table.fnm\n\n}; + open (FILELIST, ">$table.fnm") + || die "Could not open $table.fnm: $!"; + foreach my $file (@{$tables{$table}}) + { + print FILELIST $self->catfile($dir,$file) . "\n"; + } + close(FILELIST); + } + return $str; +} + diff --git a/git/usr/share/perl5/core_perl/Encode/README.e2x b/git/usr/share/perl5/core_perl/Encode/README.e2x new file mode 100644 index 0000000000000000000000000000000000000000..28a31a655c220973cc3fff33871214b664d084ce --- /dev/null +++ b/git/usr/share/perl5/core_perl/Encode/README.e2x @@ -0,0 +1,31 @@ +Encode::$_Name_ version 0.1 +======== + +NAME + Encode::$_Name_ - + +SYNOPSIS + use Encode::$_Name_; + # +ABSTRACT + +INSTALLATION + +To install this module type the following: + + perl Makefile.PL + make + make test + make install + +DEPENDENCIES + +This module requires perl version 5.7.3 or later. + +COPYRIGHT AND LICENCE + +Copyright (C) 2002 Your Name + +This library is free software; you can redistribute it and/or modify +it under the same terms as Perl itself. + diff --git a/git/usr/share/perl5/core_perl/Encode/_PM.e2x b/git/usr/share/perl5/core_perl/Encode/_PM.e2x new file mode 100644 index 0000000000000000000000000000000000000000..eb59cd1b520323bddb2f11d65d26b757d5e91c94 --- /dev/null +++ b/git/usr/share/perl5/core_perl/Encode/_PM.e2x @@ -0,0 +1,23 @@ +package Encode::$_Name_; +our $VERSION = "0.01"; + +use Encode; +use XSLoader; +XSLoader::load(__PACKAGE__,$VERSION); + +1; +__END__ + +=head1 NAME + +Encode::$_Name_ - New Encoding + +=head1 SYNOPSIS + +You got to fill this in! + +=head1 SEE ALSO + +L + +=cut diff --git a/git/usr/share/perl5/core_perl/Encode/_T.e2x b/git/usr/share/perl5/core_perl/Encode/_T.e2x new file mode 100644 index 0000000000000000000000000000000000000000..7b9a67e43d74454c1f8f9f607fd460a8e2047ee0 --- /dev/null +++ b/git/usr/share/perl5/core_perl/Encode/_T.e2x @@ -0,0 +1,9 @@ +use strict; +# Adjust the number here! +use Test::More tests => 2; + +BEGIN { + use_ok('Encode'); + use_ok('Encode::$_Name_'); +} +# Add more test here! diff --git a/git/usr/share/perl5/core_perl/Exporter/Heavy.pm b/git/usr/share/perl5/core_perl/Exporter/Heavy.pm new file mode 100644 index 0000000000000000000000000000000000000000..8c70abefb7839b3ac6bfa797055d69b25872f168 --- /dev/null +++ b/git/usr/share/perl5/core_perl/Exporter/Heavy.pm @@ -0,0 +1,250 @@ +package Exporter::Heavy; + +use strict; +no strict 'refs'; + +our $VERSION = '5.79'; + +=head1 NAME + +Exporter::Heavy - Exporter guts + +=head1 SYNOPSIS + +(internal use only) + +=head1 DESCRIPTION + +No user-serviceable parts inside. + +=cut + +# +# We go to a lot of trouble not to 'require Carp' at file scope, +# because Carp requires Exporter, and something has to give. +# + +sub _rebuild_cache { + my ($pkg, $exports, $cache) = @_; + s/^&// foreach @$exports; + @{$cache}{@$exports} = (1) x @$exports; + my $ok = \@{"${pkg}::EXPORT_OK"}; + if (@$ok) { + s/^&// foreach @$ok; + @{$cache}{@$ok} = (1) x @$ok; + } +} + +sub heavy_export { + + # Save the old __WARN__ handler in case it was defined + my $oldwarn = $SIG{__WARN__} || sub { warn $_[0] }; + + # First make import warnings look like they're coming from the "use". + local $SIG{__WARN__} = sub { + my $text = shift; + if ($text =~ s/ at \S*Exporter\S*.pm line \d+.*\n//) { + require Carp; + local $Carp::CarpLevel = 1; # ignore package calling us too. + $oldwarn->(Carp::shortmess($text)); + } + else { + $oldwarn->($text); + } + }; + local $SIG{__DIE__} = sub { + require Carp; + local $Carp::CarpLevel = 1; # ignore package calling us too. + Carp::croak("$_[0]Illegal null symbol in \@${1}::EXPORT") + if $_[0] =~ /^Unable to create sub named "(.*?)::"/; + }; + + my($pkg, $callpkg, @imports) = @_; + my($type, $sym, $cache_is_current, $oops); + my($exports, $export_cache) = (\@{"${pkg}::EXPORT"}, + $Exporter::Cache{$pkg} ||= {}); + + if (@imports) { + if (!%$export_cache) { + _rebuild_cache ($pkg, $exports, $export_cache); + $cache_is_current = 1; + } + + if (grep m{^[/!:]}, @imports) { + my $tagsref = \%{"${pkg}::EXPORT_TAGS"}; + my $tagdata; + my %imports; + my($remove, $spec, @names, @allexports); + # negated first item implies starting with default set: + unshift @imports, ':DEFAULT' if $imports[0] =~ m/^!/; + foreach $spec (@imports){ + $remove = $spec =~ s/^!//; + + if ($spec =~ s/^://){ + if ($spec eq 'DEFAULT'){ + @names = @$exports; + } + elsif ($tagdata = $tagsref->{$spec}) { + @names = @$tagdata; + } + else { + warn qq["$spec" is not defined in %${pkg}::EXPORT_TAGS]; + ++$oops; + next; + } + } + elsif ($spec =~ m:^/(.*)/$:){ + my $patn = $1; + @allexports = keys %$export_cache unless @allexports; # only do keys once + @names = grep(/$patn/, @allexports); # not anchored by default + } + else { + @names = ($spec); # is a normal symbol name + } + + warn "Import ".($remove ? "del":"add").": @names " + if $Exporter::Verbose; + + if ($remove) { + foreach $sym (@names) { delete $imports{$sym} } + } + else { + @imports{@names} = (1) x @names; + } + } + @imports = keys %imports; + } + + my @carp; + foreach $sym (@imports) { + if (!$export_cache->{$sym}) { + if ($sym =~ m/^\d/) { + $pkg->VERSION($sym); # inherit from UNIVERSAL + # If the version number was the only thing specified + # then we should act as if nothing was specified: + if (@imports == 1) { + @imports = @$exports; + last; + } + # We need a way to emulate 'use Foo ()' but still + # allow an easy version check: "use Foo 1.23, ''"; + if (@imports == 2 and !$imports[1]) { + @imports = (); + last; + } + } elsif ($sym !~ s/^&// || !$export_cache->{$sym}) { + # Last chance - see if they've updated EXPORT_OK since we + # cached it. + + unless ($cache_is_current) { + %$export_cache = (); + _rebuild_cache ($pkg, $exports, $export_cache); + $cache_is_current = 1; + } + + if (!$export_cache->{$sym}) { + # accumulate the non-exports + push @carp, + qq["$sym" is not exported by the $pkg module]; + $oops++; + } + } + } + } + if ($oops) { + require Carp; + Carp::croak(join("\n", @carp, "Can't continue after import errors")); + } + } + else { + @imports = @$exports; + } + + my($fail, $fail_cache) = (\@{"${pkg}::EXPORT_FAIL"}, + $Exporter::FailCache{$pkg} ||= {}); + + if (@$fail) { + if (!%$fail_cache) { + # Build cache of symbols. Optimise the lookup by adding + # barewords twice... both with and without a leading &. + # (Technique could be applied to $export_cache at cost of memory) + my @expanded = map { /^\w/ ? ($_, '&'.$_) : $_ } @$fail; + warn "${pkg}::EXPORT_FAIL cached: @expanded" if $Exporter::Verbose; + @{$fail_cache}{@expanded} = (1) x @expanded; + } + my @failed; + foreach $sym (@imports) { push(@failed, $sym) if $fail_cache->{$sym} } + if (@failed) { + @failed = $pkg->export_fail(@failed); + foreach $sym (@failed) { + require Carp; + Carp::carp(qq["$sym" is not implemented by the $pkg module ], + "on this architecture"); + } + if (@failed) { + require Carp; + Carp::croak("Can't continue after import errors"); + } + } + } + + warn "Importing into $callpkg from $pkg: ", + join(", ",sort @imports) if $Exporter::Verbose; + + foreach $sym (@imports) { + # shortcut for the common case of no type character + (*{"${callpkg}::$sym"} = \&{"${pkg}::$sym"}, next) + unless $sym =~ s/^(\W)//; + $type = $1; + no warnings 'once'; + *{"${callpkg}::$sym"} = + $type eq '&' ? \&{"${pkg}::$sym"} : + $type eq '$' ? \${"${pkg}::$sym"} : + $type eq '@' ? \@{"${pkg}::$sym"} : + $type eq '%' ? \%{"${pkg}::$sym"} : + $type eq '*' ? *{"${pkg}::$sym"} : + do { require Carp; Carp::croak("Can't export symbol: $type$sym") }; + } +} + +sub heavy_export_to_level +{ + my $pkg = shift; + my $level = shift; + (undef) = shift; # XXX redundant arg + my $callpkg = caller($level); + $pkg->export($callpkg, @_); +} + +# Utility functions + +sub _push_tags { + my($pkg, $var, $syms) = @_; + my @nontag = (); + my $export_tags = \%{"${pkg}::EXPORT_TAGS"}; + push(@{"${pkg}::$var"}, + map { $export_tags->{$_} ? @{$export_tags->{$_}} + : scalar(push(@nontag,$_),$_) } + (@$syms) ? @$syms : keys %$export_tags); + if (@nontag and $^W) { + # This may change to a die one day + require Carp; + Carp::carp(join(", ", @nontag)." are not tags of $pkg"); + } +} + +sub heavy_require_version { + my($self, $wanted) = @_; + my $pkg = ref $self || $self; + return ${pkg}->VERSION($wanted); +} + +sub heavy_export_tags { + _push_tags((caller)[0], "EXPORT", \@_); +} + +sub heavy_export_ok_tags { + _push_tags((caller)[0], "EXPORT_OK", \@_); +} + +1; diff --git a/git/usr/share/perl5/core_perl/File/Basename.pm b/git/usr/share/perl5/core_perl/File/Basename.pm new file mode 100644 index 0000000000000000000000000000000000000000..c3c611fbbc261a8495f143478746939fe516887e --- /dev/null +++ b/git/usr/share/perl5/core_perl/File/Basename.pm @@ -0,0 +1,402 @@ +=head1 NAME + +File::Basename - Parse file paths into directory, filename and suffix. + +=head1 SYNOPSIS + + use File::Basename; + + my ($name, $path, $suffix) = fileparse($fullname, @suffixlist); + my $name = fileparse($fullname, @suffixlist); + + my $basename = basename($fullname, @suffixlist); + my $dirname = dirname($fullname); + + +=head1 DESCRIPTION + +These routines allow you to parse file paths into their directory, filename +and suffix. + +B: C and C emulate the behaviours, and +quirks, of the shell and C functions of the same name. See each +function's documentation for details. If your concern is just parsing +paths it is safer to use L's C and +C methods. + +It is guaranteed that + + # Where $path_separator is / for Unix, \ for Windows, etc... + dirname($path) . $path_separator . basename($path); + +is equivalent to the original path for all systems but VMS. + + +=cut + + +package File::Basename; + +# File::Basename is used during the Perl build, when the re extension may +# not be available, but we only actually need it if running under tainting. +BEGIN { + if (${^TAINT}) { + require re; + re->import('taint'); + } +} + + +use strict; +use 5.006; +use warnings; +our(@ISA, @EXPORT, $VERSION, $Fileparse_fstype, $Fileparse_igncase); +require Exporter; +@ISA = qw(Exporter); +@EXPORT = qw(fileparse fileparse_set_fstype basename dirname); +$VERSION = "2.86"; + +fileparse_set_fstype($^O); + + +=over 4 + +=item C +X + + my($filename, $dirs, $suffix) = fileparse($path); + my($filename, $dirs, $suffix) = fileparse($path, @suffixes); + my $filename = fileparse($path, @suffixes); + +The C routine divides a file path into its $dirs, $filename +and (optionally) the filename $suffix. + +$dirs contains everything up to and including the last +directory separator in the $path including the volume (if applicable). +The remainder of the $path is the $filename. + + # On Unix returns ("baz", "/foo/bar/", "") + fileparse("/foo/bar/baz"); + + # On Windows returns ("baz", 'C:\foo\bar\', "") + fileparse('C:\foo\bar\baz'); + + # On Unix returns ("", "/foo/bar/baz/", "") + fileparse("/foo/bar/baz/"); + +If @suffixes are given each element is a pattern (either a string or a +C) matched against the end of the $filename. The matching +portion is removed and becomes the $suffix. + + # On Unix returns ("baz", "/foo/bar/", ".txt") + fileparse("/foo/bar/baz.txt", qr/\.[^.]*/); + +If type is non-Unix (see L) then the pattern +matching for suffix removal is performed case-insensitively, since +those systems are not case-sensitive when opening existing files. + +You are guaranteed that C<$dirs . $filename . $suffix> will +denote the same location as the original $path. + +=cut + + +sub fileparse { + my($fullname,@suffices) = @_; + + unless (defined $fullname) { + require Carp; + Carp::croak("fileparse(): need a valid pathname"); + } + + my $orig_type = ''; + my($type,$igncase) = ($Fileparse_fstype, $Fileparse_igncase); + + my($taint) = substr($fullname,0,0); # Is $fullname tainted? + + if ($type eq "VMS" and $fullname =~ m{/} ) { + # We're doing Unix emulation + $orig_type = $type; + $type = 'Unix'; + } + + my($dirpath, $basename); + + if (grep { $type eq $_ } qw(MSDOS DOS MSWin32 Epoc)) { + ($dirpath,$basename) = ($fullname =~ /^((?:.*[:\\\/])?)(.*)/s); + $dirpath .= '.\\' unless $dirpath =~ /[\\\/]\z/; + } + elsif ($type eq "OS2") { + ($dirpath,$basename) = ($fullname =~ m#^((?:.*[:\\/])?)(.*)#s); + $dirpath = './' unless $dirpath; # Can't be 0 + $dirpath .= '/' unless $dirpath =~ m#[\\/]\z#; + } + elsif ($type eq "MacOS") { + ($dirpath,$basename) = ($fullname =~ /^(.*:)?(.*)/s); + $dirpath = ':' unless $dirpath; + } + elsif ($type eq "AmigaOS") { + ($dirpath,$basename) = ($fullname =~ /(.*[:\/])?(.*)/s); + $dirpath = './' unless $dirpath; + } + elsif ($type eq 'VMS' ) { + ($dirpath,$basename) = ($fullname =~ /^(.*[:>\]])?(.*)/s); + $dirpath ||= ''; # should always be defined + } + else { # Default to Unix semantics. + ($dirpath,$basename) = ($fullname =~ m{^(.*/)?(.*)}s); + if ($orig_type eq 'VMS' and $fullname =~ m{^(/[^/]+/000000(/|$))(.*)}) { + # dev:[000000] is top of VMS tree, similar to Unix '/' + # so strip it off and treat the rest as "normal" + my $devspec = $1; + my $remainder = $3; + ($dirpath,$basename) = ($remainder =~ m{^(.*/)?(.*)}s); + $dirpath ||= ''; # should always be defined + $dirpath = $devspec.$dirpath; + } + $dirpath = './' unless $dirpath; + } + + + my $tail = ''; + my $suffix = ''; + if (@suffices) { + foreach $suffix (@suffices) { + my $pat = ($igncase ? '(?i)' : '') . "($suffix)\$"; + if ($basename =~ s/$pat//s) { + $taint .= substr($suffix,0,0); + $tail = $1 . $tail; + } + } + } + + # Ensure taint is propagated from the path to its pieces. + $tail .= $taint; + wantarray ? ($basename .= $taint, $dirpath .= $taint, $tail) + : ($basename .= $taint); +} + + + +=item C +X X + + my $filename = basename($path); + my $filename = basename($path, @suffixes); + +This function is provided for compatibility with the Unix shell command +C. It does B always return the file name portion of a +path as you might expect. To be safe, if you want the file name portion of +a path use C. + +C returns the last level of a filepath even if the last +level is clearly directory. In effect, it is acting like C for +paths. This differs from C's behaviour. + + # Both return "bar" + basename("/foo/bar"); + basename("/foo/bar/"); + +@suffixes work as in C except all regex metacharacters are +quoted. + + # These two function calls are equivalent. + my $filename = basename("/foo/bar/baz.txt", ".txt"); + my $filename = fileparse("/foo/bar/baz.txt", qr/\Q.txt\E/); + +Also note that in order to be compatible with the shell command, +C does not strip off a suffix if it is identical to the +remaining characters in the filename. + +=cut + + +sub basename { + my($path) = shift; + + # From BSD basename(1) + # The basename utility deletes any prefix ending with the last slash '/' + # character present in string (after first stripping trailing slashes) + _strip_trailing_sep($path); + + my($basename, $dirname, $suffix) = fileparse( $path, map("\Q$_\E",@_) ); + + # From BSD basename(1) + # The suffix is not stripped if it is identical to the remaining + # characters in string. + if( length $suffix and !length $basename ) { + $basename = $suffix; + } + + # Ensure that basename '/' == '/' + if( !length $basename ) { + $basename = $dirname; + } + + return $basename; +} + + + +=item C +X + +This function is provided for compatibility with the Unix shell +command C and has inherited some of its quirks. In spite of +its name it does B always return the directory name as you might +expect. To be safe, if you want the directory name of a path use +C. + +Only on VMS (where there is no ambiguity between the file and directory +portions of a path) and AmigaOS (possibly due to an implementation quirk in +this module) does C work like C, returning just the +$dirs. + + # On VMS and AmigaOS + my $dirs = dirname($path); + +When using Unix or MSDOS syntax this emulates the C shell function +which is subtly different from how C works. It returns all but +the last level of a file path even if the last level is clearly a directory. +In effect, it is not returning the directory portion but simply the path one +level up acting like C for file paths. + +Also unlike C, C does not include a trailing slash on +its returned path. + + # returns /foo/bar. fileparse() would return /foo/bar/ + dirname("/foo/bar/baz"); + + # also returns /foo/bar despite the fact that baz is clearly a + # directory. fileparse() would return /foo/bar/baz/ + dirname("/foo/bar/baz/"); + + # returns '.'. fileparse() would return 'foo/' + dirname("foo/"); + +Under VMS, if there is no directory information in the $path, then the +current default device and directory is used. + +=cut + + +sub dirname { + my $path = shift; + + my($type) = $Fileparse_fstype; + + if( $type eq 'VMS' and $path =~ m{/} ) { + # Parse as Unix + local($File::Basename::Fileparse_fstype) = ''; + return dirname($path); + } + + my($basename, $dirname) = fileparse($path); + + if ($type eq 'VMS') { + $dirname ||= $ENV{DEFAULT}; + } + elsif ($type eq 'MacOS') { + if( !length($basename) && $dirname !~ /^[^:]+:\z/) { + _strip_trailing_sep($dirname); + ($basename,$dirname) = fileparse $dirname; + } + $dirname .= ":" unless $dirname =~ /:\z/; + } + elsif (grep { $type eq $_ } qw(MSDOS DOS MSWin32 OS2)) { + _strip_trailing_sep($dirname); + unless( length($basename) ) { + ($basename,$dirname) = fileparse $dirname; + _strip_trailing_sep($dirname); + } + } + elsif ($type eq 'AmigaOS') { + if ( $dirname =~ /:\z/) { return $dirname } + chop $dirname; + $dirname =~ s{[^:/]+\z}{} unless length($basename); + } + else { + _strip_trailing_sep($dirname); + unless( length($basename) ) { + ($basename,$dirname) = fileparse $dirname; + _strip_trailing_sep($dirname); + } + } + + $dirname; +} + + +# Strip the trailing path separator. +sub _strip_trailing_sep { + my $type = $Fileparse_fstype; + + if ($type eq 'MacOS') { + $_[0] =~ s/([^:]):\z/$1/s; + } + elsif (grep { $type eq $_ } qw(MSDOS DOS MSWin32 OS2)) { + $_[0] =~ s/([^:])[\\\/]*\z/$1/; + } + else { + $_[0] =~ s{(.)/*\z}{$1}s; + } +} + + +=item C +X + + my $type = fileparse_set_fstype(); + my $previous_type = fileparse_set_fstype($type); + +Normally File::Basename will assume a file path type native to your current +operating system (ie. /foo/bar style on Unix, \foo\bar on Windows, etc...). +With this function you can override that assumption. + +Valid $types are "MacOS", "VMS", "AmigaOS", "OS2", "RISCOS", +"MSWin32", "DOS" (also "MSDOS" for backwards bug compatibility), +"Epoc" and "Unix" (all case-insensitive). If an unrecognized $type is +given "Unix" will be assumed. + +If you've selected VMS syntax, and the file specification you pass to +one of these routines contains a "/", they assume you are using Unix +emulation and apply the Unix syntax rules instead, for that function +call only. + +=back + +=cut + + +BEGIN { + +my @Ignore_Case = qw(MacOS VMS AmigaOS OS2 RISCOS MSWin32 MSDOS DOS Epoc); +my @Types = (@Ignore_Case, qw(Unix)); + +sub fileparse_set_fstype { + my $old = $Fileparse_fstype; + + if (@_) { + my $new_type = shift; + + $Fileparse_fstype = 'Unix'; # default + foreach my $type (@Types) { + $Fileparse_fstype = $type if $new_type =~ /^$type/i; + } + + $Fileparse_igncase = + (grep $Fileparse_fstype eq $_, @Ignore_Case) ? 1 : 0; + } + + return $old; +} + +} + + +1; + + +=head1 SEE ALSO + +L, L, L diff --git a/git/usr/share/perl5/core_perl/File/Compare.pm b/git/usr/share/perl5/core_perl/File/Compare.pm new file mode 100644 index 0000000000000000000000000000000000000000..4389b62260f1235100a12fbb3852b40c27fdfcb5 --- /dev/null +++ b/git/usr/share/perl5/core_perl/File/Compare.pm @@ -0,0 +1,174 @@ +package File::Compare 1.1008; + +use v5.12; +use warnings; + +use Exporter 'import'; + +our @EXPORT = qw(compare); +our @EXPORT_OK = qw(cmp compare_text); + +our $Too_Big = 1024 * 1024 * 2; + +sub croak { + require Carp; + goto &Carp::croak; +} + +sub compare { + croak("Usage: compare( file1, file2 [, buffersize]) ") + unless(@_ == 2 || @_ == 3); + + my ($from, $to, $size) = @_; + my $text_mode = defined($size) && (ref($size) eq 'CODE' || $size < 0); + + my ($fromsize, $closefrom, $closeto); + local (*FROM, *TO); + + croak("from undefined") unless (defined $from); + croak("to undefined") unless (defined $to); + + if (ref($from) && + (UNIVERSAL::isa($from, 'GLOB') || UNIVERSAL::isa($from, 'IO::Handle'))) { + *FROM = *$from; + } elsif (ref(\$from) eq 'GLOB') { + *FROM = $from; + } else { + open(FROM, '<', $from) or goto fail_open1; + unless ($text_mode) { + binmode FROM; + $fromsize = -s FROM; + } + $closefrom = 1; + } + + if (ref($to) && + (UNIVERSAL::isa($to, 'GLOB') || UNIVERSAL::isa($to, 'IO::Handle'))) { + *TO = *$to; + } elsif (ref(\$to) eq 'GLOB') { + *TO = $to; + } else { + open(TO, '<', $to) or goto fail_open2; + binmode TO unless $text_mode; + $closeto = 1; + } + + if (!$text_mode && $closefrom && $closeto) { + # If both are opened files we know they differ if their size differ + goto fail_inner if $fromsize != -s TO; + } + + if ($text_mode) { + local $/ = "\n"; + my ($fline, $tline); + while (defined($fline = )) { + goto fail_inner unless defined($tline = ); + if (ref $size) { + # $size contains ref to comparison function + goto fail_inner if &$size($fline, $tline); + } else { + goto fail_inner if $fline ne $tline; + } + } + goto fail_inner if defined($tline = ); + } + else { + unless (defined($size) && $size > 0) { + $size = $fromsize || -s TO || 0; + $size = 1024 if $size < 512; + $size = $Too_Big if $size > $Too_Big; + } + + my ($fr, $tr, $fbuf, $tbuf); + $fbuf = $tbuf = ''; + while(defined($fr = read(FROM, $fbuf, $size)) && $fr > 0) { + unless (defined($tr = read(TO, $tbuf, $fr)) && $tbuf eq $fbuf) { + goto fail_inner; + } + } + goto fail_inner if defined($tr = read(TO, $tbuf, $size)) && $tr > 0; + } + + close(TO) || goto fail_open2 if $closeto; + close(FROM) || goto fail_open1 if $closefrom; + + return 0; + + # All of these contortions try to preserve error messages... + fail_inner: + close(TO) || goto fail_open2 if $closeto; + close(FROM) || goto fail_open1 if $closefrom; + + return 1; + + fail_open2: + if ($closefrom) { + my $status = $!; + $! = 0; + close FROM; + $! = $status unless $!; + } + fail_open1: + return -1; +} + +sub cmp; +*cmp = \&compare; + +sub compare_text { + my ($from, $to, $cmp) = @_; + croak("Usage: compare_text( file1, file2 [, cmp-function])") + unless @_ == 2 || @_ == 3; + croak("Third arg to compare_text() function must be a code reference") + if @_ == 3 && ref($cmp) ne 'CODE'; + + # Using a negative buffer size puts compare into text_mode too + compare($from, $to, $cmp // -1); +} + +1; + +__END__ + +=head1 NAME + +File::Compare - Compare files or filehandles + +=head1 SYNOPSIS + + use File::Compare; + + if (compare("file1", "file2") == 0) { + print "They're equal\n"; + } + +=head1 DESCRIPTION + +The C function compares the contents of two +sources, each of which can be a file or a file handle. It is exported +from C by default. + +C is a synonym for C. It is +exported from C only by request. + +C does a line by line comparison of the two +files. It stops as soon as a difference is detected. C +accepts an optional third argument: This must be a CODE reference to +a line comparison function, which returns C<0> when both lines are considered +equal. For example: + + compare_text($file1, $file2) + +is basically equivalent to + + compare_text($file1, $file2, sub {$_[0] ne $_[1]} ) + +=head1 RETURN + +C and its sibling functions return C<0> if the files +are equal, C<1> if the files are unequal, or C<-1> if an error was encountered. + +=head1 AUTHOR + +C was written by Nick Ing-Simmons. +Its original documentation was written by Chip Salzenberg. diff --git a/git/usr/share/perl5/core_perl/File/Copy.pm b/git/usr/share/perl5/core_perl/File/Copy.pm new file mode 100644 index 0000000000000000000000000000000000000000..1dc1d2d95c3a8aada8b63084847e3c2351f673fc --- /dev/null +++ b/git/usr/share/perl5/core_perl/File/Copy.pm @@ -0,0 +1,513 @@ +# File/Copy.pm. Written in 1994 by Aaron Sherman . This +# source code has been placed in the public domain by the author. +# Please be kind and preserve the documentation. +# +# Additions copyright 1996 by Charles Bailey. Permission is granted +# to distribute the revised code under the same terms as Perl itself. + +package File::Copy; + +use 5.035007; +use strict; +use warnings; no warnings 'newline'; +no warnings 'experimental::builtin'; +use builtin 'blessed'; +use overload; +use File::Spec; +use Config; +# We want HiRes stat and utime if available +BEGIN { eval q{ use Time::HiRes qw( stat utime ) } }; +our(@ISA, @EXPORT, @EXPORT_OK, $VERSION, $Too_Big, $Syscopy_is_copy); +sub copy; +sub syscopy; +sub cp; +sub mv; + +$VERSION = '2.41'; + +require Exporter; +@ISA = qw(Exporter); +@EXPORT = qw(copy move); +@EXPORT_OK = qw(cp mv); + +$Too_Big = 1024 * 1024 * 2; + +sub croak { + require Carp; + goto &Carp::croak; +} + +sub carp { + require Carp; + goto &Carp::carp; +} + +sub _catname { + my($from, $to) = @_; + if (not defined &basename) { + require File::Basename; + File::Basename->import( 'basename' ); + } + + return File::Spec->catfile($to, basename($from)); +} + +# _eq($from, $to) tells whether $from and $to are identical +sub _eq { + my ($from, $to) = map { + blessed($_) && overload::Method($_, q{""}) + ? "$_" + : $_ + } (@_); + return '' if ( (ref $from) xor (ref $to) ); + return $from == $to if ref $from; + return $from eq $to; +} + +sub copy { + croak("Usage: copy(FROM, TO [, BUFFERSIZE]) ") + unless(@_ == 2 || @_ == 3); + + my $from = shift; + my $to = shift; + + my $size; + if (@_) { + $size = shift(@_) + 0; + croak("Bad buffer size for copy: $size\n") unless ($size > 0); + } + + my $from_a_handle = (ref($from) + ? (ref($from) eq 'GLOB' + || UNIVERSAL::isa($from, 'GLOB') + || UNIVERSAL::isa($from, 'IO::Handle')) + : (ref(\$from) eq 'GLOB')); + my $to_a_handle = (ref($to) + ? (ref($to) eq 'GLOB' + || UNIVERSAL::isa($to, 'GLOB') + || UNIVERSAL::isa($to, 'IO::Handle')) + : (ref(\$to) eq 'GLOB')); + + if (_eq($from, $to)) { # works for references, too + carp("'$from' and '$to' are identical (not copied)"); + return 0; + } + + if (!$from_a_handle && !$to_a_handle && -d $to && ! -d $from) { + $to = _catname($from, $to); + } + + if ((($Config{d_symlink} && $Config{d_readlink}) || $Config{d_link}) && + !($^O eq 'os2')) { + my @fs = stat($from); + if (@fs) { + my @ts = stat($to); + if (@ts && $fs[0] == $ts[0] && $fs[1] eq $ts[1] && !-p $from) { + carp("'$from' and '$to' are identical (not copied)"); + return 0; + } + } + } + elsif (_eq($from, $to)) { + carp("'$from' and '$to' are identical (not copied)"); + return 0; + } + + if (defined &syscopy && !$Syscopy_is_copy + && !$to_a_handle + && !($from_a_handle && $^O eq 'os2' ) # OS/2 cannot handle handles + && !($from_a_handle && $^O eq 'MSWin32') + ) + { + if ($^O eq 'VMS' && -e $from + && ! -d $to && ! -d $from) { + + # VMS natively inherits path components from the source of a + # copy, but we want the Unixy behavior of inheriting from + # the current working directory. Also, default in a trailing + # dot for null file types. + + $to = VMS::Filespec::rmsexpand(VMS::Filespec::vmsify($to), '.'); + + # Get rid of the old versions to be like UNIX + 1 while unlink $to; + } + + return syscopy($from, $to) || 0; + } + + my $closefrom = 0; + my $closeto = 0; + my ($status, $r, $buf); + local($\) = ''; + + my $from_h; + if ($from_a_handle) { + $from_h = $from; + } else { + open $from_h, "<", $from or goto fail_open1; + binmode $from_h or die "($!,$^E)"; + $closefrom = 1; + } + + # Seems most logical to do this here, in case future changes would want to + # make this croak for some reason. + unless (defined $size) { + $size = tied(*$from_h) ? 0 : -s $from_h || 0; + $size = 1024 if ($size < 512); + $size = $Too_Big if ($size > $Too_Big); + } + + my $to_h; + if ($to_a_handle) { + $to_h = $to; + } else { + $to_h = \do { local *FH }; # XXX is this line obsolete? + open $to_h, ">", $to or goto fail_open2; + binmode $to_h or die "($!,$^E)"; + $closeto = 1; + } + + $! = 0; + for (;;) { + my ($r, $w, $t); + defined($r = sysread($from_h, $buf, $size)) + or goto fail_inner; + last unless $r; + for ($w = 0; $w < $r; $w += $t) { + $t = syswrite($to_h, $buf, $r - $w, $w) + or goto fail_inner; + } + } + + close($to_h) || goto fail_open2 if $closeto; + close($from_h) || goto fail_open1 if $closefrom; + + # Use this idiom to avoid uninitialized value warning. + return 1; + + # All of these contortions try to preserve error messages... + fail_inner: + if ($closeto) { + $status = $!; + $! = 0; + close $to_h; + $! = $status unless $!; + } + fail_open2: + if ($closefrom) { + $status = $!; + $! = 0; + close $from_h; + $! = $status unless $!; + } + fail_open1: + return 0; +} + +sub cp { + my($from,$to) = @_; + my(@fromstat) = stat $from; + my(@tostat) = stat $to; + my $perm; + + return 0 unless copy(@_) and @fromstat; + + if (@tostat) { + $perm = $tostat[2]; + } else { + $perm = $fromstat[2] & ~(umask || 0); + @tostat = stat $to; + } + # Might be more robust to look for S_I* in Fcntl, but we're + # trying to avoid dependence on any XS-containing modules, + # since File::Copy is used during the Perl build. + $perm &= 07777; + if ($perm & 06000) { + croak("Unable to check setuid/setgid permissions for $to: $!") + unless @tostat; + + if ($perm & 04000 and # setuid + $fromstat[4] != $tostat[4]) { # owner must match + $perm &= ~06000; + } + + if ($perm & 02000 && $> != 0) { # if not root, setgid + my $ok = $fromstat[5] == $tostat[5]; # group must match + if ($ok) { # and we must be in group + $ok = grep { $_ == $fromstat[5] } split /\s+/, $) + } + $perm &= ~06000 unless $ok; + } + } + return 0 unless @tostat; + return 1 if $perm == ($tostat[2] & 07777); + return eval { chmod $perm, $to; } ? 1 : 0; +} + +sub _move { + croak("Usage: move(FROM, TO) ") unless @_ == 3; + + my($from,$to,$fallback) = @_; + + my($fromsz,$tosz1,$tomt1,$tosz2,$tomt2,$sts,$ossts); + + if (-d $to && ! -d $from) { + $to = _catname($from, $to); + } + + ($tosz1,$tomt1) = (stat($to))[7,9]; + $fromsz = -s $from; + if ($^O eq 'os2' and defined $tosz1 and defined $fromsz) { + # will not rename with overwrite + unlink $to; + } + + if ($^O eq 'VMS' && -e $from + && ! -d $to && ! -d $from) { + + # VMS natively inherits path components from the source of a + # copy, but we want the Unixy behavior of inheriting from + # the current working directory. Also, default in a trailing + # dot for null file types. + + $to = VMS::Filespec::rmsexpand(VMS::Filespec::vmsify($to), '.'); + + # Get rid of the old versions to be like UNIX + 1 while unlink $to; + } + + return 1 if rename $from, $to; + + # Did rename return an error even though it succeeded, because $to + # is on a remote NFS file system, and NFS lost the server's ack? + return 1 if defined($fromsz) && !-e $from && # $from disappeared + (($tosz2,$tomt2) = (stat($to))[7,9]) && # $to's there + ((!defined $tosz1) || # not before or + ($tosz1 != $tosz2 or $tomt1 != $tomt2)) && # was changed + $tosz2 == $fromsz; # it's all there + + ($tosz1,$tomt1) = (stat($to))[7,9]; # just in case rename did something + + { + local $@; + eval { + local $SIG{__DIE__}; + $fallback->($from,$to) or die; + my($atime, $mtime) = (stat($from))[8,9]; + utime($atime, $mtime, $to); + unlink($from) or die; + }; + return 1 unless $@; + } + ($sts,$ossts) = ($! + 0, $^E + 0); + + ($tosz2,$tomt2) = ((stat($to))[7,9],0,0) if defined $tomt1; + unlink($to) if !defined($tomt1) or $tomt1 != $tomt2 or $tosz1 != $tosz2; + ($!,$^E) = ($sts,$ossts); + return 0; +} + +sub move { _move(@_,\©); } +sub mv { _move(@_,\&cp); } + +# &syscopy is an XSUB under OS/2 +unless (defined &syscopy) { + if ($^O eq 'VMS') { + *syscopy = \&rmscopy; + } elsif ($^O eq 'MSWin32' && defined &DynaLoader::boot_DynaLoader) { + # Win32::CopyFile() fill only work if we can load Win32.xs + *syscopy = sub { + return 0 unless @_ == 2; + return Win32::CopyFile(@_, 1); + }; + } else { + $Syscopy_is_copy = 1; + *syscopy = \© + } +} + +1; + +__END__ + +=head1 NAME + +File::Copy - Copy files or filehandles + +=head1 SYNOPSIS + + use File::Copy; + + copy("sourcefile", "destinationfile") or die "Copy failed: $!"; + copy("Copy.pm", \*STDOUT); + move("/dev1/sourcefile", "/dev2/destinationfile"); + + use File::Copy "cp"; + + my $n = FileHandle->new("/a/file", "r"); + cp($n, "x"); + +=head1 DESCRIPTION + +The File::Copy module provides two basic functions, C and +C, which are useful for getting the contents of a file from +one place to another. + +=over 4 + +=item copy +X X + +The C function takes two +parameters: a file to copy from and a file to copy to. Either +argument may be a string, a FileHandle reference or a FileHandle +glob. Obviously, if the first argument is a filehandle of some +sort, it will be read from, and if it is a file I it will +be opened for reading. Likewise, the second argument will be +written to. If the second argument does not exist but the parent +directory does exist, then it will be created. Trying to copy +a file into a non-existent directory is an error. +Trying to copy a file on top of itself is also an error. +C will not overwrite read-only files. + +If the destination (second argument) already exists and is a directory, +and the source (first argument) is not a filehandle, then the source +file will be copied into the directory specified by the destination, +using the same base name as the source file. It's a failure to have a +filehandle as the source when the destination is a directory. + +B Files are opened in binary mode where +applicable. To get a consistent behaviour when copying from a +filehandle to a file, use C on the filehandle. + +An optional third parameter can be used to specify the buffer +size used for copying. This is the number of bytes from the +first file, that will be held in memory at any given time, before +being written to the second file. The default buffer size depends +upon the file, but will generally be the whole file (up to 2MB), or +1k for filehandles that do not reference files (eg. sockets). + +You may use the syntax C to get at the C +alias for this function. The syntax is I the same. The +behavior is nearly the same as well: as of version 2.15, C will +preserve the source file's permission bits like the shell utility +C would do with default options, while C uses the default +permissions for the target file (which may depend on the process' +C, file ownership, inherited ACLs, etc.). That is, if the +destination file already exists, C will leave its permissions +unchanged; otherwise the permissions are taken from the source file +and modified by the C. If an error occurs in setting +permissions, C will return 0, regardless of whether the file was +successfully copied. + +=item move +X X X + +The C function also takes two parameters: the current name +and the intended name of the file to be moved. If the destination +already exists and is a directory, and the source is not a +directory, then the source file will be renamed into the directory +specified by the destination. + +If possible, move() will simply rename the file. Otherwise, it copies +the file to the new location and deletes the original. If an error occurs +during this copy-and-delete process, you may be left with a (possibly partial) +copy of the file under the destination name. + +You may use the C alias for this function in the same way that +you may use the C alias for C. + +=item syscopy +X + +File::Copy also provides the C routine, which copies the +file specified in the first parameter to the file specified in the +second parameter, preserving OS-specific attributes and file +structure. For Unix systems, this is equivalent to the simple +C routine, which doesn't preserve OS-specific attributes. For +VMS systems, this calls the C routine (see below). For OS/2 +systems, this calls the C XSUB directly. For Win32 systems, +this calls C. + +B is defined (OS/2, VMS and Win32)>: + +If both arguments to C are not file handles, +then C will perform a "system copy" of +the input file to a new output file, in order to preserve file +attributes, indexed file structure, I The buffer size +parameter is ignored. If either argument to C is a +handle to an opened file, then data is copied using Perl +operators, and no effort is made to preserve file attributes +or record structure. + +The system copy routine may also be called directly under VMS and OS/2 +as C (or under VMS as C, which +is the routine that does the actual work for syscopy). + +=item rmscopy($from,$to[,$date_flag]) +X + +The first and second arguments may be strings, typeglobs, typeglob +references, or objects inheriting from IO::Handle; +they are used in all cases to obtain the +I of the input and output files, respectively. The +name and type of the input file are used as defaults for the +output file, if necessary. + +A new version of the output file is always created, which +inherits the structure and RMS attributes of the input file, +except for owner and protections (and possibly timestamps; +see below). All data from the input file is copied to the +output file; if either of the first two parameters to C +is a file handle, its position is unchanged. (Note that this +means a file handle pointing to the output file will be +associated with an old version of that file after C +returns, not the newly created version.) + +The third parameter is an integer flag, which tells C +how to handle timestamps. If it is E 0, none of the input file's +timestamps are propagated to the output file. If it is E 0, then +it is interpreted as a bitmask: if bit 0 (the LSB) is set, then +timestamps other than the revision date are propagated; if bit 1 +is set, the revision date is propagated. If the third parameter +to C is 0, then it behaves much like the DCL COPY command: +if the name or type of the output file was explicitly specified, +then no timestamps are propagated, but if they were taken implicitly +from the input filespec, then all timestamps other than the +revision date are propagated. If this parameter is not supplied, +it defaults to 0. + +C is VMS specific and cannot be exported; it must be +referenced by its full name, e.g.: + + File::Copy::rmscopy($from, $to) or die $!; + +Like C, C returns 1 on success. If an error occurs, +it sets C<$!>, deletes the output file, and returns 0. + +=back + +=head1 RETURN + +All functions return 1 on success, 0 on failure. +$! will be set if an error was encountered. + +=head1 NOTES + +Before calling copy() or move() on a filehandle, the caller should +close or flush() the file to avoid writes being lost. Note that this +is the case even for move(), because it may actually copy the file, +depending on the OS-specific implementation, and the underlying +filesystem(s). + +=head1 AUTHOR + +File::Copy was written by Aaron Sherman Iajs@ajs.comE> in 1995, +and updated by Charles Bailey Ibailey@newman.upenn.eduE> in 1996. + +=cut + diff --git a/git/usr/share/perl5/core_perl/File/Fetch.pm b/git/usr/share/perl5/core_perl/File/Fetch.pm new file mode 100644 index 0000000000000000000000000000000000000000..157f308ade63ff719462fde7f40c6eeded135ad6 --- /dev/null +++ b/git/usr/share/perl5/core_perl/File/Fetch.pm @@ -0,0 +1,1738 @@ +package File::Fetch; + +use strict; +use FileHandle; +use File::Temp; +use File::Copy; +use File::Spec; +use File::Spec::Unix; +use File::Basename qw[dirname]; + +use Cwd qw[cwd]; +use Carp qw[carp]; +use IPC::Cmd qw[can_run run QUOTE]; +use File::Path qw[mkpath]; +use File::Temp qw[tempdir]; +use Params::Check qw[check]; +use Module::Load::Conditional qw[can_load]; +use Locale::Maketext::Simple Style => 'gettext'; + +use vars qw[ $VERBOSE $PREFER_BIN $FROM_EMAIL $USER_AGENT + $BLACKLIST $METHOD_FAIL $VERSION $METHODS + $FTP_PASSIVE $TIMEOUT $DEBUG $WARN $FORCEIPV4 + ]; + +$VERSION = '1.04'; +$VERSION = eval $VERSION; # avoid warnings with development releases +$PREFER_BIN = 0; # XXX TODO implement +$FROM_EMAIL = 'File-Fetch@example.com'; +$USER_AGENT = "File::Fetch/$VERSION"; +$BLACKLIST = [qw|ftp|]; +push @$BLACKLIST, qw|lftp| if $^O eq 'dragonfly' || $^O eq 'hpux'; +$METHOD_FAIL = { }; +$FTP_PASSIVE = 1; +$TIMEOUT = 0; +$DEBUG = 0; +$WARN = 1; +$FORCEIPV4 = 0; + +### methods available to fetch the file depending on the scheme +$METHODS = { + http => [ qw|lwp httptiny wget curl lftp fetch httplite lynx iosock| ], + https => [ qw|lwp wget curl| ], + ftp => [ qw|lwp netftp wget curl lftp fetch ncftp ftp| ], + file => [ qw|lwp lftp file| ], + rsync => [ qw|rsync| ], + git => [ qw|git| ], +}; + +### silly warnings ### +local $Params::Check::VERBOSE = 1; +local $Params::Check::VERBOSE = 1; +local $Module::Load::Conditional::VERBOSE = 0; +local $Module::Load::Conditional::VERBOSE = 0; + +### see what OS we are on, important for file:// uris ### +use constant ON_WIN => ($^O eq 'MSWin32'); +use constant ON_VMS => ($^O eq 'VMS'); +use constant ON_UNIX => (!ON_WIN); +use constant HAS_VOL => (ON_WIN); +use constant HAS_SHARE => (ON_WIN); +use constant HAS_FETCH => ( $^O =~ m!^(freebsd|netbsd|dragonfly)$! ); + +=pod + +=head1 NAME + +File::Fetch - A generic file fetching mechanism + +=head1 SYNOPSIS + + use File::Fetch; + + ### build a File::Fetch object ### + my $ff = File::Fetch->new(uri => 'http://some.where.com/dir/a.txt'); + + ### fetch the uri to cwd() ### + my $where = $ff->fetch() or die $ff->error; + + ### fetch the uri to /tmp ### + my $where = $ff->fetch( to => '/tmp' ); + + ### parsed bits from the uri ### + $ff->uri; + $ff->scheme; + $ff->host; + $ff->path; + $ff->file; + +=head1 DESCRIPTION + +File::Fetch is a generic file fetching mechanism. + +It allows you to fetch any file pointed to by a C, C, +C, C or C uri by a number of different means. + +See the C section further down for details. + +=head1 ACCESSORS + +A C object has the following accessors + +=over 4 + +=item $ff->uri + +The uri you passed to the constructor + +=item $ff->scheme + +The scheme from the uri (like 'file', 'http', etc) + +=item $ff->host + +The hostname in the uri. Will be empty if host was originally +'localhost' for a 'file://' url. + +=item $ff->vol + +On operating systems with the concept of a volume the second element +of a file:// is considered to the be volume specification for the file. +Thus on Win32 this routine returns the volume, on other operating +systems this returns nothing. + +On Windows this value may be empty if the uri is to a network share, in +which case the 'share' property will be defined. Additionally, volume +specifications that use '|' as ':' will be converted on read to use ':'. + +On VMS, which has a volume concept, this field will be empty because VMS +file specifications are converted to absolute UNIX format and the volume +information is transparently included. + +=item $ff->share + +On systems with the concept of a network share (currently only Windows) returns +the sharename from a file://// url. On other operating systems returns empty. + +=item $ff->path + +The path from the uri, will be at least a single '/'. + +=item $ff->file + +The name of the remote file. For the local file name, the +result of $ff->output_file will be used. + +=item $ff->file_default + +The name of the default local file, that $ff->output_file falls back to if +it would otherwise return no filename. For example when fetching a URI like +http://www.abc.net.au/ the contents retrieved may be from a remote file called +'index.html'. The default value of this attribute is literally 'file_default'. + +=cut + + +########################## +### Object & Accessors ### +########################## + +{ + ### template for autogenerated accessors ### + my $Tmpl = { + scheme => { default => 'http' }, + host => { default => 'localhost' }, + path => { default => '/' }, + file => { required => 1 }, + uri => { required => 1 }, + userinfo => { default => '' }, + vol => { default => '' }, # windows for file:// uris + share => { default => '' }, # windows for file:// uris + file_default => { default => 'file_default' }, + tempdir_root => { required => 1 }, # Should be lazy-set at ->new() + _error_msg => { no_override => 1 }, + _error_msg_long => { no_override => 1 }, + }; + + for my $method ( keys %$Tmpl ) { + no strict 'refs'; + *$method = sub { + my $self = shift; + $self->{$method} = $_[0] if @_; + return $self->{$method}; + } + } + + sub _create { + my $class = shift; + my %hash = @_; + + my $args = check( $Tmpl, \%hash ) or return; + + bless $args, $class; + + if( lc($args->scheme) ne 'file' and not $args->host ) { + return $class->_error(loc( + "Hostname required when fetching from '%1'",$args->scheme)); + } + + for (qw[path]) { + unless( $args->$_() ) { # 5.5.x needs the () + return $class->_error(loc("No '%1' specified",$_)); + } + } + + return $args; + } +} + +=item $ff->output_file + +The name of the output file. This is the same as $ff->file, +but any query parameters are stripped off. For example: + + http://example.com/index.html?x=y + +would make the output file be C rather than +C. + +=back + +=cut + +sub output_file { + my $self = shift; + my $file = $self->file; + + $file =~ s/\?.*$//g; + + $file ||= $self->file_default; + + return $file; +} + +### XXX do this or just point to URI::Escape? +# =head2 $esc_uri = $ff->escaped_uri +# +# =cut +# +# ### most of this is stolen straight from URI::escape +# { ### Build a char->hex map +# my %escapes = map { chr($_) => sprintf("%%%02X", $_) } 0..255; +# +# sub escaped_uri { +# my $self = shift; +# my $uri = $self->uri; +# +# ### Default unsafe characters. RFC 2732 ^(uric - reserved) +# $uri =~ s/([^A-Za-z0-9\-_.!~*'()])/ +# $escapes{$1} || $self->_fail_hi($1)/ge; +# +# return $uri; +# } +# +# sub _fail_hi { +# my $self = shift; +# my $char = shift; +# +# $self->_error(loc( +# "Can't escape '%1', try using the '%2' module instead", +# sprintf("\\x{%04X}", ord($char)), 'URI::Escape' +# )); +# } +# +# sub output_file { +# +# } +# +# +# } + +=head1 METHODS + +=head2 $ff = File::Fetch->new( uri => 'http://some.where.com/dir/file.txt' ); + +Parses the uri and creates a corresponding File::Fetch::Item object, +that is ready to be Ced and returns it. + +Returns false on failure. + +=cut + +sub new { + my $class = shift; + my %hash = @_; + + my ($uri, $file_default, $tempdir_root); + my $tmpl = { + uri => { required => 1, store => \$uri }, + file_default => { required => 0, store => \$file_default }, + tempdir_root => { required => 0, store => \$tempdir_root }, + }; + + check( $tmpl, \%hash ) or return; + + ### parse the uri to usable parts ### + my $href = $class->_parse_uri( $uri ) or return; + + $href->{file_default} = $file_default if $file_default; + $href->{tempdir_root} = File::Spec->rel2abs( $tempdir_root ) if $tempdir_root; + $href->{tempdir_root} = File::Spec->rel2abs( Cwd::cwd ) if not $href->{tempdir_root}; + + ### make it into a FFI object ### + my $ff = $class->_create( %$href ) or return; + + + ### return the object ### + return $ff; +} + +### parses an uri to a hash structure: +### +### $class->_parse_uri( 'ftp://ftp.cpan.org/pub/mirror/index.txt' ) +### +### becomes: +### +### $href = { +### scheme => 'ftp', +### host => 'ftp.cpan.org', +### path => '/pub/mirror', +### file => 'index.html' +### }; +### +### In the case of file:// urls there maybe be additional fields +### +### For systems with volume specifications such as Win32 there will be +### a volume specifier provided in the 'vol' field. +### +### 'vol' => 'volumename' +### +### For windows file shares there may be a 'share' key specified +### +### 'share' => 'sharename' +### +### Note that the rules of what a file:// url means vary by the operating system +### of the host being addressed. Thus file:///d|/foo/bar.txt means the obvious +### 'D:\foo\bar.txt' on windows, but on unix it means '/d|/foo/bar.txt' and +### not '/foo/bar.txt' +### +### Similarly if the host interpreting the url is VMS then +### file:///disk$user/my/notes/note12345.txt' means +### 'DISK$USER:[MY.NOTES]NOTE123456.TXT' but will be returned the same as +### if it is unix where it means /disk$user/my/notes/note12345.txt'. +### Except for some cases in the File::Spec methods, Perl on VMS will generally +### handle UNIX format file specifications. +### +### This means it is impossible to serve certain file:// urls on certain systems. +### +### Thus are the problems with a protocol-less specification. :-( +### + +sub _parse_uri { + my $self = shift; + my $uri = shift or return; + + my $href = { uri => $uri }; + + ### find the scheme ### + $uri =~ s|^(\w+)://||; + $href->{scheme} = $1; + + ### See rfc 1738 section 3.10 + ### https://datatracker.ietf.org/doc/html/rfc1738#section-3.10 + ### And wikipedia for more on windows file:// urls + ### http://en.wikipedia.org/wiki/File:// + if( $href->{scheme} eq 'file' ) { + + my @parts = split '/',$uri; + + ### file://hostname/... + ### file://hostname/... + ### normalize file://localhost with file:/// + $href->{host} = $parts[0] || ''; + + ### index in @parts where the path components begin; + my $index = 1; + + ### file:////hostname/sharename/blah.txt + if ( HAS_SHARE and not length $parts[0] and not length $parts[1] ) { + + $href->{host} = $parts[2] || ''; # avoid warnings + $href->{share} = $parts[3] || ''; # avoid warnings + + $index = 4 # index after the share + + ### file:///D|/blah.txt + ### file:///D:/blah.txt + } elsif (HAS_VOL) { + + ### this code comes from dmq's patch, but: + ### XXX if volume is empty, wouldn't that be an error? --kane + ### if so, our file://localhost test needs to be fixed as wel + $href->{vol} = $parts[1] || ''; + + ### correct D| style colume descriptors + $href->{vol} =~ s/\A([A-Z])\|\z/$1:/i if ON_WIN; + + $index = 2; # index after the volume + } + + ### rebuild the path from the leftover parts; + $href->{path} = join '/', '', splice( @parts, $index, $#parts ); + + } else { + ### using anything but qw() in hash slices may produce warnings + ### in older perls :-( + @{$href}{ qw(userinfo host path) } = $uri =~ m|(?:([^\@:]*:[^\:\@]*)@)?([^/]*)(/.*)$|s; + } + + ### split the path into file + dir ### + { my @parts = File::Spec::Unix->splitpath( delete $href->{path} ); + $href->{path} = $parts[1]; + $href->{file} = $parts[2]; + } + + ### host will be empty if the target was 'localhost' and the + ### scheme was 'file' + $href->{host} = '' if ($href->{host} eq 'localhost') and + ($href->{scheme} eq 'file'); + + return $href; +} + +=head2 $where = $ff->fetch( [to => /my/output/dir/ | \$scalar] ) + +Fetches the file you requested and returns the full path to the file. + +By default it writes to C, but you can override that by specifying +the C argument: + + ### file fetch to /tmp, full path to the file in $where + $where = $ff->fetch( to => '/tmp' ); + + ### file slurped into $scalar, full path to the file in $where + ### file is downloaded to a temp directory and cleaned up at exit time + $where = $ff->fetch( to => \$scalar ); + +Returns the full path to the downloaded file on success, and false +on failure. + +=cut + +sub fetch { + my $self = shift or return; + my %hash = @_; + + my $target; + my $tmpl = { + to => { default => cwd(), store => \$target }, + }; + + check( $tmpl, \%hash ) or return; + + my ($to, $fh); + ### you want us to slurp the contents + if( ref $target and UNIVERSAL::isa( $target, 'SCALAR' ) ) { + $to = tempdir( 'FileFetch.XXXXXX', DIR => $self->tempdir_root, CLEANUP => 1 ); + + ### plain old fetch + } else { + $to = $target; + + ### On VMS force to VMS format so File::Spec will work. + $to = VMS::Filespec::vmspath($to) if ON_VMS; + + ### create the path if it doesn't exist yet ### + unless( -d $to ) { + eval { mkpath( $to ) }; + + return $self->_error(loc("Could not create path '%1'",$to)) if $@; + } + } + + ### set passive ftp if required ### + local $ENV{FTP_PASSIVE} = $FTP_PASSIVE; + + ### we dont use catfile on win32 because if we are using a cygwin tool + ### under cmd.exe they wont understand windows style separators. + my $out_to = ON_WIN ? $to.'/'.$self->output_file + : File::Spec->catfile( $to, $self->output_file ); + + for my $method ( @{ $METHODS->{$self->scheme} } ) { + my $sub = '_'.$method.'_fetch'; + + unless( __PACKAGE__->can($sub) ) { + $self->_error(loc("Cannot call method for '%1' -- WEIRD!", + $method)); + next; + } + + ### method is blacklisted ### + next if grep { lc $_ eq $method } @$BLACKLIST; + + ### method is known to fail ### + next if $METHOD_FAIL->{$method}; + + ### there's serious issues with IPC::Run and quoting of command + ### line arguments. using quotes in the wrong place breaks things, + ### and in the case of say, + ### C:\cygwin\bin\wget.EXE --quiet --passive-ftp --output-document + ### "index.html" "http://www.cpan.org/index.html?q=1&y=2" + ### it doesn't matter how you quote, it always fails. + local $IPC::Cmd::USE_IPC_RUN = 0; + + if( my $file = $self->$sub( + to => $out_to + )){ + + unless( -e $file && -s _ ) { + $self->_error(loc("'%1' said it fetched '%2', ". + "but it was not created",$method,$file)); + + ### mark the failure ### + $METHOD_FAIL->{$method} = 1; + + next; + + } else { + + ### slurp mode? + if( ref $target and UNIVERSAL::isa( $target, 'SCALAR' ) ) { + + ### open the file + open my $fh, "<$file" or do { + $self->_error( + loc("Could not open '%1': %2", $file, $!)); + return; + }; + + ### slurp + $$target = do { local $/; <$fh> }; + + } + + my $abs = File::Spec->rel2abs( $file ); + return $abs; + + } + } + } + + + ### if we got here, we looped over all methods, but we weren't able + ### to fetch it. + return; +} + +######################## +### _*_fetch methods ### +######################## + +### LWP fetching ### +sub _lwp_fetch { + my $self = shift; + my %hash = @_; + + my ($to); + my $tmpl = { + to => { required => 1, store => \$to } + }; + check( $tmpl, \%hash ) or return; + + ### modules required to download with lwp ### + my $use_list = { + LWP => '0.0', + 'LWP::UserAgent' => '0.0', + 'HTTP::Request' => '0.0', + 'HTTP::Status' => '0.0', + URI => '0.0', + + }; + + if ($self->scheme eq 'https') { + $use_list->{'LWP::Protocol::https'} = '0'; + } + + ### Fix CVE-2016-1238 ### + local $Module::Load::Conditional::FORCE_SAFE_INC = 1; + unless( can_load( modules => $use_list ) ) { + $METHOD_FAIL->{'lwp'} = 1; + return; + } + + ### setup the uri object + my $uri = URI->new( File::Spec::Unix->catfile( + $self->path, $self->file + ) ); + + ### special rules apply for file:// uris ### + $uri->scheme( $self->scheme ); + $uri->host( $self->scheme eq 'file' ? '' : $self->host ); + + if ($self->userinfo) { + $uri->userinfo($self->userinfo); + } elsif ($self->scheme ne 'file') { + $uri->userinfo("anonymous:$FROM_EMAIL"); + } + + ### set up the useragent object + my $ua = LWP::UserAgent->new(); + $ua->timeout( $TIMEOUT ) if $TIMEOUT; + $ua->agent( $USER_AGENT ); + $ua->from( $FROM_EMAIL ); + $ua->env_proxy; + + my $res = $ua->mirror($uri, $to) or return; + + ### uptodate or fetched ok ### + if ( $res->code == 304 or $res->code == 200 ) { + return $to; + + } else { + return $self->_error(loc("Fetch failed! HTTP response: %1 %2 [%3]", + $res->code, HTTP::Status::status_message($res->code), + $res->status_line)); + } + +} + +### HTTP::Tiny fetching ### +sub _httptiny_fetch { + my $self = shift; + my %hash = @_; + + my ($to); + my $tmpl = { + to => { required => 1, store => \$to } + }; + check( $tmpl, \%hash ) or return; + + my $use_list = { + 'HTTP::Tiny' => '0.008', + + }; + + ### Fix CVE-2016-1238 ### + local $Module::Load::Conditional::FORCE_SAFE_INC = 1; + unless( can_load(modules => $use_list) ) { + $METHOD_FAIL->{'httptiny'} = 1; + return; + } + + my $uri = $self->uri; + + my $http = HTTP::Tiny->new( ( $TIMEOUT ? ( timeout => $TIMEOUT ) : () ) ); + + my $rc = $http->mirror( $uri, $to ); + + unless ( $rc->{success} ) { + + return $self->_error(loc( "Fetch failed! HTTP response: %1 [%2]", + $rc->{status}, $rc->{reason} ) ); + + } + + return $to; + +} + +### HTTP::Lite fetching ### +sub _httplite_fetch { + my $self = shift; + my %hash = @_; + + my ($to); + my $tmpl = { + to => { required => 1, store => \$to } + }; + check( $tmpl, \%hash ) or return; + + ### modules required to download with lwp ### + my $use_list = { + 'HTTP::Lite' => '2.2', + 'MIME::Base64' => '0', + }; + + ### Fix CVE-2016-1238 ### + local $Module::Load::Conditional::FORCE_SAFE_INC = 1; + unless( can_load(modules => $use_list) ) { + $METHOD_FAIL->{'httplite'} = 1; + return; + } + + my $uri = $self->uri; + my $retries = 0; + + RETRIES: while ( $retries++ < 5 ) { + + my $http = HTTP::Lite->new(); + # Naughty naughty but there isn't any accessor/setter + $http->{timeout} = $TIMEOUT if $TIMEOUT; + $http->http11_mode(1); + + if ($self->userinfo) { + my $encoded = MIME::Base64::encode($self->userinfo, ''); + $http->add_req_header("Authorization", "Basic $encoded"); + } + + my $fh = FileHandle->new; + + unless ( $fh->open($to,'>') ) { + return $self->_error(loc( + "Could not open '%1' for writing: %2",$to,$!)); + } + + $fh->autoflush(1); + + binmode $fh; + + my $rc = $http->request( $uri, sub { my ($self,$dref,$cbargs) = @_; local $\; print {$cbargs} $$dref }, $fh ); + + close $fh; + + if ( $rc == 301 || $rc == 302 ) { + my $loc; + HEADERS: for ($http->headers_array) { + /Location: (\S+)/ and $loc = $1, last HEADERS; + } + #$loc or last; # Think we should squeal here. + if ($loc =~ m!^/!) { + $uri =~ s{^(\w+?://[^/]+)/.*$}{$1}; + $uri .= $loc; + } + else { + $uri = $loc; + } + next RETRIES; + } + elsif ( $rc == 200 ) { + return $to; + } + else { + return $self->_error(loc("Fetch failed! HTTP response: %1 [%2]", + $rc, $http->status_message)); + } + + } # Loop for 5 retries. + + return $self->_error("Fetch failed! Gave up after 5 tries"); + +} + +### Simple IO::Socket::INET fetching ### +sub _iosock_fetch { + my $self = shift; + my %hash = @_; + + my ($to); + my $tmpl = { + to => { required => 1, store => \$to } + }; + check( $tmpl, \%hash ) or return; + + my $use_list = { + 'IO::Socket::INET' => '0.0', + 'IO::Select' => '0.0', + }; + + ### Fix CVE-2016-1238 ### + local $Module::Load::Conditional::FORCE_SAFE_INC = 1; + unless( can_load(modules => $use_list) ) { + $METHOD_FAIL->{'iosock'} = 1; + return; + } + + my $sock = IO::Socket::INET->new( + PeerHost => $self->host, + ( $self->host =~ /:/ ? () : ( PeerPort => 80 ) ), + ); + + unless ( $sock ) { + return $self->_error(loc("Could not open socket to '%1', '%2'",$self->host,$!)); + } + + my $fh = FileHandle->new; + + # Check open() + + unless ( $fh->open($to,'>') ) { + return $self->_error(loc( + "Could not open '%1' for writing: %2",$to,$!)); + } + + $fh->autoflush(1); + binmode $fh; + + my $path = File::Spec::Unix->catfile( $self->path, $self->file ); + my $req = "GET $path HTTP/1.0\x0d\x0aHost: " . $self->host . "\x0d\x0a\x0d\x0a"; + $sock->send( $req ); + + my $select = IO::Select->new( $sock ); + + my $resp = ''; + my $normal = 0; + while ( $select->can_read( $TIMEOUT || 60 ) ) { + my $ret = $sock->sysread( $resp, 4096, length($resp) ); + if ( !defined $ret or $ret == 0 ) { + $select->remove( $sock ); + $normal++; + } + } + close $sock; + + unless ( $normal ) { + return $self->_error(loc("Socket timed out after '%1' seconds", ( $TIMEOUT || 60 ))); + } + + # Check the "response" + # Strip preceding blank lines apparently they are allowed (RFC 2616 4.1) + $resp =~ s/^(\x0d?\x0a)+//; + # Check it is an HTTP response + unless ( $resp =~ m!^HTTP/(\d+)\.(\d+)!i ) { + return $self->_error(loc("Did not get a HTTP response from '%1'",$self->host)); + } + + # Check for OK + my ($code) = $resp =~ m!^HTTP/\d+\.\d+\s+(\d+)!i; + unless ( $code eq '200' ) { + return $self->_error(loc("Got a '%1' from '%2' expected '200'",$code,$self->host)); + } + + { + local $\; + print $fh +($resp =~ m/\x0d\x0a\x0d\x0a(.*)$/s )[0]; + } + close $fh; + return $to; +} + +### Net::FTP fetching +sub _netftp_fetch { + my $self = shift; + my %hash = @_; + + my ($to); + my $tmpl = { + to => { required => 1, store => \$to } + }; + check( $tmpl, \%hash ) or return; + + ### required modules ### + my $use_list = { 'Net::FTP' => 0 }; + + ### Fix CVE-2016-1238 ### + local $Module::Load::Conditional::FORCE_SAFE_INC = 1; + unless( can_load( modules => $use_list ) ) { + $METHOD_FAIL->{'netftp'} = 1; + return; + } + + ### make connection ### + my $ftp; + my @options = ($self->host); + push(@options, Timeout => $TIMEOUT) if $TIMEOUT; + unless( $ftp = Net::FTP->new( @options ) ) { + return $self->_error(loc("Ftp creation failed: %1",$@)); + } + + ### login ### + unless( $ftp->login( anonymous => $FROM_EMAIL ) ) { + return $self->_error(loc("Could not login to '%1'",$self->host)); + } + + ### set binary mode, just in case ### + $ftp->binary; + + ### create the remote path + ### remember remote paths are unix paths! [#11483] + my $remote = File::Spec::Unix->catfile( $self->path, $self->file ); + + ### fetch the file ### + my $target; + unless( $target = $ftp->get( $remote, $to ) ) { + return $self->_error(loc("Could not fetch '%1' from '%2'", + $remote, $self->host)); + } + + ### log out ### + $ftp->quit; + + return $target; + +} + +### /bin/wget fetch ### +sub _wget_fetch { + my $self = shift; + my %hash = @_; + + my ($to); + my $tmpl = { + to => { required => 1, store => \$to } + }; + check( $tmpl, \%hash ) or return; + + my $wget; + ### see if we have a wget binary ### + unless( $wget = can_run('wget') ) { + $METHOD_FAIL->{'wget'} = 1; + return; + } + + ### no verboseness, thanks ### + my $cmd = [ $wget, '--quiet' ]; + + ### if a timeout is set, add it ### + push(@$cmd, '--timeout=' . $TIMEOUT) if $TIMEOUT; + + ### run passive if specified ### + push @$cmd, '--passive-ftp' if $self->scheme eq 'ftp' && $FTP_PASSIVE; + + ### set the output document, add the uri ### + push @$cmd, '--output-document', $to, $self->uri; + + ### with IPC::Cmd > 0.41, this is fixed in teh library, + ### and there's no need for special casing any more. + ### DO NOT quote things for IPC::Run, it breaks stuff. + # $IPC::Cmd::USE_IPC_RUN + # ? ($to, $self->uri) + # : (QUOTE. $to .QUOTE, QUOTE. $self->uri .QUOTE); + + ### shell out ### + my $captured; + unless(run( command => $cmd, + buffer => \$captured, + verbose => $DEBUG + )) { + ### wget creates the output document always, even if the fetch + ### fails.. so unlink it in that case + 1 while unlink $to; + + return $self->_error(loc( "Command failed: %1", $captured || '' )); + } + + return $to; +} + +### /bin/lftp fetch ### +sub _lftp_fetch { + my $self = shift; + my %hash = @_; + + my ($to); + my $tmpl = { + to => { required => 1, store => \$to } + }; + check( $tmpl, \%hash ) or return; + + ### see if we have a lftp binary ### + my $lftp; + unless( $lftp = can_run('lftp') ) { + $METHOD_FAIL->{'lftp'} = 1; + return; + } + + ### no verboseness, thanks ### + my $cmd = [ $lftp, '-f' ]; + + my $fh = File::Temp->new; + + my $str; + + ### if a timeout is set, add it ### + $str .= "set net:timeout $TIMEOUT;\n" if $TIMEOUT; + + ### run passive if specified ### + $str .= "set ftp:passive-mode 1;\n" if $FTP_PASSIVE; + + ### set the output document, add the uri ### + ### quote the URI, because lftp supports certain shell + ### expansions, most notably & for backgrounding. + ### ' quote does nto work, must be " + $str .= q[get ']. $self->uri .q[' -o ]. $to . $/; + + if( $DEBUG ) { + my $pp_str = join ' ', split $/, $str; + print "# lftp command: $pp_str\n"; + } + + ### write straight to the file. + $fh->autoflush(1); + print $fh $str; + + ### the command needs to be 1 string to be executed + push @$cmd, $fh->filename; + + ### with IPC::Cmd > 0.41, this is fixed in teh library, + ### and there's no need for special casing any more. + ### DO NOT quote things for IPC::Run, it breaks stuff. + # $IPC::Cmd::USE_IPC_RUN + # ? ($to, $self->uri) + # : (QUOTE. $to .QUOTE, QUOTE. $self->uri .QUOTE); + + + ### shell out ### + my $captured; + unless(run( command => $cmd, + buffer => \$captured, + verbose => $DEBUG + )) { + ### wget creates the output document always, even if the fetch + ### fails.. so unlink it in that case + 1 while unlink $to; + + return $self->_error(loc( "Command failed: %1", $captured || '' )); + } + + return $to; +} + + + +### /bin/ftp fetch ### +sub _ftp_fetch { + my $self = shift; + my %hash = @_; + + my ($to); + my $tmpl = { + to => { required => 1, store => \$to } + }; + check( $tmpl, \%hash ) or return; + + ### see if we have a ftp binary ### + my $ftp; + unless( $ftp = can_run('ftp') ) { + $METHOD_FAIL->{'ftp'} = 1; + return; + } + + my $fh = FileHandle->new; + + local $SIG{CHLD} = 'IGNORE'; + + unless ($fh->open("$ftp -n", '|-')) { + return $self->_error(loc("%1 creation failed: %2", $ftp, $!)); + } + + my @dialog = ( + "lcd " . dirname($to), + "open " . $self->host, + "user anonymous $FROM_EMAIL", + "cd /", + "cd " . $self->path, + "binary", + "get " . $self->file . " " . $self->output_file, + "quit", + ); + + foreach (@dialog) { $fh->print($_, "\n") } + $fh->close or return; + + return $to; +} + +### lynx is stupid - it decompresses any .gz file it finds to be text +### use /bin/lynx to fetch files +sub _lynx_fetch { + my $self = shift; + my %hash = @_; + + my ($to); + my $tmpl = { + to => { required => 1, store => \$to } + }; + check( $tmpl, \%hash ) or return; + + ### see if we have a lynx binary ### + my $lynx; + unless ( $lynx = can_run('lynx') ){ + $METHOD_FAIL->{'lynx'} = 1; + return; + } + + unless( IPC::Cmd->can_capture_buffer ) { + $METHOD_FAIL->{'lynx'} = 1; + + return $self->_error(loc( + "Can not capture buffers. Can not use '%1' to fetch files", + 'lynx' )); + } + + ### check if the HTTP resource exists ### + if ($self->uri =~ /^https?:\/\//i) { + my $cmd = [ + $lynx, + '-head', + '-source', + "-auth=anonymous:$FROM_EMAIL", + ]; + + push @$cmd, "-connect_timeout=$TIMEOUT" if $TIMEOUT; + + push @$cmd, $self->uri; + + ### shell out ### + my $head; + unless(run( command => $cmd, + buffer => \$head, + verbose => $DEBUG ) + ) { + return $self->_error(loc("Command failed: %1", $head || '')); + } + + unless($head =~ /^HTTP\/\d+\.\d+ 200\b/) { + return $self->_error(loc("Command failed: %1", $head || '')); + } + } + + ### write to the output file ourselves, since lynx ass_u_mes to much + my $local = FileHandle->new( $to, 'w' ) + or return $self->_error(loc( + "Could not open '%1' for writing: %2",$to,$!)); + + ### dump to stdout ### + my $cmd = [ + $lynx, + '-source', + "-auth=anonymous:$FROM_EMAIL", + ]; + + push @$cmd, "-connect_timeout=$TIMEOUT" if $TIMEOUT; + + ### DO NOT quote things for IPC::Run, it breaks stuff. + push @$cmd, $self->uri; + + ### with IPC::Cmd > 0.41, this is fixed in teh library, + ### and there's no need for special casing any more. + ### DO NOT quote things for IPC::Run, it breaks stuff. + # $IPC::Cmd::USE_IPC_RUN + # ? $self->uri + # : QUOTE. $self->uri .QUOTE; + + + ### shell out ### + my $captured; + unless(run( command => $cmd, + buffer => \$captured, + verbose => $DEBUG ) + ) { + return $self->_error(loc("Command failed: %1", $captured || '')); + } + + ### print to local file ### + ### XXX on a 404 with a special error page, $captured will actually + ### hold the contents of that page, and make it *appear* like the + ### request was a success, when really it wasn't :( + ### there doesn't seem to be an option for lynx to change the exit + ### code based on a 4XX status or so. + ### the closest we can come is using --error_file and parsing that, + ### which is very unreliable ;( + $local->print( $captured ); + $local->close or return; + + return $to; +} + +### use /bin/ncftp to fetch files +sub _ncftp_fetch { + my $self = shift; + my %hash = @_; + + my ($to); + my $tmpl = { + to => { required => 1, store => \$to } + }; + check( $tmpl, \%hash ) or return; + + ### we can only set passive mode in interactive sessions, so bail out + ### if $FTP_PASSIVE is set + return if $FTP_PASSIVE; + + ### see if we have a ncftp binary ### + my $ncftp; + unless( $ncftp = can_run('ncftp') ) { + $METHOD_FAIL->{'ncftp'} = 1; + return; + } + + my $cmd = [ + $ncftp, + '-V', # do not be verbose + '-p', $FROM_EMAIL, # email as password + $self->host, # hostname + dirname($to), # local dir for the file + # remote path to the file + ### DO NOT quote things for IPC::Run, it breaks stuff. + $IPC::Cmd::USE_IPC_RUN + ? File::Spec::Unix->catdir( $self->path, $self->file ) + : QUOTE. File::Spec::Unix->catdir( + $self->path, $self->file ) .QUOTE + + ]; + + ### shell out ### + my $captured; + unless(run( command => $cmd, + buffer => \$captured, + verbose => $DEBUG ) + ) { + return $self->_error(loc("Command failed: %1", $captured || '')); + } + + return $to; + +} + +### use /bin/curl to fetch files +sub _curl_fetch { + my $self = shift; + my %hash = @_; + + my ($to); + my $tmpl = { + to => { required => 1, store => \$to } + }; + check( $tmpl, \%hash ) or return; + my $curl; + unless ( $curl = can_run('curl') ) { + $METHOD_FAIL->{'curl'} = 1; + return; + } + + ### these long opts are self explanatory - I like that -jmb + my $cmd = [ $curl, '-q' ]; + + push(@$cmd, '-4') if $^O eq 'netbsd' && $FORCEIPV4; # only seen this on NetBSD so far + + push(@$cmd, '--connect-timeout', $TIMEOUT) if $TIMEOUT; + + push(@$cmd, '--silent') unless $DEBUG; + + ### curl does the right thing with passive, regardless ### + if ($self->scheme eq 'ftp') { + push(@$cmd, '--user', "anonymous:$FROM_EMAIL"); + } + + ### curl doesn't follow 302 (temporarily moved) etc automatically + ### so we add --location to enable that. + push @$cmd, '--fail', '--location', '--output', $to, $self->uri; + + ### with IPC::Cmd > 0.41, this is fixed in teh library, + ### and there's no need for special casing any more. + ### DO NOT quote things for IPC::Run, it breaks stuff. + # $IPC::Cmd::USE_IPC_RUN + # ? ($to, $self->uri) + # : (QUOTE. $to .QUOTE, QUOTE. $self->uri .QUOTE); + + + my $captured; + unless(run( command => $cmd, + buffer => \$captured, + verbose => $DEBUG ) + ) { + + return $self->_error(loc("Command failed: %1", $captured || '')); + } + + return $to; + +} + +### /usr/bin/fetch fetch! ### +sub _fetch_fetch { + my $self = shift; + my %hash = @_; + + my ($to); + my $tmpl = { + to => { required => 1, store => \$to } + }; + check( $tmpl, \%hash ) or return; + + ### see if we have a fetch binary ### + my $fetch; + unless( HAS_FETCH and $fetch = can_run('fetch') ) { + $METHOD_FAIL->{'fetch'} = 1; + return; + } + + ### no verboseness, thanks ### + my $cmd = [ $fetch, '-q' ]; + + ### if a timeout is set, add it ### + push(@$cmd, '-T', $TIMEOUT) if $TIMEOUT; + + ### run passive if specified ### + #push @$cmd, '-p' if $FTP_PASSIVE; + local $ENV{'FTP_PASSIVE_MODE'} = 1 if $FTP_PASSIVE; + + ### set the output document, add the uri ### + push @$cmd, '-o', $to, $self->uri; + + ### with IPC::Cmd > 0.41, this is fixed in teh library, + ### and there's no need for special casing any more. + ### DO NOT quote things for IPC::Run, it breaks stuff. + # $IPC::Cmd::USE_IPC_RUN + # ? ($to, $self->uri) + # : (QUOTE. $to .QUOTE, QUOTE. $self->uri .QUOTE); + + ### shell out ### + my $captured; + unless(run( command => $cmd, + buffer => \$captured, + verbose => $DEBUG + )) { + ### wget creates the output document always, even if the fetch + ### fails.. so unlink it in that case + 1 while unlink $to; + + return $self->_error(loc( "Command failed: %1", $captured || '' )); + } + + return $to; +} + +### use File::Copy for fetching file:// urls ### +### +### See section 3.10 of RFC 1738 (https://datatracker.ietf.org/doc/html/rfc1738#section-3.10) +### Also see wikipedia on file:// (http://en.wikipedia.org/wiki/File://) +### + +sub _file_fetch { + my $self = shift; + my %hash = @_; + + my ($to); + my $tmpl = { + to => { required => 1, store => \$to } + }; + check( $tmpl, \%hash ) or return; + + + + ### prefix a / on unix systems with a file uri, since it would + ### look somewhat like this: + ### file:///home/kane/file + ### whereas windows file uris for 'c:\some\dir\file' might look like: + ### file:///C:/some/dir/file + ### file:///C|/some/dir/file + ### or for a network share '\\host\share\some\dir\file': + ### file:////host/share/some/dir/file + ### + ### VMS file uri's for 'DISK$USER:[MY.NOTES]NOTE123456.TXT' might look like: + ### file://vms.host.edu/disk$user/my/notes/note12345.txt + ### + + my $path = $self->path; + my $vol = $self->vol; + my $share = $self->share; + + my $remote; + if (!$share and $self->host) { + return $self->_error(loc( + "Currently %1 cannot handle hosts in %2 urls", + 'File::Fetch', 'file://' + )); + } + + if( $vol ) { + $path = File::Spec->catdir( split /\//, $path ); + $remote = File::Spec->catpath( $vol, $path, $self->file); + + } elsif( $share ) { + ### win32 specific, and a share name, so we wont bother with File::Spec + $path =~ s|/+|\\|g; + $remote = "\\\\".$self->host."\\$share\\$path"; + + } else { + ### File::Spec on VMS can not currently handle UNIX syntax. + my $file_class = ON_VMS + ? 'File::Spec::Unix' + : 'File::Spec'; + + $remote = $file_class->catfile( $path, $self->file ); + } + + ### File::Copy is littered with 'die' statements :( ### + my $rv = eval { File::Copy::copy( $remote, $to ) }; + + ### something went wrong ### + if( !$rv or $@ ) { + return $self->_error(loc("Could not copy '%1' to '%2': %3 %4", + $remote, $to, $!, $@)); + } + + return $to; +} + +### use /usr/bin/rsync to fetch files +sub _rsync_fetch { + my $self = shift; + my %hash = @_; + + my ($to); + my $tmpl = { + to => { required => 1, store => \$to } + }; + check( $tmpl, \%hash ) or return; + my $rsync; + unless ( $rsync = can_run('rsync') ) { + $METHOD_FAIL->{'rsync'} = 1; + return; + } + + my $cmd = [ $rsync ]; + + ### XXX: rsync has no I/O timeouts at all, by default + push(@$cmd, '--timeout=' . $TIMEOUT) if $TIMEOUT; + + push(@$cmd, '--quiet') unless $DEBUG; + + ### DO NOT quote things for IPC::Run, it breaks stuff. + push @$cmd, $self->uri, $to; + + ### with IPC::Cmd > 0.41, this is fixed in teh library, + ### and there's no need for special casing any more. + ### DO NOT quote things for IPC::Run, it breaks stuff. + # $IPC::Cmd::USE_IPC_RUN + # ? ($to, $self->uri) + # : (QUOTE. $to .QUOTE, QUOTE. $self->uri .QUOTE); + + my $captured; + unless(run( command => $cmd, + buffer => \$captured, + verbose => $DEBUG ) + ) { + + return $self->_error(loc("Command %1 failed: %2", + "@$cmd" || '', $captured || '')); + } + + return $to; + +} + +### use git to fetch files +sub _git_fetch { + my $self = shift; + my %hash = @_; + + my ($to); + my $tmpl = { + to => { required => 1, store => \$to } + }; + check( $tmpl, \%hash ) or return; + my $git; + unless ( $git = can_run('git') ) { + $METHOD_FAIL->{'git'} = 1; + return; + } + + my $cmd = [ $git, 'clone' ]; + + #push(@$cmd, '--timeout=' . $TIMEOUT) if $TIMEOUT; + + push(@$cmd, '--quiet') unless $DEBUG; + + ### DO NOT quote things for IPC::Run, it breaks stuff. + push @$cmd, $self->uri, $to; + + ### with IPC::Cmd > 0.41, this is fixed in teh library, + ### and there's no need for special casing any more. + ### DO NOT quote things for IPC::Run, it breaks stuff. + # $IPC::Cmd::USE_IPC_RUN + # ? ($to, $self->uri) + # : (QUOTE. $to .QUOTE, QUOTE. $self->uri .QUOTE); + + my $captured; + unless(run( command => $cmd, + buffer => \$captured, + verbose => $DEBUG ) + ) { + + return $self->_error(loc("Command %1 failed: %2", + "@$cmd" || '', $captured || '')); + } + + return $to; + +} + +################################# +# +# Error code +# +################################# + +=pod + +=head2 $ff->error([BOOL]) + +Returns the last encountered error as string. +Pass it a true value to get the C output instead. + +=cut + +### error handling the way Archive::Extract does it +sub _error { + my $self = shift; + my $error = shift; + + $self->_error_msg( $error ); + $self->_error_msg_long( Carp::longmess($error) ); + + if( $WARN ) { + carp $DEBUG ? $self->_error_msg_long : $self->_error_msg; + } + + return; +} + +sub error { + my $self = shift; + return shift() ? $self->_error_msg_long : $self->_error_msg; +} + + +1; + +=pod + +=head1 HOW IT WORKS + +File::Fetch is able to fetch a variety of uris, by using several +external programs and modules. + +Below is a mapping of what utilities will be used in what order +for what schemes, if available: + + file => LWP, lftp, file + http => LWP, HTTP::Tiny, wget, curl, lftp, fetch, HTTP::Lite, lynx, iosock + ftp => LWP, Net::FTP, wget, curl, lftp, fetch, ncftp, ftp + rsync => rsync + git => git + +If you'd like to disable the use of one or more of these utilities +and/or modules, see the C<$BLACKLIST> variable further down. + +If a utility or module isn't available, it will be marked in a cache +(see the C<$METHOD_FAIL> variable further down), so it will not be +tried again. The C method will only fail when all options are +exhausted, and it was not able to retrieve the file. + +The C utility is available on FreeBSD. NetBSD and Dragonfly BSD +may also have it from C. We only check for C on those +three platforms. + +C is a very limited L based mechanism for +retrieving C schemed urls. It doesn't follow redirects for instance. + +C only supports C style urls. + +A special note about fetching files from an ftp uri: + +By default, all ftp connections are done in passive mode. To change +that, see the C<$FTP_PASSIVE> variable further down. + +Furthermore, ftp uris only support anonymous connections, so no +named user/password pair can be passed along. + +C is blacklisted by default; see the C<$BLACKLIST> variable +further down. + +=head1 GLOBAL VARIABLES + +The behaviour of File::Fetch can be altered by changing the following +global variables: + +=head2 $File::Fetch::FROM_EMAIL + +This is the email address that will be sent as your anonymous ftp +password. + +Default is C. + +=head2 $File::Fetch::USER_AGENT + +This is the useragent as C will report it. + +Default is C. + +=head2 $File::Fetch::FTP_PASSIVE + +This variable controls whether the environment variable C +and any passive switches to commandline tools will be set to true. + +Default value is 1. + +Note: When $FTP_PASSIVE is true, C will not be used to fetch +files, since passive mode can only be set interactively for this binary + +=head2 $File::Fetch::TIMEOUT + +When set, controls the network timeout (counted in seconds). + +Default value is 0. + +=head2 $File::Fetch::WARN + +This variable controls whether errors encountered internally by +C should be C'd or not. + +Set to false to silence warnings. Inspect the output of the C +method manually to see what went wrong. + +Defaults to C. + +=head2 $File::Fetch::DEBUG + +This enables debugging output when calling commandline utilities to +fetch files. +This also enables C errors, instead of the regular +C errors. + +Good for tracking down why things don't work with your particular +setup. + +Default is 0. + +=head2 $File::Fetch::BLACKLIST + +This is an array ref holding blacklisted modules/utilities for fetching +files with. + +To disallow the use of, for example, C and C, you could +set $File::Fetch::BLACKLIST to: + + $File::Fetch::BLACKLIST = [qw|lwp netftp|] + +The default blacklist is [qw|ftp|], as C is rather unreliable. + +See the note on C below. + +=head2 $File::Fetch::METHOD_FAIL + +This is a hashref registering what modules/utilities were known to fail +for fetching files (mostly because they weren't installed). + +You can reset this cache by assigning an empty hashref to it, or +individually remove keys. + +See the note on C below. + +=head1 MAPPING + + +Here's a quick mapping for the utilities/modules, and their names for +the $BLACKLIST, $METHOD_FAIL and other internal functions. + + LWP => lwp + HTTP::Lite => httplite + HTTP::Tiny => httptiny + Net::FTP => netftp + wget => wget + lynx => lynx + ncftp => ncftp + ftp => ftp + curl => curl + rsync => rsync + lftp => lftp + fetch => fetch + IO::Socket => iosock + +=head1 FREQUENTLY ASKED QUESTIONS + +=head2 So how do I use a proxy with File::Fetch? + +C currently only supports proxies with LWP::UserAgent. +You will need to set your environment variables accordingly. For +example, to use an ftp proxy: + + $ENV{ftp_proxy} = 'foo.com'; + +Refer to the LWP::UserAgent manpage for more details. + +=head2 I used 'lynx' to fetch a file, but its contents is all wrong! + +C can only fetch remote files by dumping its contents to C, +which we in turn capture. If that content is a 'custom' error file +(like, say, a C<404 handler>), you will get that contents instead. + +Sadly, C doesn't support any options to return a different exit +code on non-C<200 OK> status, giving us no way to tell the difference +between a 'successful' fetch and a custom error page. + +Therefor, we recommend to only use C as a last resort. This is +why it is at the back of our list of methods to try as well. + +=head2 Files I'm trying to fetch have reserved characters or non-ASCII characters in them. What do I do? + +C is relatively smart about things. When trying to write +a file to disk, it removes the C (see the +C method for details) from the file name before creating +it. In most cases this suffices. + +If you have any other characters you need to escape, please install +the C module from CPAN, and pre-encode your URI before +passing it to C. You can read about the details of URIs +and URI encoding here: + +L + +=head1 TODO + +=over 4 + +=item Implement $PREFER_BIN + +To indicate to rather use commandline tools than modules + +=back + +=head1 BUG REPORTS + +Please report bugs or other issues to Ebug-file-fetch@rt.cpan.org. + +=head1 AUTHOR + +This module by Jos Boumans Ekane@cpan.orgE. + +=head1 COPYRIGHT + +This library is free software; you may redistribute and/or modify it +under the same terms as Perl itself. + + +=cut + +# Local variables: +# c-indentation-style: bsd +# c-basic-offset: 4 +# indent-tabs-mode: nil +# End: +# vim: expandtab shiftwidth=4: + + + + diff --git a/git/usr/share/perl5/core_perl/File/Find.pm b/git/usr/share/perl5/core_perl/File/Find.pm new file mode 100644 index 0000000000000000000000000000000000000000..af84fbf116f32c0cecff83d952805ae4bf4416a3 --- /dev/null +++ b/git/usr/share/perl5/core_perl/File/Find.pm @@ -0,0 +1,1124 @@ +package File::Find; + +use 5.006; +use strict; +use warnings; +use warnings::register; + +use Exporter 'import'; +require Cwd; +require File::Basename; +require File::Spec; + +our $VERSION = '1.44'; +our @EXPORT = qw(find finddepth); + +my $Is_VMS = $^O eq 'VMS'; +my $Is_Win32 = $^O eq 'MSWin32'; + + +# Should ideally be my() not our() but local() currently +# refuses to operate on lexicals + +our %SLnkSeen; +our ($wanted_callback, $avoid_nlink, $bydepth, $no_chdir, $follow, + $follow_skip, $full_check, $untaint, $untaint_skip, $untaint_pat, + $pre_process, $post_process, $dangling_symlinks); + +sub contract_name { + my ($cdir,$fn) = @_; + + return substr($cdir,0,rindex($cdir,'/')) if $fn eq $File::Find::current_dir; + + $cdir = substr($cdir,0,rindex($cdir,'/')+1); + + $fn =~ s|^\./||; + + my $abs_name= $cdir . $fn; + + if (substr($fn,0,3) eq '../') { + 1 while $abs_name =~ s!/[^/]*/\.\./+!/!; + } + + return $abs_name; +} + +sub _is_absolute { + return $_[0] =~ m|^(?:[A-Za-z]:)?/| if $Is_Win32; + return substr($_[0], 0, 1) eq '/'; +} + +sub _is_root { + return $_[0] =~ m|^(?:[A-Za-z]:)?/\z| if $Is_Win32; + return $_[0] eq '/'; +} + +sub PathCombine($$) { + my ($Base,$Name) = @_; + my $AbsName; + + if (_is_absolute($Name)) { + $AbsName= $Name; + } + else { + $AbsName= contract_name($Base,$Name); + } + + # (simple) check for recursion + my $newlen= length($AbsName); + if ($newlen <= length($Base)) { + if (($newlen == length($Base) || substr($Base,$newlen,1) eq '/') + && $AbsName eq substr($Base,0,$newlen)) + { + return undef; + } + } + return $AbsName; +} + +sub Follow_SymLink($) { + my ($AbsName) = @_; + + my ($NewName,$DEV, $INO); + ($DEV, $INO)= lstat $AbsName; + + while (-l _) { + if ($SLnkSeen{$DEV, $INO}++) { + if ($follow_skip < 2) { + die "$AbsName is encountered a second time"; + } + else { + return undef; + } + } + my $Link = readlink($AbsName); + # canonicalize directory separators + $Link =~ s|\\|/|g if $Is_Win32; + $NewName= PathCombine($AbsName, $Link); + unless(defined $NewName) { + if ($follow_skip < 2) { + die "$AbsName is a recursive symbolic link"; + } + else { + return undef; + } + } + else { + $AbsName= $NewName; + } + ($DEV, $INO) = lstat($AbsName); + return undef unless defined $DEV; # dangling symbolic link + } + + if ($full_check && defined $DEV && $SLnkSeen{$DEV, $INO}++) { + if ( ($follow_skip < 1) || ((-d _) && ($follow_skip < 2)) ) { + die "$AbsName encountered a second time"; + } + else { + return undef; + } + } + + return $AbsName; +} + +our($dir, $name, $fullname, $prune); +sub _find_dir_symlnk($$$); +sub _find_dir($$$); + +# check whether or not a scalar variable is tainted +# (code straight from the Camel, 3rd ed., page 561) +sub is_tainted_pp { + my $arg = shift; + my $nada = substr($arg, 0, 0); # zero-length + local $@; + eval { eval "# $nada" }; + return length($@) != 0; +} + + +sub _find_opt { + my $wanted = shift; + return unless @_; + die "invalid top directory" unless defined $_[0]; + + # This function must local()ize everything because callbacks may + # call find() or finddepth() + + local %SLnkSeen; + local ($wanted_callback, $avoid_nlink, $bydepth, $no_chdir, $follow, + $follow_skip, $full_check, $untaint, $untaint_skip, $untaint_pat, + $pre_process, $post_process, $dangling_symlinks); + local($dir, $name, $fullname, $prune); + local *_ = \my $a; + + my $cwd = $wanted->{bydepth} ? Cwd::fastcwd() : Cwd::getcwd(); + if ($Is_VMS) { + # VMS returns this by default in VMS format which just doesn't + # work for the rest of this module. + $cwd = VMS::Filespec::unixpath($cwd); + + # Apparently this is not expected to have a trailing space. + # To attempt to make VMS/UNIX conversions mostly reversible, + # a trailing slash is needed. The run-time functions ignore the + # resulting double slash, but it causes the perl tests to fail. + $cwd =~ s#/\z##; + + # This comes up in upper case now, but should be lower. + # In the future this could be exact case, no need to change. + } + my $cwd_untainted = $cwd; + my $check_t_cwd = 1; + $wanted_callback = $wanted->{wanted}; + $bydepth = $wanted->{bydepth}; + $pre_process = $wanted->{preprocess}; + $post_process = $wanted->{postprocess}; + $no_chdir = $wanted->{no_chdir}; + $full_check = $wanted->{follow}; + $follow = $full_check || $wanted->{follow_fast}; + $follow_skip = $wanted->{follow_skip}; + $untaint = $wanted->{untaint}; + $untaint_pat = $wanted->{untaint_pattern}; + $untaint_skip = $wanted->{untaint_skip}; + $dangling_symlinks = $wanted->{dangling_symlinks}; + + # for compatibility reasons (find.pl, find2perl) + local our ($topdir, $topdev, $topino, $topmode, $topnlink); + + # a symbolic link to a directory doesn't increase the link count + $avoid_nlink = $follow || $File::Find::dont_use_nlink; + + my ($abs_dir, $Is_Dir); + + Proc_Top_Item: + foreach my $TOP (@_) { + my $top_item = $TOP; + $top_item = VMS::Filespec::unixify($top_item) if $Is_VMS; + + ($topdev,$topino,$topmode,$topnlink) = $follow ? stat $top_item : lstat $top_item; + + # canonicalize directory separators + $top_item =~ s|[/\\]|/|g if $Is_Win32; + + # no trailing / unless path is root + $top_item =~ s|/\z|| unless _is_root($top_item); + + $Is_Dir= 0; + + if ($follow) { + + if (_is_absolute($top_item)) { + $abs_dir = $top_item; + } + elsif ($top_item eq $File::Find::current_dir) { + $abs_dir = $cwd; + } + else { # care about any ../ + $top_item =~ s/\.dir\z//i if $Is_VMS; + $abs_dir = contract_name("$cwd/",$top_item); + } + $abs_dir= Follow_SymLink($abs_dir); + unless (defined $abs_dir) { + if ($dangling_symlinks) { + if (ref $dangling_symlinks eq 'CODE') { + $dangling_symlinks->($top_item, $cwd); + } else { + warnings::warnif "$top_item is a dangling symbolic link\n"; + } + } + next Proc_Top_Item; + } + + if (-d _) { + $top_item =~ s/\.dir\z//i if $Is_VMS; + _find_dir_symlnk($wanted, $abs_dir, $top_item); + $Is_Dir= 1; + } + } + else { # no follow + $topdir = $top_item; + unless (defined $topnlink) { + warnings::warnif "Can't stat $top_item: $!\n"; + next Proc_Top_Item; + } + if (-d _) { + $top_item =~ s/\.dir\z//i if $Is_VMS; + _find_dir($wanted, $top_item, $topnlink); + $Is_Dir= 1; + } + else { + $abs_dir= $top_item; + } + } + + unless ($Is_Dir) { + unless (($_,$dir) = File::Basename::fileparse($abs_dir)) { + ($dir,$_) = ('./', $top_item); + } + + $abs_dir = $dir; + if (( $untaint ) && (is_tainted($dir) )) { + ( $abs_dir ) = $dir =~ m|$untaint_pat|; + unless (defined $abs_dir) { + if ($untaint_skip == 0) { + die "directory $dir is still tainted"; + } + else { + next Proc_Top_Item; + } + } + } + + unless ($no_chdir || chdir $abs_dir) { + warnings::warnif "Couldn't chdir $abs_dir: $!\n"; + next Proc_Top_Item; + } + + $name = $abs_dir . $_; # $File::Find::name + $_ = $name if $no_chdir; + + { $wanted_callback->() }; # protect against wild "next" + + } + + unless ( $no_chdir ) { + if ( ($check_t_cwd) && (($untaint) && (is_tainted($cwd) )) ) { + ( $cwd_untainted ) = $cwd =~ m|$untaint_pat|; + unless (defined $cwd_untainted) { + die "insecure cwd in find(depth)"; + } + $check_t_cwd = 0; + } + unless (chdir $cwd_untainted) { + die "Can't cd to $cwd: $!\n"; + } + } + } +} + +# API: +# $wanted +# $p_dir : "parent directory" +# $nlink : what came back from the stat +# preconditions: +# chdir (if not no_chdir) to dir + +sub _find_dir($$$) { + my ($wanted, $p_dir, $nlink) = @_; + my ($CdLvl,$Level) = (0,0); + my @Stack; + my @filenames; + my ($subcount,$sub_nlink); + my $SE= []; + my $dir_name= $p_dir; + my $dir_pref; + my $dir_rel = $File::Find::current_dir; + my $tainted = 0; + my $no_nlink; + + if ($Is_VMS) { + # VMS is returning trailing .dir on directories + # and trailing . on files and symbolic links + # in UNIX syntax. + # + + $p_dir =~ s/\.(dir)?$//i unless $p_dir eq '.'; + + $dir_pref = ($p_dir =~ m/[\]>]+$/ ? $p_dir : "$p_dir/" ); + } + else { + $dir_pref = _is_root($p_dir) ? $p_dir : "$p_dir/"; + } + + local ($dir, $name, $prune); + + unless ( $no_chdir || ($p_dir eq $File::Find::current_dir)) { + my $udir = $p_dir; + if (( $untaint ) && (is_tainted($p_dir) )) { + ( $udir ) = $p_dir =~ m|$untaint_pat|; + unless (defined $udir) { + if ($untaint_skip == 0) { + die "directory $p_dir is still tainted"; + } + else { + return; + } + } + } + unless (chdir ($Is_VMS && $udir !~ /[\/\[<]+/ ? "./$udir" : $udir)) { + warnings::warnif "Can't cd to $udir: $!\n"; + return; + } + } + + # push the starting directory + push @Stack,[$CdLvl,$p_dir,$dir_rel,-1] if $bydepth; + + while (defined $SE) { + unless ($bydepth) { + $dir= $p_dir; # $File::Find::dir + $name= $dir_name; # $File::Find::name + $_= ($no_chdir ? $dir_name : $dir_rel ); # $_ + # prune may happen here + $prune= 0; + { $wanted_callback->() }; # protect against wild "next" + next if $prune; + } + + # change to that directory + unless ($no_chdir || ($dir_rel eq $File::Find::current_dir)) { + my $udir= $dir_rel; + if ( ($untaint) && (($tainted) || ($tainted = is_tainted($dir_rel) )) ) { + ( $udir ) = $dir_rel =~ m|$untaint_pat|; + unless (defined $udir) { + if ($untaint_skip == 0) { + die "directory (" . ($p_dir ne '/' ? $p_dir : '') . "/) $dir_rel is still tainted"; + } else { # $untaint_skip == 1 + next; + } + } + } + unless (chdir ($Is_VMS && $udir !~ /[\/\[<]+/ ? "./$udir" : $udir)) { + warnings::warnif "Can't cd to (" . + ($p_dir ne '/' ? $p_dir : '') . "/) $udir: $!\n"; + next; + } + $CdLvl++; + } + + $dir= $dir_name; # $File::Find::dir + + # Get the list of files in the current directory. + my $dh; + unless (opendir $dh, ($no_chdir ? $dir_name : $File::Find::current_dir)) { + warnings::warnif "Can't opendir($dir_name): $!\n"; + next; + } + @filenames = readdir $dh; + closedir($dh); + @filenames = $pre_process->(@filenames) if $pre_process; + push @Stack,[$CdLvl,$dir_name,"",-2] if $post_process; + + # default: use whatever was specified + # (if $nlink >= 2, and $avoid_nlink == 0, this will switch back) + $no_nlink = $avoid_nlink; + # if dir has wrong nlink count, force switch to slower stat method + $no_nlink = 1 if ($nlink < 2); + + if ($nlink == 2 && !$no_nlink) { + # This dir has no subdirectories. + for my $FN (@filenames) { + if ($Is_VMS) { + # Big hammer here - Compensate for VMS trailing . and .dir + # No win situation until this is changed, but this + # will handle the majority of the cases with breaking the fewest + + $FN =~ s/\.dir\z//i; + $FN =~ s#\.$## if ($FN ne '.'); + } + next if $FN =~ $File::Find::skip_pattern; + + $name = $dir_pref . $FN; # $File::Find::name + $_ = ($no_chdir ? $name : $FN); # $_ + { $wanted_callback->() }; # protect against wild "next" + } + + } + else { + # This dir has subdirectories. + $subcount = $nlink - 2; + + # HACK: insert directories at this position, so as to preserve + # the user pre-processed ordering of files (thus ensuring + # directory traversal is in user sorted order, not at random). + my $stack_top = @Stack; + + for my $FN (@filenames) { + next if $FN =~ $File::Find::skip_pattern; + if ($subcount > 0 || $no_nlink) { + # Seen all the subdirs? + # check for directoriness. + # stat is faster for a file in the current directory + $sub_nlink = (lstat ($no_chdir ? $dir_pref . $FN : $FN))[3]; + + if (-d _) { + --$subcount; + $FN =~ s/\.dir\z//i if $Is_VMS; + # HACK: replace push to preserve dir traversal order + #push @Stack,[$CdLvl,$dir_name,$FN,$sub_nlink]; + splice @Stack, $stack_top, 0, + [$CdLvl,$dir_name,$FN,$sub_nlink]; + } + else { + $name = $dir_pref . $FN; # $File::Find::name + $_= ($no_chdir ? $name : $FN); # $_ + { $wanted_callback->() }; # protect against wild "next" + } + } + else { + $name = $dir_pref . $FN; # $File::Find::name + $_= ($no_chdir ? $name : $FN); # $_ + { $wanted_callback->() }; # protect against wild "next" + } + } + } + } + continue { + while ( defined ($SE = pop @Stack) ) { + ($Level, $p_dir, $dir_rel, $nlink) = @$SE; + if ($CdLvl > $Level && !$no_chdir) { + my $tmp; + if ($Is_VMS) { + $tmp = '[' . ('-' x ($CdLvl-$Level)) . ']'; + } + else { + $tmp = join('/',('..') x ($CdLvl-$Level)); + } + die "Can't cd to $tmp from $dir_name: $!" + unless chdir ($tmp); + $CdLvl = $Level; + } + + if ($^O eq 'VMS') { + if ($p_dir =~ m/[\]>]+$/) { + $dir_name = $p_dir; + $dir_name =~ s/([\]>]+)$/.$dir_rel$1/; + $dir_pref = $dir_name; + } + else { + $dir_name = "$p_dir/$dir_rel"; + $dir_pref = "$dir_name/"; + } + } + else { + $dir_name = _is_root($p_dir) ? "$p_dir$dir_rel" : "$p_dir/$dir_rel"; + $dir_pref = "$dir_name/"; + } + + if ( $nlink == -2 ) { + $name = $dir = $p_dir; # $File::Find::name / dir + $_ = $File::Find::current_dir; + $post_process->(); # End-of-directory processing + } + elsif ( $nlink < 0 ) { # must be finddepth, report dirname now + $name = $dir_name; + if ( substr($name,-2) eq '/.' ) { + substr($name, length($name) == 2 ? -1 : -2) = ''; + } + $dir = $p_dir; + $_ = ($no_chdir ? $dir_name : $dir_rel ); + if ( substr($_,-2) eq '/.' ) { + substr($_, length($_) == 2 ? -1 : -2) = ''; + } + { $wanted_callback->() }; # protect against wild "next" + } + else { + push @Stack,[$CdLvl,$p_dir,$dir_rel,-1] if $bydepth; + last; + } + } + } +} + + +# API: +# $wanted +# $dir_loc : absolute location of a dir +# $p_dir : "parent directory" +# preconditions: +# chdir (if not no_chdir) to dir + +sub _find_dir_symlnk($$$) { + my ($wanted, $dir_loc, $p_dir) = @_; # $dir_loc is the absolute directory + my @Stack; + my @filenames; + my $new_loc; + my $updir_loc = $dir_loc; # untainted parent directory + my $SE = []; + my $dir_name = $p_dir; + my $dir_pref; + my $loc_pref; + my $dir_rel = $File::Find::current_dir; + my $byd_flag; # flag for pending stack entry if $bydepth + my $tainted = 0; + my $ok = 1; + + $dir_pref = _is_root($p_dir) ? $p_dir : "$p_dir/"; + $loc_pref = _is_root($dir_loc) ? $dir_loc : "$dir_loc/"; + + local ($dir, $name, $fullname, $prune); + + unless ($no_chdir) { + # untaint the topdir + if (( $untaint ) && (is_tainted($dir_loc) )) { + ( $updir_loc ) = $dir_loc =~ m|$untaint_pat|; # parent dir, now untainted + # once untainted, $updir_loc is pushed on the stack (as parent directory); + # hence, we don't need to untaint the parent directory every time we chdir + # to it later + unless (defined $updir_loc) { + if ($untaint_skip == 0) { + die "directory $dir_loc is still tainted"; + } + else { + return; + } + } + } + $ok = chdir($updir_loc) unless ($p_dir eq $File::Find::current_dir); + unless ($ok) { + warnings::warnif "Can't cd to $updir_loc: $!\n"; + return; + } + } + + push @Stack,[$dir_loc,$updir_loc,$p_dir,$dir_rel,-1] if $bydepth; + + while (defined $SE) { + + unless ($bydepth) { + # change (back) to parent directory (always untainted) + unless ($no_chdir) { + unless (chdir $updir_loc) { + warnings::warnif "Can't cd to $updir_loc: $!\n"; + next; + } + } + $dir= $p_dir; # $File::Find::dir + $name= $dir_name; # $File::Find::name + $_= ($no_chdir ? $dir_name : $dir_rel ); # $_ + $fullname= $dir_loc; # $File::Find::fullname + # prune may happen here + $prune= 0; + lstat($_); # make sure file tests with '_' work + { $wanted_callback->() }; # protect against wild "next" + next if $prune; + } + + # change to that directory + unless ($no_chdir || ($dir_rel eq $File::Find::current_dir)) { + $updir_loc = $dir_loc; + if ( ($untaint) && (($tainted) || ($tainted = is_tainted($dir_loc) )) ) { + # untaint $dir_loc, what will be pushed on the stack as (untainted) parent dir + ( $updir_loc ) = $dir_loc =~ m|$untaint_pat|; + unless (defined $updir_loc) { + if ($untaint_skip == 0) { + die "directory $dir_loc is still tainted"; + } + else { + next; + } + } + } + unless (chdir $updir_loc) { + warnings::warnif "Can't cd to $updir_loc: $!\n"; + next; + } + } + + $dir = $dir_name; # $File::Find::dir + + # Get the list of files in the current directory. + my $dh; + unless (opendir $dh, ($no_chdir ? $dir_loc : $File::Find::current_dir)) { + warnings::warnif "Can't opendir($dir_loc): $!\n"; + next; + } + @filenames = readdir $dh; + closedir($dh); + + for my $FN (@filenames) { + if ($Is_VMS) { + # Big hammer here - Compensate for VMS trailing . and .dir + # No win situation until this is changed, but this + # will handle the majority of the cases with breaking the fewest. + + $FN =~ s/\.dir\z//i; + $FN =~ s#\.$## if ($FN ne '.'); + } + next if $FN =~ $File::Find::skip_pattern; + + # follow symbolic links / do an lstat + $new_loc = Follow_SymLink($loc_pref.$FN); + + # ignore if invalid symlink + unless (defined $new_loc) { + if (!defined -l _ && $dangling_symlinks) { + $fullname = undef; + if (ref $dangling_symlinks eq 'CODE') { + $dangling_symlinks->($FN, $dir_pref); + } else { + warnings::warnif "$dir_pref$FN is a dangling symbolic link\n"; + } + } + else { + $fullname = $loc_pref . $FN; + } + $name = $dir_pref . $FN; + $_ = ($no_chdir ? $name : $FN); + { $wanted_callback->() }; + next; + } + + if (-d _) { + if ($Is_VMS) { + $FN =~ s/\.dir\z//i; + $FN =~ s#\.$## if ($FN ne '.'); + $new_loc =~ s/\.dir\z//i; + $new_loc =~ s#\.$## if ($new_loc ne '.'); + } + push @Stack,[$new_loc,$updir_loc,$dir_name,$FN,1]; + } + else { + $fullname = $new_loc; # $File::Find::fullname + $name = $dir_pref . $FN; # $File::Find::name + $_ = ($no_chdir ? $name : $FN); # $_ + { $wanted_callback->() }; # protect against wild "next" + } + } + + } + continue { + while (defined($SE = pop @Stack)) { + ($dir_loc, $updir_loc, $p_dir, $dir_rel, $byd_flag) = @$SE; + $dir_name = _is_root($p_dir) ? "$p_dir$dir_rel" : "$p_dir/$dir_rel"; + $dir_pref = "$dir_name/"; + $loc_pref = "$dir_loc/"; + if ( $byd_flag < 0 ) { # must be finddepth, report dirname now + unless ($no_chdir || ($dir_rel eq $File::Find::current_dir)) { + unless (chdir $updir_loc) { # $updir_loc (parent dir) is always untainted + warnings::warnif "Can't cd to $updir_loc: $!\n"; + next; + } + } + $fullname = $dir_loc; # $File::Find::fullname + $name = $dir_name; # $File::Find::name + if ( substr($name,-2) eq '/.' ) { + substr($name, length($name) == 2 ? -1 : -2) = ''; # $File::Find::name + } + $dir = $p_dir; # $File::Find::dir + $_ = ($no_chdir ? $dir_name : $dir_rel); # $_ + if ( substr($_,-2) eq '/.' ) { + substr($_, length($_) == 2 ? -1 : -2) = ''; + } + + lstat($_); # make sure file tests with '_' work + { $wanted_callback->() }; # protect against wild "next" + } + else { + push @Stack,[$dir_loc, $updir_loc, $p_dir, $dir_rel,-1] if $bydepth; + last; + } + } + } +} + + +sub wrap_wanted { + my $wanted = shift; + if ( ref($wanted) eq 'HASH' ) { + # RT #122547 + my %valid_options = map {$_ => 1} qw( + wanted + bydepth + preprocess + postprocess + follow + follow_fast + follow_skip + dangling_symlinks + no_chdir + untaint + untaint_pattern + untaint_skip + ); + my @invalid_options = (); + for my $v (keys %{$wanted}) { + push @invalid_options, $v unless exists $valid_options{$v}; + } + warn "Invalid option(s): @invalid_options" if @invalid_options; + + unless( exists $wanted->{wanted} and ref( $wanted->{wanted} ) eq 'CODE' ) { + die 'no &wanted subroutine given'; + } + if ( $wanted->{follow} || $wanted->{follow_fast}) { + $wanted->{follow_skip} = 1 unless defined $wanted->{follow_skip}; + } + if ( $wanted->{untaint} ) { + $wanted->{untaint_pattern} = $File::Find::untaint_pattern + unless defined $wanted->{untaint_pattern}; + $wanted->{untaint_skip} = 0 unless defined $wanted->{untaint_skip}; + } + return $wanted; + } + elsif( ref( $wanted ) eq 'CODE' ) { + return { wanted => $wanted }; + } + else { + die 'no &wanted subroutine given'; + } +} + +sub find { + my $wanted = shift; + _find_opt(wrap_wanted($wanted), @_); +} + +sub finddepth { + my $wanted = wrap_wanted(shift); + $wanted->{bydepth} = 1; + _find_opt($wanted, @_); +} + +# default +$File::Find::skip_pattern = qr/^\.{1,2}\z/; +$File::Find::untaint_pattern = qr|^([-+@\w./]+)$|; + +# this _should_ work properly on all platforms +# where File::Find can be expected to work +$File::Find::current_dir = File::Spec->curdir || '.'; + +$File::Find::dont_use_nlink = 1; + +# We need a function that checks if a scalar is tainted. Either use the +# Scalar::Util module's tainted() function or our (slower) pure Perl +# fallback is_tainted_pp() +{ + local $@; + eval { require Scalar::Util }; + *is_tainted = $@ ? \&is_tainted_pp : \&Scalar::Util::tainted; +} + +1; + +__END__ + +=head1 NAME + +File::Find - Traverse a directory tree. + +=head1 SYNOPSIS + + use File::Find; + find(\&wanted, @directories_to_search); + sub wanted { ... } + + use File::Find; + finddepth(\&wanted, @directories_to_search); + sub wanted { ... } + + use File::Find; + find({ wanted => \&process, follow => 1 }, '.'); + +=head1 DESCRIPTION + +These are functions for searching through directory trees doing work +on each file found similar to the Unix L command. C +exports two functions, C and C. They work similarly +but have subtle differences. + +=over 4 + +=item B + + find(\&wanted, @directories); + find(\%options, @directories); + +C does a depth-first search over the given C<@directories> in +the order they are given. For each file or directory found, it calls +the C<&wanted> subroutine. (See below for details on how to use the +C<&wanted> function). Additionally, for each directory found, it will +C into that directory and continue the search, invoking the +C<&wanted> function on each file or subdirectory in the directory. + +=item B + + finddepth(\&wanted, @directories); + finddepth(\%options, @directories); + +C works just like C except that it invokes the +C<&wanted> function for a directory I invoking it for the +directory's contents. It does a postorder traversal instead of a +preorder traversal, working from the bottom of the directory tree up +where C works from the top of the tree down. + +=back + +Despite the name of the C function, both C and +C perform a depth-first search of the directory hierarchy. + +=head2 C<%options> + +The first argument to C is either a code reference to your +C<&wanted> function, or a hash reference describing the operations +to be performed for each file. The +code reference is described in L below. + +Here are the possible B for the hash: + +=over 4 + +=item C + +The value should be a code reference. This code reference is +described in L below. The C<&wanted> subroutine is +mandatory. + +=item C + +Reports the name of a directory only AFTER all its entries +have been reported. Entry point C is a shortcut for +specifying C<< { bydepth => 1 } >> in the first argument of C. + +=item C + +The value should be a code reference. This code reference is used to +preprocess the current directory. The name of the currently processed +directory is in C<$File::Find::dir>. Your preprocessing function is +called after C, but before the loop that calls the C +function. It is called with a list of strings (actually file/directory +names) and is expected to return a list of strings. The code can be +used to sort the file/directory names alphabetically, numerically, +or to filter out directory entries based on their name alone. When +C or C are in effect, C is a no-op. + +=item C + +The value should be a code reference. It is invoked just before leaving +the currently processed directory. It is called in void context with no +arguments. The name of the current directory is in C<$File::Find::dir>. This +hook is handy for summarizing a directory, such as calculating its disk +usage. When C or C are in effect, C is a +no-op. + +=item C + +Causes symbolic links to be followed. Since directory trees with symbolic +links (followed) may contain files more than once and may even have +cycles, a hash has to be built up with an entry for each file. +This might be expensive both in space and time for a large +directory tree. See L and L below. +If either C or C is in effect: + +=over 4 + +=item * + +It is guaranteed that an C has been called before the user's +C function is called. This enables fast file checks involving C<_>. +Note that this guarantee no longer holds if C or C +are not set. + +=item * + +There is a variable C<$File::Find::fullname> which holds the absolute +pathname of the file with all symbolic links resolved. If the link is +a dangling symbolic link, then fullname will be set to C. + +=back + +=item C + +This is similar to C except that it may report some files more +than once. It does detect cycles, however. Since only symbolic links +have to be hashed, this is much cheaper both in space and time. If +processing a file more than once (by the user's C function) +is worse than just taking time, the option C should be used. + +=item C + +C, which is the default, causes all files which are +neither directories nor symbolic links to be ignored if they are about +to be processed a second time. If a directory or a symbolic link +are about to be processed a second time, C dies. + +C causes C to die if any file is about to be +processed a second time. + +C causes C to ignore any duplicate files and +directories but to proceed normally otherwise. + +=item C + +Specifies what to do with symbolic links whose target doesn't exist. +If true and a code reference, will be called with the symbolic link +name and the directory it lives in as arguments. Otherwise, if true +and warnings are on, a warning of the form C<"symbolic_link_name is a dangling +symbolic link\n"> will be issued. If false, the dangling symbolic link +will be silently ignored. + +=item C + +Does not C to each directory as it recurses. The C +function will need to be aware of this, of course. In this case, +C<$_> will be the same as C<$File::Find::name>. + +=item C + +If find is used in L (C<-T> command line +switch or C or C), then internally +directory names have to be untainted before they can be C'd to. +Therefore they are checked against a regular expression C. +Note that all names passed to the user's C function are still +tainted. If this option is used while not in taint-mode, C +is a no-op. + +=item C + +See above. This should be set using the C quoting operator. +The default is set to C. +Note that the parentheses are vital. + +=item C + +If set, a directory which fails the C is skipped, +including all its sub-directories. The default is to C in such a case. + +=back + +=head2 The wanted function + +The C function does whatever verifications you want on +each file and directory. Note that despite its name, the C +function is a generic callback function, and does B tell +C if a file is "wanted" or not. In fact, its return value +is ignored. + +The C function takes no arguments but rather does its work +through a collection of variables. + +=over 4 + +=item C<$File::Find::dir> is the current directory name, + +=item C<$_> is the current filename within that directory + +=item C<$File::Find::name> is the complete pathname to the file. + +=back + +The above variables have all been localized and may be changed without +affecting data outside of the wanted function. + +For example, when examining the file F you will have: + + $File::Find::dir = /some/path/ + $_ = foo.ext + $File::Find::name = /some/path/foo.ext + +You are C'd to C<$File::Find::dir> when the function is called, +unless C was specified. Note that when changing to +directories is in effect, the root directory (F) is a somewhat +special case inasmuch as the concatenation of C<$File::Find::dir>, +C<'/'> and C<$_> is not literally equal to C<$File::Find::name>. The +table below summarizes all variants: + + $File::Find::name $File::Find::dir $_ + default / / . + no_chdir=>0 /etc / etc + /etc/x /etc x + + no_chdir=>1 / / / + /etc / /etc + /etc/x /etc /etc/x + + +When C or C are in effect, there is +also a C<$File::Find::fullname>. The function may set +C<$File::Find::prune> to prune the tree unless C was +specified. Unless C or C is specified, for +compatibility reasons (C, L) there are +in addition the following globals available: C<$File::Find::topdir>, +C<$File::Find::topdev>, C<$File::Find::topino>, +C<$File::Find::topmode> and C<$File::Find::topnlink>. + +This library is useful for the C tool (distributed with the +L CPAN module), which when fed: + + find2perl / -name .nfs\* -mtime +7 \ + -exec rm -f {} \; -o -fstype nfs -prune + +produces something like: + + sub wanted { + /^\.nfs.*\z/s && + (($dev, $ino, $mode, $nlink, $uid, $gid) = lstat($_)) && + int(-M _) > 7 && + unlink($_) + || + ($nlink || (($dev, $ino, $mode, $nlink, $uid, $gid) = lstat($_))) && + $dev < 0 && + ($File::Find::prune = 1); + } + +Notice the C<_> in the above C: the C<_> is a magical +filehandle that caches the information from the preceding +C, C, or filetest. + +Here's another interesting wanted function. It will find all symbolic +links that don't resolve: + + sub wanted { + -l && !-e && print "bogus link: $File::Find::name\n"; + } + +Note that you may mix directories and (non-directory) files in the list of +directories to be searched by the C function. + + find(\&wanted, "./foo", "./bar", "./baz/epsilon"); + +In the example above, no file in F<./baz/> other than F<./baz/epsilon> will be +evaluated by C. + +See also the script C on CPAN for a nice application of this +module. + +=head1 WARNINGS + +If you run your program with the C<-w> switch, or if you use the +C pragma, File::Find will report warnings for several weird +situations. You can disable these warnings by putting the statement + + no warnings 'File::Find'; + +in the appropriate scope. See L for more info about lexical +warnings. + +=head1 BUGS AND CAVEATS + +=over 4 + +=item C<$dont_use_nlink> + +You can set the variable C<$File::Find::dont_use_nlink> to C<0> if you +are sure the filesystem you are scanning reflects the number of +subdirectories in the parent directory's C count. + +If you do set C<$File::Find::dont_use_nlink> to 0, you may notice an +improvement in speed at the risk of not recursing into subdirectories +if a filesystem doesn't populate C as expected. + +C<$File::Find::dont_use_nlink> now defaults to 1 on all platforms. + +=item Symlinks + +Be aware that the option to follow symbolic links can be dangerous. +Depending on the structure of the directory tree (including symbolic +links to directories) you might traverse a given (physical) directory +more than once (only if C is in effect). +Furthermore, deleting or changing files in a symbolically linked directory +might cause very unpleasant surprises, since you delete or change files +in an unknown directory. + +=back + +=head1 HISTORY + +C used to produce incorrect results if called recursively. +During the development of perl 5.8 this bug was fixed. +The first fixed version of C was 1.01. + +=head1 SEE ALSO + +L, L + +=cut diff --git a/git/usr/share/perl5/core_perl/File/GlobMapper.pm b/git/usr/share/perl5/core_perl/File/GlobMapper.pm new file mode 100644 index 0000000000000000000000000000000000000000..53f957aef36cde025065c98241ce0b52d4960c63 --- /dev/null +++ b/git/usr/share/perl5/core_perl/File/GlobMapper.pm @@ -0,0 +1,679 @@ +package File::GlobMapper; + +use strict; +use warnings; +use Carp; + +our ($CSH_GLOB); + +BEGIN +{ + if ($] < 5.006) + { + require File::BSDGlob; File::BSDGlob->import(':glob'); + $CSH_GLOB = File::BSDGlob::GLOB_CSH(); + *globber = \&File::BSDGlob::csh_glob; + } + else + { + require File::Glob; File::Glob->import(':glob'); + $CSH_GLOB = File::Glob::GLOB_CSH(); + #*globber = \&File::Glob::bsd_glob; + *globber = \&File::Glob::csh_glob; + } +} + +our ($Error); + +our ($VERSION, @EXPORT_OK); +$VERSION = '1.001'; +@EXPORT_OK = qw( globmap ); + + +our ($noPreBS, $metachars, $matchMetaRE, %mapping, %wildCount); +$noPreBS = '(? '([^/]*)', + '?' => '([^/])', + '.' => '\.', + '[' => '([', + '(' => '(', + ')' => ')', + ); + +%wildCount = map { $_ => 1 } qw/ * ? . { ( [ /; + +sub globmap ($$;) +{ + my $inputGlob = shift ; + my $outputGlob = shift ; + + my $obj = File::GlobMapper->new($inputGlob, $outputGlob, @_) + or croak "globmap: $Error" ; + return $obj->getFileMap(); +} + +sub new +{ + my $class = shift ; + my $inputGlob = shift ; + my $outputGlob = shift ; + # TODO -- flags needs to default to whatever File::Glob does + my $flags = shift || $CSH_GLOB ; + #my $flags = shift ; + + $inputGlob =~ s/^\s*\<\s*//; + $inputGlob =~ s/\s*\>\s*$//; + + $outputGlob =~ s/^\s*\<\s*//; + $outputGlob =~ s/\s*\>\s*$//; + + my %object = + ( InputGlob => $inputGlob, + OutputGlob => $outputGlob, + GlobFlags => $flags, + Braces => 0, + WildCount => 0, + Pairs => [], + Sigil => '#', + ); + + my $self = bless \%object, ref($class) || $class ; + + $self->_parseInputGlob() + or return undef ; + + $self->_parseOutputGlob() + or return undef ; + + my @inputFiles = globber($self->{InputGlob}, $flags) ; + + if (GLOB_ERROR) + { + $Error = $!; + return undef ; + } + + #if (whatever) + { + my $missing = grep { ! -e $_ } @inputFiles ; + + if ($missing) + { + $Error = "$missing input files do not exist"; + return undef ; + } + } + + $self->{InputFiles} = \@inputFiles ; + + $self->_getFiles() + or return undef ; + + return $self; +} + +sub _retError +{ + my $string = shift ; + $Error = "$string in input fileglob" ; + return undef ; +} + +sub _unmatched +{ + my $delimeter = shift ; + + _retError("Unmatched $delimeter"); + return undef ; +} + +sub _parseBit +{ + my $self = shift ; + + my $string = shift ; + + my $out = ''; + my $depth = 0 ; + + while ($string =~ s/(.*?)$noPreBS(,|$matchMetaRE)//) + { + $out .= quotemeta($1) ; + $out .= $mapping{$2} if defined $mapping{$2}; + + ++ $self->{WildCount} if $wildCount{$2} ; + + if ($2 eq ',') + { + return _unmatched("(") + if $depth ; + + $out .= '|'; + } + elsif ($2 eq '(') + { + ++ $depth ; + } + elsif ($2 eq ')') + { + return _unmatched(")") + if ! $depth ; + + -- $depth ; + } + elsif ($2 eq '[') + { + # TODO -- quotemeta & check no '/' + # TODO -- check for \] & other \ within the [] + $string =~ s#(.*?\])## + or return _unmatched("["); + $out .= "$1)" ; + } + elsif ($2 eq ']') + { + return _unmatched("]"); + } + elsif ($2 eq '{' || $2 eq '}') + { + return _retError("Nested {} not allowed"); + } + } + + $out .= quotemeta $string; + + return _unmatched("(") + if $depth ; + + return $out ; +} + +sub _parseInputGlob +{ + my $self = shift ; + + my $string = $self->{InputGlob} ; + my $inGlob = ''; + + # Multiple concatenated *'s don't make sense + #$string =~ s#\*\*+#*# ; + + # TODO -- Allow space to delimit patterns? + #my @strings = split /\s+/, $string ; + #for my $str (@strings) + my $out = ''; + my $depth = 0 ; + + while ($string =~ s/(.*?)$noPreBS($matchMetaRE)//) + { + $out .= quotemeta($1) ; + $out .= $mapping{$2} if defined $mapping{$2}; + ++ $self->{WildCount} if $wildCount{$2} ; + + if ($2 eq '(') + { + ++ $depth ; + } + elsif ($2 eq ')') + { + return _unmatched(")") + if ! $depth ; + + -- $depth ; + } + elsif ($2 eq '[') + { + # TODO -- quotemeta & check no '/' or '(' or ')' + # TODO -- check for \] & other \ within the [] + $string =~ s#(.*?\])## + or return _unmatched("["); + $out .= "$1)" ; + } + elsif ($2 eq ']') + { + return _unmatched("]"); + } + elsif ($2 eq '}') + { + return _unmatched("}"); + } + elsif ($2 eq '{') + { + # TODO -- check no '/' within the {} + # TODO -- check for \} & other \ within the {} + + my $tmp ; + unless ( $string =~ s/(.*?)$noPreBS\}//) + { + return _unmatched("{"); + } + #$string =~ s#(.*?)\}##; + + #my $alt = join '|', + # map { quotemeta $_ } + # split "$noPreBS,", $1 ; + my $alt = $self->_parseBit($1); + defined $alt or return 0 ; + $out .= "($alt)" ; + + ++ $self->{Braces} ; + } + } + + return _unmatched("(") + if $depth ; + + $out .= quotemeta $string ; + + + $self->{InputGlob} =~ s/$noPreBS[\(\)]//g; + $self->{InputPattern} = $out ; + + #print "# INPUT '$self->{InputGlob}' => '$out'\n"; + + return 1 ; + +} + +sub _parseOutputGlob +{ + my $self = shift ; + + my $string = $self->{OutputGlob} ; + my $maxwild = $self->{WildCount}; + + if ($self->{GlobFlags} & GLOB_TILDE) + #if (1) + { + $string =~ s{ + ^ ~ # find a leading tilde + ( # save this in $1 + [^/] # a non-slash character + * # repeated 0 or more times (0 means me) + ) + }{ + $1 + ? (getpwnam($1))[7] + : ( $ENV{HOME} || $ENV{LOGDIR} ) + }ex; + + } + + # max #1 must be == to max no of '*' in input + while ( $string =~ m/#(\d)/g ) + { + croak "Max wild is #$maxwild, you tried #$1" + if $1 > $maxwild ; + } + + my $noPreBS = '(?{OutputGlob}' => '$string'\n"; + $self->{OutputPattern} = $string ; + + return 1 ; +} + +sub _getFiles +{ + my $self = shift ; + + my %outInMapping = (); + my %inFiles = () ; + + foreach my $inFile (@{ $self->{InputFiles} }) + { + next if $inFiles{$inFile} ++ ; + + my $outFile = $inFile ; + + if ( $inFile =~ m/$self->{InputPattern}/ ) + { + no warnings 'uninitialized'; + eval "\$outFile = $self->{OutputPattern};" ; + + if (defined $outInMapping{$outFile}) + { + $Error = "multiple input files map to one output file"; + return undef ; + } + $outInMapping{$outFile} = $inFile; + push @{ $self->{Pairs} }, [$inFile, $outFile]; + } + } + + return 1 ; +} + +sub getFileMap +{ + my $self = shift ; + + return $self->{Pairs} ; +} + +sub getHash +{ + my $self = shift ; + + return { map { $_->[0] => $_->[1] } @{ $self->{Pairs} } } ; +} + +1; + +__END__ + +=head1 NAME + +File::GlobMapper - Extend File Glob to Allow Input and Output Files + +=head1 SYNOPSIS + + use File::GlobMapper qw( globmap ); + + my $aref = globmap $input => $output + or die $File::GlobMapper::Error ; + + my $gm = File::GlobMapper->new( $input => $output ) + or die $File::GlobMapper::Error ; + + +=head1 DESCRIPTION + +This module needs Perl5.005 or better. + +This module takes the existing C module as a starting point and +extends it to allow new filenames to be derived from the files matched by +C. + +This can be useful when carrying out batch operations on multiple files that +have both an input filename and output filename and the output file can be +derived from the input filename. Examples of operations where this can be +useful include, file renaming, file copying and file compression. + + +=head2 Behind The Scenes + +To help explain what C does, consider what code you +would write if you wanted to rename all files in the current directory +that ended in C<.tar.gz> to C<.tgz>. So say these files are in the +current directory + + alpha.tar.gz + beta.tar.gz + gamma.tar.gz + +and they need renamed to this + + alpha.tgz + beta.tgz + gamma.tgz + +Below is a possible implementation of a script to carry out the rename +(error cases have been omitted) + + foreach my $old ( glob "*.tar.gz" ) + { + my $new = $old; + $new =~ s#(.*)\.tar\.gz$#$1.tgz# ; + + rename $old => $new + or die "Cannot rename '$old' to '$new': $!\n; + } + +Notice that a file glob pattern C<*.tar.gz> was used to match the +C<.tar.gz> files, then a fairly similar regular expression was used in +the substitute to allow the new filename to be created. + +Given that the file glob is just a cut-down regular expression and that it +has already done a lot of the hard work in pattern matching the filenames, +wouldn't it be handy to be able to use the patterns in the fileglob to +drive the new filename? + +Well, that's I what C does. + +Here is same snippet of code rewritten using C + + for my $pair (globmap '<*.tar.gz>' => '<#1.tgz>' ) + { + my ($from, $to) = @$pair; + rename $from => $to + or die "Cannot rename '$old' to '$new': $!\n; + } + +So how does it work? + +Behind the scenes the C function does a combination of a +file glob to match existing filenames followed by a substitute +to create the new filenames. + +Notice how both parameters to C are strings that are delimited by <>. +This is done to make them look more like file globs - it is just syntactic +sugar, but it can be handy when you want the strings to be visually +distinctive. The enclosing <> are optional, so you don't have to use them - in +fact the first thing globmap will do is remove these delimiters if they are +present. + +The first parameter to C, C<*.tar.gz>, is an I. +Once the enclosing "< ... >" is removed, this is passed (more or +less) unchanged to C to carry out a file match. + +Next the fileglob C<*.tar.gz> is transformed behind the scenes into a +full Perl regular expression, with the additional step of wrapping each +transformed wildcard metacharacter sequence in parenthesis. + +In this case the input fileglob C<*.tar.gz> will be transformed into +this Perl regular expression + + ([^/]*)\.tar\.gz + +Wrapping with parenthesis allows the wildcard parts of the Input File +Glob to be referenced by the second parameter to C, C<#1.tgz>, +the I. This parameter operates just like the replacement +part of a substitute command. The difference is that the C<#1> syntax +is used to reference sub-patterns matched in the input fileglob, rather +than the C<$1> syntax that is used with perl regular expressions. In +this case C<#1> is used to refer to the text matched by the C<*> in the +Input File Glob. This makes it easier to use this module where the +parameters to C are typed at the command line. + +The final step involves passing each filename matched by the C<*.tar.gz> +file glob through the derived Perl regular expression in turn and +expanding the output fileglob using it. + +The end result of all this is a list of pairs of filenames. By default +that is what is returned by C. In this example the data structure +returned will look like this + + ( ['alpha.tar.gz' => 'alpha.tgz'], + ['beta.tar.gz' => 'beta.tgz' ], + ['gamma.tar.gz' => 'gamma.tgz'] + ) + + +Each pair is an array reference with two elements - namely the I +filename, that C has matched, and a I filename that is +derived from the I filename. + + + +=head2 Limitations + +C has been kept simple deliberately, so it isn't intended to +solve all filename mapping operations. Under the hood C (or for +older versions of Perl, C) is used to match the files, so you +will never have the flexibility of full Perl regular expression. + +=head2 Input File Glob + +The syntax for an Input FileGlob is identical to C, except +for the following + +=over 5 + +=item 1. + +No nested {} + +=item 2. + +Whitespace does not delimit fileglobs. + +=item 3. + +The use of parenthesis can be used to capture parts of the input filename. + +=item 4. + +If an Input glob matches the same file more than once, only the first +will be used. + +=back + +The syntax + +=over 5 + +=item B<~> + +=item B<~user> + + +=item B<.> + +Matches a literal '.'. +Equivalent to the Perl regular expression + + \. + +=item B<*> + +Matches zero or more characters, except '/'. Equivalent to the Perl +regular expression + + [^/]* + +=item B + +Matches zero or one character, except '/'. Equivalent to the Perl +regular expression + + [^/]? + +=item B<\> + +Backslash is used, as usual, to escape the next character. + +=item B<[]> + +Character class. + +=item B<{,}> + +Alternation + +=item B<()> + +Capturing parenthesis that work just like perl + +=back + +Any other character it taken literally. + +=head2 Output File Glob + +The Output File Glob is a normal string, with 2 glob-like features. + +The first is the '*' metacharacter. This will be replaced by the complete +filename matched by the input file glob. So + + *.c *.Z + +The second is + +Output FileGlobs take the + +=over 5 + +=item "*" + +The "*" character will be replaced with the complete input filename. + +=item #1 + +Patterns of the form /#\d/ will be replaced with the + +=back + +=head2 Returned Data + + +=head1 EXAMPLES + +=head2 A Rename script + +Below is a simple "rename" script that uses C to determine the +source and destination filenames. + + use File::GlobMapper qw(globmap) ; + use File::Copy; + + die "rename: Usage rename 'from' 'to'\n" + unless @ARGV == 2 ; + + my $fromGlob = shift @ARGV; + my $toGlob = shift @ARGV; + + my $pairs = globmap($fromGlob, $toGlob) + or die $File::GlobMapper::Error; + + for my $pair (@$pairs) + { + my ($from, $to) = @$pair; + move $from => $to ; + } + + + +Here is an example that renames all c files to cpp. + + $ rename '*.c' '#1.cpp' + +=head2 A few example globmaps + +Below are a few examples of globmaps + +To copy all your .c file to a backup directory + + '' '' + +If you want to compress all + + '' '<*.gz>' + +To uncompress + + '' '' + +=head1 SEE ALSO + +L + +=head1 AUTHOR + +The I module was written by Paul Marquess, F. + +=head1 COPYRIGHT AND LICENSE + +Copyright (c) 2005 Paul Marquess. All rights reserved. +This program is free software; you can redistribute it and/or +modify it under the same terms as Perl itself. diff --git a/git/usr/share/perl5/core_perl/File/Path.pm b/git/usr/share/perl5/core_perl/File/Path.pm new file mode 100644 index 0000000000000000000000000000000000000000..3f7545fdbe0adf902f178d500f6c4a369c790514 --- /dev/null +++ b/git/usr/share/perl5/core_perl/File/Path.pm @@ -0,0 +1,1287 @@ +package File::Path; + +use 5.005_04; +use strict; + +use Cwd 'getcwd'; +use File::Basename (); +use File::Spec (); + +BEGIN { + if ( $] < 5.006 ) { + + # can't say 'opendir my $dh, $dirname' + # need to initialise $dh + eval 'use Symbol'; + } +} + +use Exporter (); +use vars qw($VERSION @ISA @EXPORT @EXPORT_OK); +$VERSION = '2.18'; +$VERSION = eval $VERSION; +@ISA = qw(Exporter); +@EXPORT = qw(mkpath rmtree); +@EXPORT_OK = qw(make_path remove_tree); + +BEGIN { + for (qw(VMS MacOS MSWin32 os2)) { + no strict 'refs'; + *{"_IS_\U$_"} = $^O eq $_ ? sub () { 1 } : sub () { 0 }; + } + + # These OSes complain if you want to remove a file that you have no + # write permission to: + *_FORCE_WRITABLE = ( + grep { $^O eq $_ } qw(amigaos dos epoc MSWin32 MacOS os2) + ) ? sub () { 1 } : sub () { 0 }; + + # Unix-like systems need to stat each directory in order to detect + # race condition. MS-Windows is immune to this particular attack. + *_NEED_STAT_CHECK = !(_IS_MSWIN32()) ? sub () { 1 } : sub () { 0 }; +} + +sub _carp { + require Carp; + goto &Carp::carp; +} + +sub _croak { + require Carp; + goto &Carp::croak; +} + +sub _error { + my $arg = shift; + my $message = shift; + my $object = shift; + + if ( $arg->{error} ) { + $object = '' unless defined $object; + $message .= ": $!" if $!; + push @{ ${ $arg->{error} } }, { $object => $message }; + } + else { + _carp( defined($object) ? "$message for $object: $!" : "$message: $!" ); + } +} + +sub __is_arg { + my ($arg) = @_; + + # If client code blessed an array ref to HASH, this will not work + # properly. We could have done $arg->isa() wrapped in eval, but + # that would be expensive. This implementation should suffice. + # We could have also used Scalar::Util:blessed, but we choose not + # to add this dependency + return ( ref $arg eq 'HASH' ); +} + +sub make_path { + push @_, {} unless @_ and __is_arg( $_[-1] ); + goto &mkpath; +} + +sub mkpath { + my $old_style = !( @_ and __is_arg( $_[-1] ) ); + + my $data; + my $paths; + + if ($old_style) { + my ( $verbose, $mode ); + ( $paths, $verbose, $mode ) = @_; + $paths = [$paths] unless UNIVERSAL::isa( $paths, 'ARRAY' ); + $data->{verbose} = $verbose; + $data->{mode} = defined $mode ? $mode : oct '777'; + } + else { + my %args_permitted = map { $_ => 1 } ( qw| + chmod + error + group + mask + mode + owner + uid + user + verbose + | ); + my %not_on_win32_args = map { $_ => 1 } ( qw| + group + owner + uid + user + | ); + my @bad_args = (); + my @win32_implausible_args = (); + my $arg = pop @_; + for my $k (sort keys %{$arg}) { + if (! $args_permitted{$k}) { + push @bad_args, $k; + } + elsif ($not_on_win32_args{$k} and _IS_MSWIN32) { + push @win32_implausible_args, $k; + } + else { + $data->{$k} = $arg->{$k}; + } + } + _carp("Unrecognized option(s) passed to mkpath() or make_path(): @bad_args") + if @bad_args; + _carp("Option(s) implausible on Win32 passed to mkpath() or make_path(): @win32_implausible_args") + if @win32_implausible_args; + $data->{mode} = delete $data->{mask} if exists $data->{mask}; + $data->{mode} = oct '777' unless exists $data->{mode}; + ${ $data->{error} } = [] if exists $data->{error}; + unless (@win32_implausible_args) { + $data->{owner} = delete $data->{user} if exists $data->{user}; + $data->{owner} = delete $data->{uid} if exists $data->{uid}; + if ( exists $data->{owner} and $data->{owner} =~ /\D/ ) { + my $uid = ( getpwnam $data->{owner} )[2]; + if ( defined $uid ) { + $data->{owner} = $uid; + } + else { + _error( $data, + "unable to map $data->{owner} to a uid, ownership not changed" + ); + delete $data->{owner}; + } + } + if ( exists $data->{group} and $data->{group} =~ /\D/ ) { + my $gid = ( getgrnam $data->{group} )[2]; + if ( defined $gid ) { + $data->{group} = $gid; + } + else { + _error( $data, + "unable to map $data->{group} to a gid, group ownership not changed" + ); + delete $data->{group}; + } + } + if ( exists $data->{owner} and not exists $data->{group} ) { + $data->{group} = -1; # chown will leave group unchanged + } + if ( exists $data->{group} and not exists $data->{owner} ) { + $data->{owner} = -1; # chown will leave owner unchanged + } + } + $paths = [@_]; + } + return _mkpath( $data, $paths ); +} + +sub _mkpath { + my $data = shift; + my $paths = shift; + + my ( @created ); + foreach my $path ( @{$paths} ) { + next unless defined($path) and length($path); + $path .= '/' if _IS_OS2 and $path =~ /^\w:\z/s; # feature of CRT + + # Logic wants Unix paths, so go with the flow. + if (_IS_VMS) { + next if $path eq '/'; + $path = VMS::Filespec::unixify($path); + } + next if -d $path; + my $parent = File::Basename::dirname($path); + # Coverage note: It's not clear how we would test the condition: + # '-d $parent or $path eq $parent' + unless ( -d $parent or $path eq $parent ) { + push( @created, _mkpath( $data, [$parent] ) ); + } + print "mkdir $path\n" if $data->{verbose}; + if ( mkdir( $path, $data->{mode} ) ) { + push( @created, $path ); + if ( exists $data->{owner} ) { + + # NB: $data->{group} guaranteed to be set during initialisation + if ( !chown $data->{owner}, $data->{group}, $path ) { + _error( $data, + "Cannot change ownership of $path to $data->{owner}:$data->{group}" + ); + } + } + if ( exists $data->{chmod} ) { + # Coverage note: It's not clear how we would trigger the next + # 'if' block. Failure of 'chmod' might first result in a + # system error: "Permission denied". + if ( !chmod $data->{chmod}, $path ) { + _error( $data, + "Cannot change permissions of $path to $data->{chmod}" ); + } + } + } + else { + my $save_bang = $!; + + # From 'perldoc perlvar': $EXTENDED_OS_ERROR ($^E) is documented + # as: + # Error information specific to the current operating system. At the + # moment, this differs from "$!" under only VMS, OS/2, and Win32 + # (and for MacPerl). On all other platforms, $^E is always just the + # same as $!. + + my ( $e, $e1 ) = ( $save_bang, $^E ); + $e .= "; $e1" if $e ne $e1; + + # allow for another process to have created it meanwhile + if ( ! -d $path ) { + $! = $save_bang; + if ( $data->{error} ) { + push @{ ${ $data->{error} } }, { $path => $e }; + } + else { + _croak("mkdir $path: $e"); + } + } + } + } + return @created; +} + +sub remove_tree { + push @_, {} unless @_ and __is_arg( $_[-1] ); + goto &rmtree; +} + +sub _is_subdir { + my ( $dir, $test ) = @_; + + my ( $dv, $dd ) = File::Spec->splitpath( $dir, 1 ); + my ( $tv, $td ) = File::Spec->splitpath( $test, 1 ); + + # not on same volume + return 0 if $dv ne $tv; + + my @d = File::Spec->splitdir($dd); + my @t = File::Spec->splitdir($td); + + # @t can't be a subdir if it's shorter than @d + return 0 if @t < @d; + + return join( '/', @d ) eq join( '/', splice @t, 0, +@d ); +} + +sub rmtree { + my $old_style = !( @_ and __is_arg( $_[-1] ) ); + + my ($arg, $data, $paths); + + if ($old_style) { + my ( $verbose, $safe ); + ( $paths, $verbose, $safe ) = @_; + $data->{verbose} = $verbose; + $data->{safe} = defined $safe ? $safe : 0; + + if ( defined($paths) and length($paths) ) { + $paths = [$paths] unless UNIVERSAL::isa( $paths, 'ARRAY' ); + } + else { + _carp("No root path(s) specified\n"); + return 0; + } + } + else { + my %args_permitted = map { $_ => 1 } ( qw| + error + keep_root + result + safe + verbose + | ); + my @bad_args = (); + my $arg = pop @_; + for my $k (sort keys %{$arg}) { + if (! $args_permitted{$k}) { + push @bad_args, $k; + } + else { + $data->{$k} = $arg->{$k}; + } + } + _carp("Unrecognized option(s) passed to remove_tree(): @bad_args") + if @bad_args; + ${ $data->{error} } = [] if exists $data->{error}; + ${ $data->{result} } = [] if exists $data->{result}; + + # Wouldn't it make sense to do some validation on @_ before assigning + # to $paths here? + # In the $old_style case we guarantee that each path is both defined + # and non-empty. We don't check that here, which means we have to + # check it later in the first condition in this line: + # if ( $ortho_root_length && _is_subdir( $ortho_root, $ortho_cwd ) ) { + # Granted, that would be a change in behavior for the two + # non-old-style interfaces. + + $paths = [@_]; + } + + $data->{prefix} = ''; + $data->{depth} = 0; + + my @clean_path; + $data->{cwd} = getcwd() or do { + _error( $data, "cannot fetch initial working directory" ); + return 0; + }; + for ( $data->{cwd} ) { /\A(.*)\Z/s; $_ = $1 } # untaint + + for my $p (@$paths) { + + # need to fixup case and map \ to / on Windows + my $ortho_root = _IS_MSWIN32 ? _slash_lc($p) : $p; + my $ortho_cwd = + _IS_MSWIN32 ? _slash_lc( $data->{cwd} ) : $data->{cwd}; + my $ortho_root_length = length($ortho_root); + $ortho_root_length-- if _IS_VMS; # don't compare '.' with ']' + if ( $ortho_root_length && _is_subdir( $ortho_root, $ortho_cwd ) ) { + local $! = 0; + _error( $data, "cannot remove path when cwd is $data->{cwd}", $p ); + next; + } + + if (_IS_MACOS) { + $p = ":$p" unless $p =~ /:/; + $p .= ":" unless $p =~ /:\z/; + } + elsif ( _IS_MSWIN32 ) { + $p =~ s{[/\\]\z}{}; + } + else { + $p =~ s{/\z}{}; + } + push @clean_path, $p; + } + + @{$data}{qw(device inode)} = ( lstat $data->{cwd} )[ 0, 1 ] or do { + _error( $data, "cannot stat initial working directory", $data->{cwd} ); + return 0; + }; + + return _rmtree( $data, \@clean_path ); +} + +sub _rmtree { + my $data = shift; + my $paths = shift; + + my $count = 0; + my $curdir = File::Spec->curdir(); + my $updir = File::Spec->updir(); + + my ( @files, $root ); + ROOT_DIR: + foreach my $root (@$paths) { + + # since we chdir into each directory, it may not be obvious + # to figure out where we are if we generate a message about + # a file name. We therefore construct a semi-canonical + # filename, anchored from the directory being unlinked (as + # opposed to being truly canonical, anchored from the root (/). + + my $canon = + $data->{prefix} + ? File::Spec->catfile( $data->{prefix}, $root ) + : $root; + + my ( $ldev, $lino, $perm ) = ( lstat $root )[ 0, 1, 2 ] + or next ROOT_DIR; + + if ( -d _ ) { + $root = VMS::Filespec::vmspath( VMS::Filespec::pathify($root) ) + if _IS_VMS; + + if ( !chdir($root) ) { + + # see if we can escalate privileges to get in + # (e.g. funny protection mask such as -w- instead of rwx) + # This uses fchmod to avoid traversing outside of the proper + # location (CVE-2017-6512) + my $root_fh; + if (open($root_fh, '<', $root)) { + my ($fh_dev, $fh_inode) = (stat $root_fh )[0,1]; + $perm &= oct '7777'; + my $nperm = $perm | oct '700'; + local $@; + if ( + !( + $data->{safe} + or $nperm == $perm + or !-d _ + or $fh_dev ne $ldev + or $fh_inode ne $lino + or eval { chmod( $nperm, $root_fh ) } + ) + ) + { + _error( $data, + "cannot make child directory read-write-exec", $canon ); + next ROOT_DIR; + } + close $root_fh; + } + if ( !chdir($root) ) { + _error( $data, "cannot chdir to child", $canon ); + next ROOT_DIR; + } + } + + my ( $cur_dev, $cur_inode, $perm ) = ( stat $curdir )[ 0, 1, 2 ] + or do { + _error( $data, "cannot stat current working directory", $canon ); + next ROOT_DIR; + }; + + if (_NEED_STAT_CHECK) { + ( $ldev eq $cur_dev and $lino eq $cur_inode ) + or _croak( +"directory $canon changed before chdir, expected dev=$ldev ino=$lino, actual dev=$cur_dev ino=$cur_inode, aborting." + ); + } + + $perm &= oct '7777'; # don't forget setuid, setgid, sticky bits + my $nperm = $perm | oct '700'; + + # notabene: 0700 is for making readable in the first place, + # it's also intended to change it to writable in case we have + # to recurse in which case we are better than rm -rf for + # subtrees with strange permissions + + if ( + !( + $data->{safe} + or $nperm == $perm + or chmod( $nperm, $curdir ) + ) + ) + { + _error( $data, "cannot make directory read+writeable", $canon ); + $nperm = $perm; + } + + my $d; + $d = gensym() if $] < 5.006; + if ( !opendir $d, $curdir ) { + _error( $data, "cannot opendir", $canon ); + @files = (); + } + else { + if ( !defined ${^TAINT} or ${^TAINT} ) { + # Blindly untaint dir names if taint mode is active + @files = map { /\A(.*)\z/s; $1 } readdir $d; + } + else { + @files = readdir $d; + } + closedir $d; + } + + if (_IS_VMS) { + + # Deleting large numbers of files from VMS Files-11 + # filesystems is faster if done in reverse ASCIIbetical order. + # include '.' to '.;' from blead patch #31775 + @files = map { $_ eq '.' ? '.;' : $_ } reverse @files; + } + + @files = grep { $_ ne $updir and $_ ne $curdir } @files; + + if (@files) { + + # remove the contained files before the directory itself + my $narg = {%$data}; + @{$narg}{qw(device inode cwd prefix depth)} = + ( $cur_dev, $cur_inode, $updir, $canon, $data->{depth} + 1 ); + $count += _rmtree( $narg, \@files ); + } + + # restore directory permissions of required now (in case the rmdir + # below fails), while we are still in the directory and may do so + # without a race via '.' + if ( $nperm != $perm and not chmod( $perm, $curdir ) ) { + _error( $data, "cannot reset chmod", $canon ); + } + + # don't leave the client code in an unexpected directory + chdir( $data->{cwd} ) + or + _croak("cannot chdir to $data->{cwd} from $canon: $!, aborting."); + + # ensure that a chdir upwards didn't take us somewhere other + # than we expected (see CVE-2002-0435) + ( $cur_dev, $cur_inode ) = ( stat $curdir )[ 0, 1 ] + or _croak( + "cannot stat prior working directory $data->{cwd}: $!, aborting." + ); + + if (_NEED_STAT_CHECK) { + ( $data->{device} eq $cur_dev and $data->{inode} eq $cur_inode ) + or _croak( "previous directory $data->{cwd} " + . "changed before entering $canon, " + . "expected dev=$ldev ino=$lino, " + . "actual dev=$cur_dev ino=$cur_inode, aborting." + ); + } + + if ( $data->{depth} or !$data->{keep_root} ) { + if ( $data->{safe} + && ( _IS_VMS + ? !&VMS::Filespec::candelete($root) + : !-w $root ) ) + { + print "skipped $root\n" if $data->{verbose}; + next ROOT_DIR; + } + if ( _FORCE_WRITABLE and !chmod $perm | oct '700', $root ) { + _error( $data, "cannot make directory writeable", $canon ); + } + print "rmdir $root\n" if $data->{verbose}; + if ( rmdir $root ) { + push @{ ${ $data->{result} } }, $root if $data->{result}; + ++$count; + } + else { + _error( $data, "cannot remove directory", $canon ); + if ( + _FORCE_WRITABLE + && !chmod( $perm, + ( _IS_VMS ? VMS::Filespec::fileify($root) : $root ) + ) + ) + { + _error( + $data, + sprintf( "cannot restore permissions to 0%o", + $perm ), + $canon + ); + } + } + } + } + else { + # not a directory + $root = VMS::Filespec::vmsify("./$root") + if _IS_VMS + && !File::Spec->file_name_is_absolute($root) + && ( $root !~ m/(?]+/ ); # not already in VMS syntax + + if ( + $data->{safe} + && ( + _IS_VMS + ? !&VMS::Filespec::candelete($root) + : !( -l $root || -w $root ) + ) + ) + { + print "skipped $root\n" if $data->{verbose}; + next ROOT_DIR; + } + + my $nperm = $perm & oct '7777' | oct '600'; + if ( _FORCE_WRITABLE + and $nperm != $perm + and not chmod $nperm, $root ) + { + _error( $data, "cannot make file writeable", $canon ); + } + print "unlink $canon\n" if $data->{verbose}; + + # delete all versions under VMS + for ( ; ; ) { + if ( unlink $root ) { + push @{ ${ $data->{result} } }, $root if $data->{result}; + } + else { + _error( $data, "cannot unlink file", $canon ); + _FORCE_WRITABLE and chmod( $perm, $root ) + or _error( $data, + sprintf( "cannot restore permissions to 0%o", $perm ), + $canon ); + last; + } + ++$count; + last unless _IS_VMS && lstat $root; + } + } + } + return $count; +} + +sub _slash_lc { + + # fix up slashes and case on MSWin32 so that we can determine that + # c:\path\to\dir is underneath C:/Path/To + my $path = shift; + $path =~ tr{\\}{/}; + return lc($path); +} + +1; + +__END__ + +=head1 NAME + +File::Path - Create or remove directory trees + +=head1 VERSION + +2.18 - released November 4 2020. + +=head1 SYNOPSIS + + use File::Path qw(make_path remove_tree); + + @created = make_path('foo/bar/baz', '/zug/zwang'); + @created = make_path('foo/bar/baz', '/zug/zwang', { + verbose => 1, + mode => 0711, + }); + make_path('foo/bar/baz', '/zug/zwang', { + chmod => 0777, + }); + + $removed_count = remove_tree('foo/bar/baz', '/zug/zwang', { + verbose => 1, + error => \my $err_list, + safe => 1, + }); + + # legacy (interface promoted before v2.00) + @created = mkpath('/foo/bar/baz'); + @created = mkpath('/foo/bar/baz', 1, 0711); + @created = mkpath(['/foo/bar/baz', 'blurfl/quux'], 1, 0711); + $removed_count = rmtree('foo/bar/baz', 1, 1); + $removed_count = rmtree(['foo/bar/baz', 'blurfl/quux'], 1, 1); + + # legacy (interface promoted before v2.06) + @created = mkpath('foo/bar/baz', '/zug/zwang', { verbose => 1, mode => 0711 }); + $removed_count = rmtree('foo/bar/baz', '/zug/zwang', { verbose => 1, mode => 0711 }); + +=head1 DESCRIPTION + +This module provides a convenient way to create directories of +arbitrary depth and to delete an entire directory subtree from the +filesystem. + +The following functions are provided: + +=over + +=item make_path( $dir1, $dir2, .... ) + +=item make_path( $dir1, $dir2, ...., \%opts ) + +The C function creates the given directories if they don't +exist before, much like the Unix command C. + +The function accepts a list of directories to be created. Its +behaviour may be tuned by an optional hashref appearing as the last +parameter on the call. + +The function returns the list of directories actually created during +the call; in scalar context the number of directories created. + +The following keys are recognised in the option hash: + +=over + +=item mode => $num + +The numeric permissions mode to apply to each created directory +(defaults to C<0777>), to be modified by the current C. If the +directory already exists (and thus does not need to be created), +the permissions will not be modified. + +C is recognised as an alias for this parameter. + +=item chmod => $num + +Takes a numeric mode to apply to each created directory (not +modified by the current C). If the directory already exists +(and thus does not need to be created), the permissions will +not be modified. + +=item verbose => $bool + +If present, will cause C to print the name of each directory +as it is created. By default nothing is printed. + +=item error => \$err + +If present, it should be a reference to a scalar. +This scalar will be made to reference an array, which will +be used to store any errors that are encountered. See the L section for more information. + +If this parameter is not used, certain error conditions may raise +a fatal error that will cause the program to halt, unless trapped +in an C block. + +=item owner => $owner + +=item user => $owner + +=item uid => $owner + +If present, will cause any created directory to be owned by C<$owner>. +If the value is numeric, it will be interpreted as a uid; otherwise a +username is assumed. An error will be issued if the username cannot be +mapped to a uid, the uid does not exist or the process lacks the +privileges to change ownership. + +Ownership of directories that already exist will not be changed. + +C and C are aliases of C. + +=item group => $group + +If present, will cause any created directory to be owned by the group +C<$group>. If the value is numeric, it will be interpreted as a gid; +otherwise a group name is assumed. An error will be issued if the +group name cannot be mapped to a gid, the gid does not exist or the +process lacks the privileges to change group ownership. + +Group ownership of directories that already exist will not be changed. + + make_path '/var/tmp/webcache', {owner=>'nobody', group=>'nogroup'}; + +=back + +=item mkpath( $dir ) + +=item mkpath( $dir, $verbose, $mode ) + +=item mkpath( [$dir1, $dir2,...], $verbose, $mode ) + +=item mkpath( $dir1, $dir2,..., \%opt ) + +The C function provide the legacy interface of +C with a different interpretation of the arguments +passed. The behaviour and return value of the function is otherwise +identical to C. + +=item remove_tree( $dir1, $dir2, .... ) + +=item remove_tree( $dir1, $dir2, ...., \%opts ) + +The C function deletes the given directories and any +files and subdirectories they might contain, much like the Unix +command C or the Windows commands C and C. + +The function accepts a list of directories to be removed. (In point of fact, +it will also accept filesystem entries which are not directories, such as +regular files and symlinks. But, as its name suggests, its intent is to +remove trees rather than individual files.) + +C's behaviour may be tuned by an optional hashref +appearing as the last parameter on the call. If an empty string is +passed to C, an error will occur. + +B For security reasons, we strongly advise use of the +hashref-as-final-argument syntax -- specifically, with a setting of the C +element to a true value. + + remove_tree( $dir1, $dir2, ...., + { + safe => 1, + ... # other key-value pairs + }, + ); + +The function returns the number of files successfully deleted. + +The following keys are recognised in the option hash: + +=over + +=item verbose => $bool + +If present, will cause C to print the name of each file as +it is unlinked. By default nothing is printed. + +=item safe => $bool + +When set to a true value, will cause C to skip the files +for which the process lacks the required privileges needed to delete +files, such as delete privileges on VMS. In other words, the code +will make no attempt to alter file permissions. Thus, if the process +is interrupted, no filesystem object will be left in a more +permissive mode. + +=item keep_root => $bool + +When set to a true value, will cause all files and subdirectories +to be removed, except the initially specified directories. This comes +in handy when cleaning out an application's scratch directory. + + remove_tree( '/tmp', {keep_root => 1} ); + +=item result => \$res + +If present, it should be a reference to a scalar. +This scalar will be made to reference an array, which will +be used to store all files and directories unlinked +during the call. If nothing is unlinked, the array will be empty. + + remove_tree( '/tmp', {result => \my $list} ); + print "unlinked $_\n" for @$list; + +This is a useful alternative to the C key. + +=item error => \$err + +If present, it should be a reference to a scalar. +This scalar will be made to reference an array, which will +be used to store any errors that are encountered. See the L section for more information. + +Removing things is a much more dangerous proposition than +creating things. As such, there are certain conditions that +C may encounter that are so dangerous that the only +sane action left is to kill the program. + +Use C to trap all that is reasonable (problems with +permissions and the like), and let it die if things get out +of hand. This is the safest course of action. + +=back + +=item rmtree( $dir ) + +=item rmtree( $dir, $verbose, $safe ) + +=item rmtree( [$dir1, $dir2,...], $verbose, $safe ) + +=item rmtree( $dir1, $dir2,..., \%opt ) + +The C function provide the legacy interface of +C with a different interpretation of the arguments +passed. The behaviour and return value of the function is otherwise +identical to C. + +B For security reasons, we strongly advise use of the +hashref-as-final-argument syntax, specifically with a setting of the C +element to a true value. + + rmtree( $dir1, $dir2, ...., + { + safe => 1, + ... # other key-value pairs + }, + ); + +=back + +=head2 ERROR HANDLING + +=over 4 + +=item B + +The following error handling mechanism is consistent throughout all +code paths EXCEPT in cases where the ROOT node is nonexistent. In +version 2.11 the maintainers attempted to rectify this inconsistency +but too many downstream modules encountered problems. In such case, +if you require root node evaluation or error checking prior to calling +C or C, you should take additional precautions. + +=back + +If C or C encounters an error, a diagnostic +message will be printed to C via C (for non-fatal +errors) or via C (for fatal errors). + +If this behaviour is not desirable, the C attribute may be +used to hold a reference to a variable, which will be used to store +the diagnostics. The variable is made a reference to an array of hash +references. Each hash contain a single key/value pair where the key +is the name of the file, and the value is the error message (including +the contents of C<$!> when appropriate). If a general error is +encountered the diagnostic key will be empty. + +An example usage looks like: + + remove_tree( 'foo/bar', 'bar/rat', {error => \my $err} ); + if ($err && @$err) { + for my $diag (@$err) { + my ($file, $message) = %$diag; + if ($file eq '') { + print "general error: $message\n"; + } + else { + print "problem unlinking $file: $message\n"; + } + } + } + else { + print "No error encountered\n"; + } + +Note that if no errors are encountered, C<$err> will reference an +empty array. This means that C<$err> will always end up TRUE; so you +need to test C<@$err> to determine if errors occurred. + +=head2 NOTES + +C blindly exports C and C into the +current namespace. These days, this is considered bad style, but +to change it now would break too much code. Nonetheless, you are +invited to specify what it is you are expecting to use: + + use File::Path 'rmtree'; + +The routines C and C are B exported +by default. You must specify which ones you want to use. + + use File::Path 'remove_tree'; + +Note that a side-effect of the above is that C and C +are no longer exported at all. This is due to the way the C +module works. If you are migrating a codebase to use the new +interface, you will have to list everything explicitly. But that's +just good practice anyway. + + use File::Path qw(remove_tree rmtree); + +=head3 API CHANGES + +The API was changed in the 2.0 branch. For a time, C and +C tried, unsuccessfully, to deal with the two different +calling mechanisms. This approach was considered a failure. + +The new semantics are now only available with C and +C. The old semantics are only available through +C and C. Users are strongly encouraged to upgrade +to at least 2.08 in order to avoid surprises. + +=head3 SECURITY CONSIDERATIONS + +There were race conditions in the 1.x implementations of File::Path's +C function (although sometimes patched depending on the OS +distribution or platform). The 2.0 version contains code to avoid the +problem mentioned in CVE-2002-0435. + +See the following pages for more information: + + http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=286905 + http://www.nntp.perl.org/group/perl.perl5.porters/2005/01/msg97623.html + http://www.debian.org/security/2005/dsa-696 + +Additionally, unless the C parameter is set (or the +third parameter in the traditional interface is TRUE), should a +C be interrupted, files that were originally in read-only +mode may now have their permissions set to a read-write (or "delete +OK") mode. + +The following CVE reports were previously filed against File-Path and are +believed to have been addressed: + +=over 4 + +=item * L + +=item * L + +=back + +In February 2017 the cPanel Security Team reported an additional vulnerability +in File-Path. The C logic to make directories traversable can be +abused to set the mode on an attacker-chosen file to an attacker-chosen value. +This is due to the time-of-check-to-time-of-use (TOCTTOU) race condition +(L) between the +C that decides the inode is a directory and the C that tries +to make it user-rwx. CPAN versions 2.13 and later incorporate a patch +provided by John Lightsey to address this problem. This vulnerability has +been reported as CVE-2017-6512. + +=head1 DIAGNOSTICS + +FATAL errors will cause the program to halt (C), since the +problem is so severe that it would be dangerous to continue. (This +can always be trapped with C, but it's not a good idea. Under +the circumstances, dying is the best thing to do). + +SEVERE errors may be trapped using the modern interface. If the +they are not trapped, or if the old interface is used, such an error +will cause the program will halt. + +All other errors may be trapped using the modern interface, otherwise +they will be Ced about. Program execution will not be halted. + +=over 4 + +=item mkdir [path]: [errmsg] (SEVERE) + +C was unable to create the path. Probably some sort of +permissions error at the point of departure or insufficient resources +(such as free inodes on Unix). + +=item No root path(s) specified + +C was not given any paths to create. This message is only +emitted if the routine is called with the traditional interface. +The modern interface will remain silent if given nothing to do. + +=item No such file or directory + +On Windows, if C gives you this warning, it may mean that +you have exceeded your filesystem's maximum path length. + +=item cannot fetch initial working directory: [errmsg] + +C attempted to determine the initial directory by calling +C, but the call failed for some reason. No attempt +will be made to delete anything. + +=item cannot stat initial working directory: [errmsg] + +C attempted to stat the initial directory (after having +successfully obtained its name via C), however, the call +failed for some reason. No attempt will be made to delete anything. + +=item cannot chdir to [dir]: [errmsg] + +C attempted to set the working directory in order to +begin deleting the objects therein, but was unsuccessful. This is +usually a permissions issue. The routine will continue to delete +other things, but this directory will be left intact. + +=item directory [dir] changed before chdir, expected dev=[n] ino=[n], actual dev=[n] ino=[n], aborting. (FATAL) + +C recorded the device and inode of a directory, and then +moved into it. It then performed a C on the current directory +and detected that the device and inode were no longer the same. As +this is at the heart of the race condition problem, the program +will die at this point. + +=item cannot make directory [dir] read+writeable: [errmsg] + +C attempted to change the permissions on the current directory +to ensure that subsequent unlinkings would not run into problems, +but was unable to do so. The permissions remain as they were, and +the program will carry on, doing the best it can. + +=item cannot read [dir]: [errmsg] + +C tried to read the contents of the directory in order +to acquire the names of the directory entries to be unlinked, but +was unsuccessful. This is usually a permissions issue. The +program will continue, but the files in this directory will remain +after the call. + +=item cannot reset chmod [dir]: [errmsg] + +C, after having deleted everything in a directory, attempted +to restore its permissions to the original state but failed. The +directory may wind up being left behind. + +=item cannot remove [dir] when cwd is [dir] + +The current working directory of the program is F +and you are attempting to remove an ancestor, such as F. +The directory tree is left untouched. + +The solution is to C out of the child directory to a place +outside the directory tree to be removed. + +=item cannot chdir to [parent-dir] from [child-dir]: [errmsg], aborting. (FATAL) + +C, after having deleted everything and restored the permissions +of a directory, was unable to chdir back to the parent. The program +halts to avoid a race condition from occurring. + +=item cannot stat prior working directory [dir]: [errmsg], aborting. (FATAL) + +C was unable to stat the parent directory after having returned +from the child. Since there is no way of knowing if we returned to +where we think we should be (by comparing device and inode) the only +way out is to C. + +=item previous directory [parent-dir] changed before entering [child-dir], expected dev=[n] ino=[n], actual dev=[n] ino=[n], aborting. (FATAL) + +When C returned from deleting files in a child directory, a +check revealed that the parent directory it returned to wasn't the one +it started out from. This is considered a sign of malicious activity. + +=item cannot make directory [dir] writeable: [errmsg] + +Just before removing a directory (after having successfully removed +everything it contained), C attempted to set the permissions +on the directory to ensure it could be removed and failed. Program +execution continues, but the directory may possibly not be deleted. + +=item cannot remove directory [dir]: [errmsg] + +C attempted to remove a directory, but failed. This may be because +some objects that were unable to be removed remain in the directory, or +it could be a permissions issue. The directory will be left behind. + +=item cannot restore permissions of [dir] to [0nnn]: [errmsg] + +After having failed to remove a directory, C was unable to +restore its permissions from a permissive state back to a possibly +more restrictive setting. (Permissions given in octal). + +=item cannot make file [file] writeable: [errmsg] + +C attempted to force the permissions of a file to ensure it +could be deleted, but failed to do so. It will, however, still attempt +to unlink the file. + +=item cannot unlink file [file]: [errmsg] + +C failed to remove a file. Probably a permissions issue. + +=item cannot restore permissions of [file] to [0nnn]: [errmsg] + +After having failed to remove a file, C was also unable +to restore the permissions on the file to a possibly less permissive +setting. (Permissions given in octal). + +=item unable to map [owner] to a uid, ownership not changed"); + +C was instructed to give the ownership of created +directories to the symbolic name [owner], but C did +not return the corresponding numeric uid. The directory will +be created, but ownership will not be changed. + +=item unable to map [group] to a gid, group ownership not changed + +C was instructed to give the group ownership of created +directories to the symbolic name [group], but C did +not return the corresponding numeric gid. The directory will +be created, but group ownership will not be changed. + +=back + +=head1 SEE ALSO + +=over 4 + +=item * + +L + +Allows files and directories to be moved to the Trashcan/Recycle +Bin (where they may later be restored if necessary) if the operating +system supports such functionality. This feature may one day be +made available directly in C. + +=item * + +L + +When removing directory trees, if you want to examine each file to +decide whether to delete it (and possibly leaving large swathes +alone), F offers a convenient and flexible approach +to examining directory trees. + +=back + +=head1 BUGS AND LIMITATIONS + +The following describes F limitations and how to report bugs. + +=head2 MULTITHREADED APPLICATIONS + +F C and C will not work with +multithreaded applications due to its use of C. At this time, +no warning or error is generated in this situation. You will +certainly encounter unexpected results. + +The implementation that surfaces this limitation will not be changed. See the +F module for functionality similar to F but which does +not C. + +=head2 NFS Mount Points + +F is not responsible for triggering the automounts, mirror mounts, +and the contents of network mounted filesystems. If your NFS implementation +requires an action to be performed on the filesystem in order for +F to perform operations, it is strongly suggested you assure +filesystem availability by reading the root of the mounted filesystem. + +=head2 REPORTING BUGS + +Please report all bugs on the RT queue, either via the web interface: + +L + +or by email: + + bug-File-Path@rt.cpan.org + +In either case, please B patches to the bug report rather than +including them inline in the web post or the body of the email. + +You can also send pull requests to the Github repository: + +L + +=head1 ACKNOWLEDGEMENTS + +Paul Szabo identified the race condition originally, and Brendan +O'Dea wrote an implementation for Debian that addressed the problem. +That code was used as a basis for the current code. Their efforts +are greatly appreciated. + +Gisle Aas made a number of improvements to the documentation for +2.07 and his advice and assistance is also greatly appreciated. + +=head1 AUTHORS + +Prior authors and maintainers: Tim Bunce, Charles Bailey, and +David Landgren >. + +Current maintainers are Richard Elberger > and +James (Jim) Keenan >. + +=head1 CONTRIBUTORS + +Contributors to File::Path, in alphabetical order by first name. + +=over 1 + +=item > + +=item Charlie Gonzalez > + +=item Craig A. Berry > + +=item James E Keenan > + +=item John Lightsey > + +=item Nigel Horne > + +=item Richard Elberger > + +=item Ryan Yee > + +=item Skye Shaw > + +=item Tom Lutz > + +=item Will Sheppard > + +=back + +=head1 COPYRIGHT + +This module is copyright (C) Charles Bailey, Tim Bunce, David Landgren, +James Keenan and Richard Elberger 1995-2020. All rights reserved. + +=head1 LICENSE + +This library is free software; you can redistribute it and/or modify +it under the same terms as Perl itself. + +=cut diff --git a/git/usr/share/perl5/core_perl/File/Temp.pm b/git/usr/share/perl5/core_perl/File/Temp.pm new file mode 100644 index 0000000000000000000000000000000000000000..570f25a5619eda68f38c3865a06475153b56ec95 --- /dev/null +++ b/git/usr/share/perl5/core_perl/File/Temp.pm @@ -0,0 +1,3721 @@ +package File::Temp; # git description: v0.2310-3-gc7148fe +# ABSTRACT: return name and handle of a temporary file safely + +our $VERSION = '0.2311'; + +#pod =begin :__INTERNALS +#pod +#pod =head1 PORTABILITY +#pod +#pod This section is at the top in order to provide easier access to +#pod porters. It is not expected to be rendered by a standard pod +#pod formatting tool. Please skip straight to the SYNOPSIS section if you +#pod are not trying to port this module to a new platform. +#pod +#pod This module is designed to be portable across operating systems and it +#pod currently supports Unix, VMS, DOS, OS/2, Windows and Mac OS +#pod (Classic). When porting to a new OS there are generally three main +#pod issues that have to be solved: +#pod +#pod =over 4 +#pod +#pod =item * +#pod +#pod Can the OS unlink an open file? If it can not then the +#pod C<_can_unlink_opened_file> method should be modified. +#pod +#pod =item * +#pod +#pod Are the return values from C reliable? By default all the +#pod return values from C are compared when unlinking a temporary +#pod file using the filename and the handle. Operating systems other than +#pod unix do not always have valid entries in all fields. If utility function +#pod C fails then the C comparison should be +#pod modified accordingly. +#pod +#pod =item * +#pod +#pod Security. Systems that can not support a test for the sticky bit +#pod on a directory can not use the MEDIUM and HIGH security tests. +#pod The C<_can_do_level> method should be modified accordingly. +#pod +#pod =back +#pod +#pod =end :__INTERNALS +#pod +#pod =head1 SYNOPSIS +#pod +#pod use File::Temp qw/ tempfile tempdir /; +#pod +#pod $fh = tempfile(); +#pod ($fh, $filename) = tempfile(); +#pod +#pod ($fh, $filename) = tempfile( $template, DIR => $dir); +#pod ($fh, $filename) = tempfile( $template, SUFFIX => '.dat'); +#pod ($fh, $filename) = tempfile( $template, TMPDIR => 1 ); +#pod +#pod binmode( $fh, ":utf8" ); +#pod +#pod $dir = tempdir( CLEANUP => 1 ); +#pod ($fh, $filename) = tempfile( DIR => $dir ); +#pod +#pod Object interface: +#pod +#pod require File::Temp; +#pod use File::Temp (); +#pod use File::Temp qw/ :seekable /; +#pod +#pod $fh = File::Temp->new(); +#pod $fname = $fh->filename; +#pod +#pod $fh = File::Temp->new(TEMPLATE => $template); +#pod $fname = $fh->filename; +#pod +#pod $tmp = File::Temp->new( UNLINK => 0, SUFFIX => '.dat' ); +#pod print $tmp "Some data\n"; +#pod print "Filename is $tmp\n"; +#pod $tmp->seek( 0, SEEK_END ); +#pod +#pod $dir = File::Temp->newdir(); # CLEANUP => 1 by default +#pod +#pod The following interfaces are provided for compatibility with +#pod existing APIs. They should not be used in new code. +#pod +#pod MkTemp family: +#pod +#pod use File::Temp qw/ :mktemp /; +#pod +#pod ($fh, $file) = mkstemp( "tmpfileXXXXX" ); +#pod ($fh, $file) = mkstemps( "tmpfileXXXXXX", $suffix); +#pod +#pod $tmpdir = mkdtemp( $template ); +#pod +#pod $unopened_file = mktemp( $template ); +#pod +#pod POSIX functions: +#pod +#pod use File::Temp qw/ :POSIX /; +#pod +#pod $file = tmpnam(); +#pod $fh = tmpfile(); +#pod +#pod ($fh, $file) = tmpnam(); +#pod +#pod Compatibility functions: +#pod +#pod $unopened_file = File::Temp::tempnam( $dir, $pfx ); +#pod +#pod =head1 DESCRIPTION +#pod +#pod C can be used to create and open temporary files in a safe +#pod way. There is both a function interface and an object-oriented +#pod interface. The File::Temp constructor or the tempfile() function can +#pod be used to return the name and the open filehandle of a temporary +#pod file. The tempdir() function can be used to create a temporary +#pod directory. +#pod +#pod The security aspect of temporary file creation is emphasized such that +#pod a filehandle and filename are returned together. This helps guarantee +#pod that a race condition can not occur where the temporary file is +#pod created by another process between checking for the existence of the +#pod file and its opening. Additional security levels are provided to +#pod check, for example, that the sticky bit is set on world writable +#pod directories. See L<"safe_level"> for more information. +#pod +#pod For compatibility with popular C library functions, Perl implementations of +#pod the mkstemp() family of functions are provided. These are, mkstemp(), +#pod mkstemps(), mkdtemp() and mktemp(). +#pod +#pod Additionally, implementations of the standard L +#pod tmpnam() and tmpfile() functions are provided if required. +#pod +#pod Implementations of mktemp(), tmpnam(), and tempnam() are provided, +#pod but should be used with caution since they return only a filename +#pod that was valid when function was called, so cannot guarantee +#pod that the file will not exist by the time the caller opens the filename. +#pod +#pod Filehandles returned by these functions support the seekable methods. +#pod +#pod =cut + +# Toolchain targets v5.8.1, but we'll try to support back to v5.6 anyway. +# It might be possible to make this v5.5, but many v5.6isms are creeping +# into the code and tests. +use 5.006; +use strict; +use Carp; +use File::Spec 0.8; +use Cwd (); +use File::Path 2.06 qw/ rmtree /; +use Fcntl 1.03; +use IO::Seekable; # For SEEK_* +use Errno; +use Scalar::Util 'refaddr'; +require VMS::Stdio if $^O eq 'VMS'; + +# pre-emptively load Carp::Heavy. If we don't when we run out of file +# handles and attempt to call croak() we get an error message telling +# us that Carp::Heavy won't load rather than an error telling us we +# have run out of file handles. We either preload croak() or we +# switch the calls to croak from _gettemp() to use die. +eval { require Carp::Heavy; }; + +# Need the Symbol package if we are running older perl +require Symbol if $] < 5.006; + +### For the OO interface +use parent 0.221 qw/ IO::Handle IO::Seekable /; +use overload '""' => "STRINGIFY", '0+' => "NUMIFY", + fallback => 1; + +our $DEBUG = 0; +our $KEEP_ALL = 0; + +# We are exporting functions + +use Exporter 5.57 'import'; # 5.57 lets us import 'import' + +# Export list - to allow fine tuning of export table + +our @EXPORT_OK = qw{ + tempfile + tempdir + tmpnam + tmpfile + mktemp + mkstemp + mkstemps + mkdtemp + unlink0 + cleanup + SEEK_SET + SEEK_CUR + SEEK_END + }; + +# Groups of functions for export + +our %EXPORT_TAGS = ( + 'POSIX' => [qw/ tmpnam tmpfile /], + 'mktemp' => [qw/ mktemp mkstemp mkstemps mkdtemp/], + 'seekable' => [qw/ SEEK_SET SEEK_CUR SEEK_END /], + ); + +# add contents of these tags to @EXPORT +Exporter::export_tags('POSIX','mktemp','seekable'); + +# This is a list of characters that can be used in random filenames + +my @CHARS = (qw/ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z + a b c d e f g h i j k l m n o p q r s t u v w x y z + 0 1 2 3 4 5 6 7 8 9 _ + /); + +# Maximum number of tries to make a temp file before failing + +use constant MAX_TRIES => 1000; + +# Minimum number of X characters that should be in a template +use constant MINX => 4; + +# Default template when no template supplied + +use constant TEMPXXX => 'X' x 10; + +# Constants for the security level + +use constant STANDARD => 0; +use constant MEDIUM => 1; +use constant HIGH => 2; + +# OPENFLAGS. If we defined the flag to use with Sysopen here this gives +# us an optimisation when many temporary files are requested + +my $OPENFLAGS = O_CREAT | O_EXCL | O_RDWR; +my $LOCKFLAG; + +unless ($^O eq 'MacOS') { + for my $oflag (qw/ NOFOLLOW BINARY LARGEFILE NOINHERIT /) { + my ($bit, $func) = (0, "Fcntl::O_" . $oflag); + no strict 'refs'; + $OPENFLAGS |= $bit if eval { + # Make sure that redefined die handlers do not cause problems + # e.g. CGI::Carp + local $SIG{__DIE__} = sub {}; + local $SIG{__WARN__} = sub {}; + $bit = &$func(); + 1; + }; + } + # Special case O_EXLOCK + $LOCKFLAG = eval { + local $SIG{__DIE__} = sub {}; + local $SIG{__WARN__} = sub {}; + &Fcntl::O_EXLOCK(); + }; +} + +# On some systems the O_TEMPORARY flag can be used to tell the OS +# to automatically remove the file when it is closed. This is fine +# in most cases but not if tempfile is called with UNLINK=>0 and +# the filename is requested -- in the case where the filename is to +# be passed to another routine. This happens on windows. We overcome +# this by using a second open flags variable + +my $OPENTEMPFLAGS = $OPENFLAGS; +unless ($^O eq 'MacOS') { + for my $oflag (qw/ TEMPORARY /) { + my ($bit, $func) = (0, "Fcntl::O_" . $oflag); + local($@); + no strict 'refs'; + $OPENTEMPFLAGS |= $bit if eval { + # Make sure that redefined die handlers do not cause problems + # e.g. CGI::Carp + local $SIG{__DIE__} = sub {}; + local $SIG{__WARN__} = sub {}; + $bit = &$func(); + 1; + }; + } +} + +# Private hash tracking which files have been created by each process id via the OO interface +my %FILES_CREATED_BY_OBJECT; + +# INTERNAL ROUTINES - not to be used outside of package + +# Generic routine for getting a temporary filename +# modelled on OpenBSD _gettemp() in mktemp.c + +# The template must contain X's that are to be replaced +# with the random values + +# Arguments: + +# TEMPLATE - string containing the XXXXX's that is converted +# to a random filename and opened if required + +# Optionally, a hash can also be supplied containing specific options +# "open" => if true open the temp file, else just return the name +# default is 0 +# "mkdir"=> if true, we are creating a temp directory rather than tempfile +# default is 0 +# "suffixlen" => number of characters at end of PATH to be ignored. +# default is 0. +# "unlink_on_close" => indicates that, if possible, the OS should remove +# the file as soon as it is closed. Usually indicates +# use of the O_TEMPORARY flag to sysopen. +# Usually irrelevant on unix +# "use_exlock" => Indicates that O_EXLOCK should be used. Default is false. +# "file_permissions" => file permissions for sysopen(). Default is 0600. + +# Optionally a reference to a scalar can be passed into the function +# On error this will be used to store the reason for the error +# "ErrStr" => \$errstr + +# "open" and "mkdir" can not both be true +# "unlink_on_close" is not used when "mkdir" is true. + +# The default options are equivalent to mktemp(). + +# Returns: +# filehandle - open file handle (if called with doopen=1, else undef) +# temp name - name of the temp file or directory + +# For example: +# ($fh, $name) = _gettemp($template, "open" => 1); + +# for the current version, failures are associated with +# stored in an error string and returned to give the reason whilst debugging +# This routine is not called by any external function +sub _gettemp { + + croak 'Usage: ($fh, $name) = _gettemp($template, OPTIONS);' + unless scalar(@_) >= 1; + + # the internal error string - expect it to be overridden + # Need this in case the caller decides not to supply us a value + # need an anonymous scalar + my $tempErrStr; + + # Default options + my %options = ( + "open" => 0, + "mkdir" => 0, + "suffixlen" => 0, + "unlink_on_close" => 0, + "use_exlock" => 0, + "ErrStr" => \$tempErrStr, + "file_permissions" => undef, + ); + + # Read the template + my $template = shift; + if (ref($template)) { + # Use a warning here since we have not yet merged ErrStr + carp "File::Temp::_gettemp: template must not be a reference"; + return (); + } + + # Check that the number of entries on stack are even + if (scalar(@_) % 2 != 0) { + # Use a warning here since we have not yet merged ErrStr + carp "File::Temp::_gettemp: Must have even number of options"; + return (); + } + + # Read the options and merge with defaults + %options = (%options, @_) if @_; + + # Make sure the error string is set to undef + ${$options{ErrStr}} = undef; + + # Can not open the file and make a directory in a single call + if ($options{"open"} && $options{"mkdir"}) { + ${$options{ErrStr}} = "doopen and domkdir can not both be true\n"; + return (); + } + + # Find the start of the end of the Xs (position of last X) + # Substr starts from 0 + my $start = length($template) - 1 - $options{"suffixlen"}; + + # Check that we have at least MINX x X (e.g. 'XXXX") at the end of the string + # (taking suffixlen into account). Any fewer is insecure. + + # Do it using substr - no reason to use a pattern match since + # we know where we are looking and what we are looking for + + if (substr($template, $start - MINX + 1, MINX) ne 'X' x MINX) { + ${$options{ErrStr}} = "The template must end with at least ". + MINX . " 'X' characters\n"; + return (); + } + + # Replace all the X at the end of the substring with a + # random character or just all the XX at the end of a full string. + # Do it as an if, since the suffix adjusts which section to replace + # and suffixlen=0 returns nothing if used in the substr directly + # and generate a full path from the template + + my $path = _replace_XX($template, $options{"suffixlen"}); + + + # Split the path into constituent parts - eventually we need to check + # whether the directory exists + # We need to know whether we are making a temp directory + # or a tempfile + + my ($volume, $directories, $file); + my $parent; # parent directory + if ($options{"mkdir"}) { + # There is no filename at the end + ($volume, $directories, $file) = File::Spec->splitpath( $path, 1); + + # The parent is then $directories without the last directory + # Split the directory and put it back together again + my @dirs = File::Spec->splitdir($directories); + + # If @dirs only has one entry (i.e. the directory template) that means + # we are in the current directory + if ($#dirs == 0) { + $parent = File::Spec->curdir; + } else { + + if ($^O eq 'VMS') { # need volume to avoid relative dir spec + $parent = File::Spec->catdir($volume, @dirs[0..$#dirs-1]); + $parent = 'sys$disk:[]' if $parent eq ''; + } else { + + # Put it back together without the last one + $parent = File::Spec->catdir(@dirs[0..$#dirs-1]); + + # ...and attach the volume (no filename) + $parent = File::Spec->catpath($volume, $parent, ''); + } + + } + + } else { + + # Get rid of the last filename (use File::Basename for this?) + ($volume, $directories, $file) = File::Spec->splitpath( $path ); + + # Join up without the file part + $parent = File::Spec->catpath($volume,$directories,''); + + # If $parent is empty replace with curdir + $parent = File::Spec->curdir + unless $directories ne ''; + + } + + # Check that the parent directories exist + # Do this even for the case where we are simply returning a name + # not a file -- no point returning a name that includes a directory + # that does not exist or is not writable + + unless (-e $parent) { + ${$options{ErrStr}} = "Parent directory ($parent) does not exist"; + return (); + } + unless (-d $parent) { + ${$options{ErrStr}} = "Parent directory ($parent) is not a directory"; + return (); + } + + # Check the stickiness of the directory and chown giveaway if required + # If the directory is world writable the sticky bit + # must be set + + if (File::Temp->safe_level == MEDIUM) { + my $safeerr; + unless (_is_safe($parent,\$safeerr)) { + ${$options{ErrStr}} = "Parent directory ($parent) is not safe ($safeerr)"; + return (); + } + } elsif (File::Temp->safe_level == HIGH) { + my $safeerr; + unless (_is_verysafe($parent, \$safeerr)) { + ${$options{ErrStr}} = "Parent directory ($parent) is not safe ($safeerr)"; + return (); + } + } + + my $perms = $options{file_permissions}; + my $has_perms = defined $perms; + $perms = 0600 unless $has_perms; + + # Now try MAX_TRIES time to open the file + for (my $i = 0; $i < MAX_TRIES; $i++) { + + # Try to open the file if requested + if ($options{"open"}) { + my $fh; + + # If we are running before perl5.6.0 we can not auto-vivify + if ($] < 5.006) { + $fh = &Symbol::gensym; + } + + # Try to make sure this will be marked close-on-exec + # XXX: Win32 doesn't respect this, nor the proper fcntl, + # but may have O_NOINHERIT. This may or may not be in Fcntl. + local $^F = 2; + + # Attempt to open the file + my $open_success = undef; + if ( $^O eq 'VMS' and $options{"unlink_on_close"} && !$KEEP_ALL) { + # make it auto delete on close by setting FAB$V_DLT bit + $fh = VMS::Stdio::vmssysopen($path, $OPENFLAGS, $perms, 'fop=dlt'); + $open_success = $fh; + } else { + my $flags = ( ($options{"unlink_on_close"} && !$KEEP_ALL) ? + $OPENTEMPFLAGS : + $OPENFLAGS ); + $flags |= $LOCKFLAG if (defined $LOCKFLAG && $options{use_exlock}); + $open_success = sysopen($fh, $path, $flags, $perms); + } + if ( $open_success ) { + + # in case of odd umask force rw + chmod($perms, $path) unless $has_perms; + + # Opened successfully - return file handle and name + return ($fh, $path); + + } else { + + # Error opening file - abort with error + # if the reason was anything but EEXIST + unless ($!{EEXIST}) { + ${$options{ErrStr}} = "Could not create temp file $path: $!"; + return (); + } + + # Loop round for another try + + } + } elsif ($options{"mkdir"}) { + + # Open the temp directory + if (mkdir( $path, 0700)) { + # in case of odd umask + chmod(0700, $path); + + return undef, $path; + } else { + + # Abort with error if the reason for failure was anything + # except EEXIST + unless ($!{EEXIST}) { + ${$options{ErrStr}} = "Could not create directory $path: $!"; + return (); + } + + # Loop round for another try + + } + + } else { + + # Return true if the file can not be found + # Directory has been checked previously + + return (undef, $path) unless -e $path; + + # Try again until MAX_TRIES + + } + + # Did not successfully open the tempfile/dir + # so try again with a different set of random letters + # No point in trying to increment unless we have only + # 1 X say and the randomness could come up with the same + # file MAX_TRIES in a row. + + # Store current attempt - in principle this implies that the + # 3rd time around the open attempt that the first temp file + # name could be generated again. Probably should store each + # attempt and make sure that none are repeated + + my $original = $path; + my $counter = 0; # Stop infinite loop + my $MAX_GUESS = 50; + + do { + + # Generate new name from original template + $path = _replace_XX($template, $options{"suffixlen"}); + + $counter++; + + } until ($path ne $original || $counter > $MAX_GUESS); + + # Check for out of control looping + if ($counter > $MAX_GUESS) { + ${$options{ErrStr}} = "Tried to get a new temp name different to the previous value $MAX_GUESS times.\nSomething wrong with template?? ($template)"; + return (); + } + + } + + # If we get here, we have run out of tries + ${ $options{ErrStr} } = "Have exceeded the maximum number of attempts (" + . MAX_TRIES . ") to open temp file/dir"; + + return (); + +} + +# Internal routine to replace the XXXX... with random characters +# This has to be done by _gettemp() every time it fails to +# open a temp file/dir + +# Arguments: $template (the template with XXX), +# $ignore (number of characters at end to ignore) + +# Returns: modified template + +sub _replace_XX { + + croak 'Usage: _replace_XX($template, $ignore)' + unless scalar(@_) == 2; + + my ($path, $ignore) = @_; + + # Do it as an if, since the suffix adjusts which section to replace + # and suffixlen=0 returns nothing if used in the substr directly + # Alternatively, could simply set $ignore to length($path)-1 + # Don't want to always use substr when not required though. + my $end = ( $] >= 5.006 ? "\\z" : "\\Z" ); + + if ($ignore) { + substr($path, 0, - $ignore) =~ s/X(?=X*$end)/$CHARS[ int( rand( @CHARS ) ) ]/ge; + } else { + $path =~ s/X(?=X*$end)/$CHARS[ int( rand( @CHARS ) ) ]/ge; + } + return $path; +} + +# Internal routine to force a temp file to be writable after +# it is created so that we can unlink it. Windows seems to occasionally +# force a file to be readonly when written to certain temp locations +sub _force_writable { + my $file = shift; + chmod 0600, $file; +} + + +# internal routine to check to see if the directory is safe +# First checks to see if the directory is not owned by the +# current user or root. Then checks to see if anyone else +# can write to the directory and if so, checks to see if +# it has the sticky bit set + +# Will not work on systems that do not support sticky bit + +#Args: directory path to check +# Optionally: reference to scalar to contain error message +# Returns true if the path is safe and false otherwise. +# Returns undef if can not even run stat() on the path + +# This routine based on version written by Tom Christiansen + +# Presumably, by the time we actually attempt to create the +# file or directory in this directory, it may not be safe +# anymore... Have to run _is_safe directly after the open. + +sub _is_safe { + + my $path = shift; + my $err_ref = shift; + + # Stat path + my @info = stat($path); + unless (scalar(@info)) { + $$err_ref = "stat(path) returned no values"; + return 0; + } + ; + return 1 if $^O eq 'VMS'; # owner delete control at file level + + # Check to see whether owner is neither superuser (or a system uid) nor me + # Use the effective uid from the $> variable + # UID is in [4] + if ($info[4] > File::Temp->top_system_uid() && $info[4] != $>) { + + Carp::cluck(sprintf "uid=$info[4] topuid=%s euid=$> path='$path'", + File::Temp->top_system_uid()); + + $$err_ref = "Directory owned neither by root nor the current user" + if ref($err_ref); + return 0; + } + + # check whether group or other can write file + # use 066 to detect either reading or writing + # use 022 to check writability + # Do it with S_IWOTH and S_IWGRP for portability (maybe) + # mode is in info[2] + if (($info[2] & &Fcntl::S_IWGRP) || # Is group writable? + ($info[2] & &Fcntl::S_IWOTH) ) { # Is world writable? + # Must be a directory + unless (-d $path) { + $$err_ref = "Path ($path) is not a directory" + if ref($err_ref); + return 0; + } + # Must have sticky bit set + unless (-k $path) { + $$err_ref = "Sticky bit not set on $path when dir is group|world writable" + if ref($err_ref); + return 0; + } + } + + return 1; +} + +# Internal routine to check whether a directory is safe +# for temp files. Safer than _is_safe since it checks for +# the possibility of chown giveaway and if that is a possibility +# checks each directory in the path to see if it is safe (with _is_safe) + +# If _PC_CHOWN_RESTRICTED is not set, does the full test of each +# directory anyway. + +# Takes optional second arg as scalar ref to error reason + +sub _is_verysafe { + + # Need POSIX - but only want to bother if really necessary due to overhead + require POSIX; + + my $path = shift; + print "_is_verysafe testing $path\n" if $DEBUG; + return 1 if $^O eq 'VMS'; # owner delete control at file level + + my $err_ref = shift; + + # Should Get the value of _PC_CHOWN_RESTRICTED if it is defined + # and If it is not there do the extensive test + local($@); + my $chown_restricted; + $chown_restricted = &POSIX::_PC_CHOWN_RESTRICTED() + if eval { &POSIX::_PC_CHOWN_RESTRICTED(); 1}; + + # If chown_resticted is set to some value we should test it + if (defined $chown_restricted) { + + # Return if the current directory is safe + return _is_safe($path,$err_ref) if POSIX::sysconf( $chown_restricted ); + + } + + # To reach this point either, the _PC_CHOWN_RESTRICTED symbol + # was not available or the symbol was there but chown giveaway + # is allowed. Either way, we now have to test the entire tree for + # safety. + + # Convert path to an absolute directory if required + unless (File::Spec->file_name_is_absolute($path)) { + $path = File::Spec->rel2abs($path); + } + + # Split directory into components - assume no file + my ($volume, $directories, undef) = File::Spec->splitpath( $path, 1); + + # Slightly less efficient than having a function in File::Spec + # to chop off the end of a directory or even a function that + # can handle ../ in a directory tree + # Sometimes splitdir() returns a blank at the end + # so we will probably check the bottom directory twice in some cases + my @dirs = File::Spec->splitdir($directories); + + # Concatenate one less directory each time around + foreach my $pos (0.. $#dirs) { + # Get a directory name + my $dir = File::Spec->catpath($volume, + File::Spec->catdir(@dirs[0.. $#dirs - $pos]), + '' + ); + + print "TESTING DIR $dir\n" if $DEBUG; + + # Check the directory + return 0 unless _is_safe($dir,$err_ref); + + } + + return 1; +} + + + +# internal routine to determine whether unlink works on this +# platform for files that are currently open. +# Returns true if we can, false otherwise. + +# Currently WinNT, OS/2 and VMS can not unlink an opened file +# On VMS this is because the O_EXCL flag is used to open the +# temporary file. Currently I do not know enough about the issues +# on VMS to decide whether O_EXCL is a requirement. + +sub _can_unlink_opened_file { + + if (grep $^O eq $_, qw/MSWin32 os2 VMS dos MacOS haiku/) { + return 0; + } else { + return 1; + } + +} + +# internal routine to decide which security levels are allowed +# see safe_level() for more information on this + +# Controls whether the supplied security level is allowed + +# $cando = _can_do_level( $level ) + +sub _can_do_level { + + # Get security level + my $level = shift; + + # Always have to be able to do STANDARD + return 1 if $level == STANDARD; + + # Currently, the systems that can do HIGH or MEDIUM are identical + if ( $^O eq 'MSWin32' || $^O eq 'os2' || $^O eq 'cygwin' || $^O eq 'dos' || $^O eq 'MacOS' || $^O eq 'mpeix') { + return 0; + } else { + return 1; + } + +} + +# This routine sets up a deferred unlinking of a specified +# filename and filehandle. It is used in the following cases: +# - Called by unlink0 if an opened file can not be unlinked +# - Called by tempfile() if files are to be removed on shutdown +# - Called by tempdir() if directories are to be removed on shutdown + +# Arguments: +# _deferred_unlink( $fh, $fname, $isdir ); +# +# - filehandle (so that it can be explicitly closed if open +# - filename (the thing we want to remove) +# - isdir (flag to indicate that we are being given a directory) +# [and hence no filehandle] + +# Status is not referred to since all the magic is done with an END block + +{ + # Will set up two lexical variables to contain all the files to be + # removed. One array for files, another for directories They will + # only exist in this block. + + # This means we only have to set up a single END block to remove + # all files. + + # in order to prevent child processes inadvertently deleting the parent + # temp files we use a hash to store the temp files and directories + # created by a particular process id. + + # %files_to_unlink contains values that are references to an array of + # array references containing the filehandle and filename associated with + # the temp file. + my (%files_to_unlink, %dirs_to_unlink); + + # Set up an end block to use these arrays + END { + local($., $@, $!, $^E, $?); + cleanup(at_exit => 1); + } + + # Cleanup function. Always triggered on END (with at_exit => 1) but + # can be invoked manually. + sub cleanup { + my %h = @_; + my $at_exit = delete $h{at_exit}; + $at_exit = 0 if not defined $at_exit; + { my @k = sort keys %h; die "unrecognized parameters: @k" if @k } + + if (!$KEEP_ALL) { + # Files + my @files = (exists $files_to_unlink{$$} ? + @{ $files_to_unlink{$$} } : () ); + foreach my $file (@files) { + # close the filehandle without checking its state + # in order to make real sure that this is closed + # if its already closed then I don't care about the answer + # probably a better way to do this + close($file->[0]); # file handle is [0] + + if (-f $file->[1]) { # file name is [1] + _force_writable( $file->[1] ); # for windows + unlink $file->[1] or warn "Error removing ".$file->[1]; + } + } + # Dirs + my @dirs = (exists $dirs_to_unlink{$$} ? + @{ $dirs_to_unlink{$$} } : () ); + my ($cwd, $cwd_to_remove); + foreach my $dir (@dirs) { + if (-d $dir) { + # Some versions of rmtree will abort if you attempt to remove + # the directory you are sitting in. For automatic cleanup + # at program exit, we avoid this by chdir()ing out of the way + # first. If not at program exit, it's best not to mess with the + # current directory, so just let it fail with a warning. + if ($at_exit) { + $cwd = Cwd::abs_path(File::Spec->curdir) if not defined $cwd; + my $abs = Cwd::abs_path($dir); + if ($abs eq $cwd) { + $cwd_to_remove = $dir; + next; + } + } + eval { rmtree($dir, $DEBUG, 0); }; + warn $@ if ($@ && $^W); + } + } + + if (defined $cwd_to_remove) { + # We do need to clean up the current directory, and everything + # else is done, so get out of there and remove it. + chdir $cwd_to_remove or die "cannot chdir to $cwd_to_remove: $!"; + my $updir = File::Spec->updir; + chdir $updir or die "cannot chdir to $updir: $!"; + eval { rmtree($cwd_to_remove, $DEBUG, 0); }; + warn $@ if ($@ && $^W); + } + + # clear the arrays + @{ $files_to_unlink{$$} } = () + if exists $files_to_unlink{$$}; + @{ $dirs_to_unlink{$$} } = () + if exists $dirs_to_unlink{$$}; + } + } + + + # This is the sub called to register a file for deferred unlinking + # This could simply store the input parameters and defer everything + # until the END block. For now we do a bit of checking at this + # point in order to make sure that (1) we have a file/dir to delete + # and (2) we have been called with the correct arguments. + sub _deferred_unlink { + + croak 'Usage: _deferred_unlink($fh, $fname, $isdir)' + unless scalar(@_) == 3; + + my ($fh, $fname, $isdir) = @_; + + warn "Setting up deferred removal of $fname\n" + if $DEBUG; + + # make sure we save the absolute path for later cleanup + # OK to untaint because we only ever use this internally + # as a file path, never interpolating into the shell + $fname = Cwd::abs_path($fname); + ($fname) = $fname =~ /^(.*)$/; + + # If we have a directory, check that it is a directory + if ($isdir) { + + if (-d $fname) { + + # Directory exists so store it + # first on VMS turn []foo into [.foo] for rmtree + $fname = VMS::Filespec::vmspath($fname) if $^O eq 'VMS'; + $dirs_to_unlink{$$} = [] + unless exists $dirs_to_unlink{$$}; + push (@{ $dirs_to_unlink{$$} }, $fname); + + } else { + carp "Request to remove directory $fname could not be completed since it does not exist!\n" if $^W; + } + + } else { + + if (-f $fname) { + + # file exists so store handle and name for later removal + $files_to_unlink{$$} = [] + unless exists $files_to_unlink{$$}; + push(@{ $files_to_unlink{$$} }, [$fh, $fname]); + + } else { + carp "Request to remove file $fname could not be completed since it is not there!\n" if $^W; + } + + } + + } + + +} + +# normalize argument keys to upper case and do consistent handling +# of leading template vs TEMPLATE +sub _parse_args { + my $leading_template = (scalar(@_) % 2 == 1 ? shift(@_) : '' ); + my %args = @_; + %args = map +(uc($_) => $args{$_}), keys %args; + + # template (store it in an array so that it will + # disappear from the arg list of tempfile) + my @template = ( + exists $args{TEMPLATE} ? $args{TEMPLATE} : + $leading_template ? $leading_template : () + ); + delete $args{TEMPLATE}; + + return( \@template, \%args ); +} + +#pod =head1 OBJECT-ORIENTED INTERFACE +#pod +#pod This is the primary interface for interacting with +#pod C. Using the OO interface a temporary file can be created +#pod when the object is constructed and the file can be removed when the +#pod object is no longer required. +#pod +#pod Note that there is no method to obtain the filehandle from the +#pod C object. The object itself acts as a filehandle. The object +#pod isa C and isa C so all those methods are +#pod available. +#pod +#pod Also, the object is configured such that it stringifies to the name of the +#pod temporary file and so can be compared to a filename directly. It numifies +#pod to the C the same as other handles and so can be compared to other +#pod handles with C<==>. +#pod +#pod $fh eq $filename # as a string +#pod $fh != \*STDOUT # as a number +#pod +#pod Available since 0.14. +#pod +#pod =over 4 +#pod +#pod =item B +#pod +#pod Create a temporary file object. +#pod +#pod my $tmp = File::Temp->new(); +#pod +#pod by default the object is constructed as if C +#pod was called without options, but with the additional behaviour +#pod that the temporary file is removed by the object destructor +#pod if UNLINK is set to true (the default). +#pod +#pod Supported arguments are the same as for C: UNLINK +#pod (defaulting to true), DIR, EXLOCK, PERMS and SUFFIX. +#pod Additionally, the filename +#pod template is specified using the TEMPLATE option. The OPEN option +#pod is not supported (the file is always opened). +#pod +#pod $tmp = File::Temp->new( TEMPLATE => 'tempXXXXX', +#pod DIR => 'mydir', +#pod SUFFIX => '.dat'); +#pod +#pod Arguments are case insensitive. +#pod +#pod Can call croak() if an error occurs. +#pod +#pod Available since 0.14. +#pod +#pod TEMPLATE available since 0.23 +#pod +#pod =cut + +sub new { + my $proto = shift; + my $class = ref($proto) || $proto; + + my ($maybe_template, $args) = _parse_args(@_); + + # see if they are unlinking (defaulting to yes) + my $unlink = (exists $args->{UNLINK} ? $args->{UNLINK} : 1 ); + delete $args->{UNLINK}; + + # Protect OPEN + delete $args->{OPEN}; + + # Open the file and retain file handle and file name + my ($fh, $path) = tempfile( @$maybe_template, %$args ); + + print "Tmp: $fh - $path\n" if $DEBUG; + + # Store the filename in the scalar slot + ${*$fh} = $path; + + # Cache the filename by pid so that the destructor can decide whether to remove it + $FILES_CREATED_BY_OBJECT{$$}{$path} = 1; + + # Store unlink information in hash slot (plus other constructor info) + %{*$fh} = %$args; + + # create the object + bless $fh, $class; + + # final method-based configuration + $fh->unlink_on_destroy( $unlink ); + + return $fh; +} + +#pod =item B +#pod +#pod Create a temporary directory using an object oriented interface. +#pod +#pod $dir = File::Temp->newdir(); +#pod +#pod By default the directory is deleted when the object goes out of scope. +#pod +#pod Supports the same options as the C function. Note that directories +#pod created with this method default to CLEANUP => 1. +#pod +#pod $dir = File::Temp->newdir( $template, %options ); +#pod +#pod A template may be specified either with a leading template or +#pod with a TEMPLATE argument. +#pod +#pod Available since 0.19. +#pod +#pod TEMPLATE available since 0.23. +#pod +#pod =cut + +sub newdir { + my $self = shift; + + my ($maybe_template, $args) = _parse_args(@_); + + # handle CLEANUP without passing CLEANUP to tempdir + my $cleanup = (exists $args->{CLEANUP} ? $args->{CLEANUP} : 1 ); + delete $args->{CLEANUP}; + + my $tempdir = tempdir( @$maybe_template, %$args); + + # get a safe absolute path for cleanup, just like + # happens in _deferred_unlink + my $real_dir = Cwd::abs_path( $tempdir ); + ($real_dir) = $real_dir =~ /^(.*)$/; + + return bless { DIRNAME => $tempdir, + REALNAME => $real_dir, + CLEANUP => $cleanup, + LAUNCHPID => $$, + }, "File::Temp::Dir"; +} + +#pod =item B +#pod +#pod Return the name of the temporary file associated with this object +#pod (if the object was created using the "new" constructor). +#pod +#pod $filename = $tmp->filename; +#pod +#pod This method is called automatically when the object is used as +#pod a string. +#pod +#pod Current API available since 0.14 +#pod +#pod =cut + +sub filename { + my $self = shift; + return ${*$self}; +} + +sub STRINGIFY { + my $self = shift; + return $self->filename; +} + +# For reference, can't use '0+'=>\&Scalar::Util::refaddr directly because +# refaddr() demands one parameter only, whereas overload.pm calls with three +# even for unary operations like '0+'. +sub NUMIFY { + return refaddr($_[0]); +} + +#pod =item B +#pod +#pod Return the name of the temporary directory associated with this +#pod object (if the object was created using the "newdir" constructor). +#pod +#pod $dirname = $tmpdir->dirname; +#pod +#pod This method is called automatically when the object is used in string context. +#pod +#pod =item B +#pod +#pod Control whether the file is unlinked when the object goes out of scope. +#pod The file is removed if this value is true and $KEEP_ALL is not. +#pod +#pod $fh->unlink_on_destroy( 1 ); +#pod +#pod Default is for the file to be removed. +#pod +#pod Current API available since 0.15 +#pod +#pod =cut + +sub unlink_on_destroy { + my $self = shift; + if (@_) { + ${*$self}{UNLINK} = shift; + } + return ${*$self}{UNLINK}; +} + +#pod =item B +#pod +#pod When the object goes out of scope, the destructor is called. This +#pod destructor will attempt to unlink the file (using L) +#pod if the constructor was called with UNLINK set to 1 (the default state +#pod if UNLINK is not specified). +#pod +#pod No error is given if the unlink fails. +#pod +#pod If the object has been passed to a child process during a fork, the +#pod file will be deleted when the object goes out of scope in the parent. +#pod +#pod For a temporary directory object the directory will be removed unless +#pod the CLEANUP argument was used in the constructor (and set to false) or +#pod C was modified after creation. Note that if a temp +#pod directory is your current directory, it cannot be removed - a warning +#pod will be given in this case. C out of the directory before +#pod letting the object go out of scope. +#pod +#pod If the global variable $KEEP_ALL is true, the file or directory +#pod will not be removed. +#pod +#pod =cut + +sub DESTROY { + local($., $@, $!, $^E, $?); + my $self = shift; + + # Make sure we always remove the file from the global hash + # on destruction. This prevents the hash from growing uncontrollably + # and post-destruction there is no reason to know about the file. + my $file = $self->filename; + my $was_created_by_proc; + if (exists $FILES_CREATED_BY_OBJECT{$$}{$file}) { + $was_created_by_proc = 1; + delete $FILES_CREATED_BY_OBJECT{$$}{$file}; + } + + if (${*$self}{UNLINK} && !$KEEP_ALL) { + print "# ---------> Unlinking $self\n" if $DEBUG; + + # only delete if this process created it + return unless $was_created_by_proc; + + # The unlink1 may fail if the file has been closed + # by the caller. This leaves us with the decision + # of whether to refuse to remove the file or simply + # do an unlink without test. Seems to be silly + # to do this when we are trying to be careful + # about security + _force_writable( $file ); # for windows + unlink1( $self, $file ) + or unlink($file); + } +} + +#pod =back +#pod +#pod =head1 FUNCTIONS +#pod +#pod This section describes the recommended interface for generating +#pod temporary files and directories. +#pod +#pod =over 4 +#pod +#pod =item B +#pod +#pod This is the basic function to generate temporary files. +#pod The behaviour of the file can be changed using various options: +#pod +#pod $fh = tempfile(); +#pod ($fh, $filename) = tempfile(); +#pod +#pod Create a temporary file in the directory specified for temporary +#pod files, as specified by the tmpdir() function in L. +#pod +#pod ($fh, $filename) = tempfile($template); +#pod +#pod Create a temporary file in the current directory using the supplied +#pod template. Trailing `X' characters are replaced with random letters to +#pod generate the filename. At least four `X' characters must be present +#pod at the end of the template. +#pod +#pod ($fh, $filename) = tempfile($template, SUFFIX => $suffix) +#pod +#pod Same as previously, except that a suffix is added to the template +#pod after the `X' translation. Useful for ensuring that a temporary +#pod filename has a particular extension when needed by other applications. +#pod But see the WARNING at the end. +#pod +#pod ($fh, $filename) = tempfile($template, DIR => $dir); +#pod +#pod Translates the template as before except that a directory name +#pod is specified. +#pod +#pod ($fh, $filename) = tempfile($template, TMPDIR => 1); +#pod +#pod Equivalent to specifying a DIR of "File::Spec->tmpdir", writing the file +#pod into the same temporary directory as would be used if no template was +#pod specified at all. +#pod +#pod ($fh, $filename) = tempfile($template, UNLINK => 1); +#pod +#pod Return the filename and filehandle as before except that the file is +#pod automatically removed when the program exits (dependent on +#pod $KEEP_ALL). Default is for the file to be removed if a file handle is +#pod requested and to be kept if the filename is requested. In a scalar +#pod context (where no filename is returned) the file is always deleted +#pod either (depending on the operating system) on exit or when it is +#pod closed (unless $KEEP_ALL is true when the temp file is created). +#pod +#pod Use the object-oriented interface if fine-grained control of when +#pod a file is removed is required. +#pod +#pod If the template is not specified, a template is always +#pod automatically generated. This temporary file is placed in tmpdir() +#pod (L) unless a directory is specified explicitly with the +#pod DIR option. +#pod +#pod $fh = tempfile( DIR => $dir ); +#pod +#pod If called in scalar context, only the filehandle is returned and the +#pod file will automatically be deleted when closed on operating systems +#pod that support this (see the description of tmpfile() elsewhere in this +#pod document). This is the preferred mode of operation, as if you only +#pod have a filehandle, you can never create a race condition by fumbling +#pod with the filename. On systems that can not unlink an open file or can +#pod not mark a file as temporary when it is opened (for example, Windows +#pod NT uses the C flag) the file is marked for deletion when +#pod the program ends (equivalent to setting UNLINK to 1). The C +#pod flag is ignored if present. +#pod +#pod (undef, $filename) = tempfile($template, OPEN => 0); +#pod +#pod This will return the filename based on the template but +#pod will not open this file. Cannot be used in conjunction with +#pod UNLINK set to true. Default is to always open the file +#pod to protect from possible race conditions. A warning is issued +#pod if warnings are turned on. Consider using the tmpnam() +#pod and mktemp() functions described elsewhere in this document +#pod if opening the file is not required. +#pod +#pod To open the temporary filehandle with O_EXLOCK (open with exclusive +#pod file lock) use C<< EXLOCK=>1 >>. This is supported only by some +#pod operating systems (most notably BSD derived systems). By default +#pod EXLOCK will be false. Former C versions set EXLOCK to +#pod true, so to be sure to get an unlocked filehandle also with older +#pod versions, explicitly set C<< EXLOCK=>0 >>. +#pod +#pod ($fh, $filename) = tempfile($template, EXLOCK => 1); +#pod +#pod By default, the temp file is created with 0600 file permissions. +#pod Use C to change this: +#pod +#pod ($fh, $filename) = tempfile($template, PERMS => 0666); +#pod +#pod Options can be combined as required. +#pod +#pod Will croak() if there is an error. +#pod +#pod Available since 0.05. +#pod +#pod UNLINK flag available since 0.10. +#pod +#pod TMPDIR flag available since 0.19. +#pod +#pod EXLOCK flag available since 0.19. +#pod +#pod PERMS flag available since 0.2310. +#pod +#pod =cut + +sub tempfile { + if ( @_ && $_[0] eq 'File::Temp' ) { + croak "'tempfile' can't be called as a method"; + } + # Can not check for argument count since we can have any + # number of args + + # Default options + my %options = ( + "DIR" => undef, # Directory prefix + "SUFFIX" => '', # Template suffix + "UNLINK" => 0, # Do not unlink file on exit + "OPEN" => 1, # Open file + "TMPDIR" => 0, # Place tempfile in tempdir if template specified + "EXLOCK" => 0, # Open file with O_EXLOCK + "PERMS" => undef, # File permissions + ); + + # Check to see whether we have an odd or even number of arguments + my ($maybe_template, $args) = _parse_args(@_); + my $template = @$maybe_template ? $maybe_template->[0] : undef; + + # Read the options and merge with defaults + %options = (%options, %$args); + + # First decision is whether or not to open the file + if (! $options{"OPEN"}) { + + warn "tempfile(): temporary filename requested but not opened.\nPossibly unsafe, consider using tempfile() with OPEN set to true\n" + if $^W; + + } + + if ($options{"DIR"} and $^O eq 'VMS') { + + # on VMS turn []foo into [.foo] for concatenation + $options{"DIR"} = VMS::Filespec::vmspath($options{"DIR"}); + } + + # Construct the template + + # Have a choice of trying to work around the mkstemp/mktemp/tmpnam etc + # functions or simply constructing a template and using _gettemp() + # explicitly. Go for the latter + + # First generate a template if not defined and prefix the directory + # If no template must prefix the temp directory + if (defined $template) { + # End up with current directory if neither DIR not TMPDIR are set + if ($options{"DIR"}) { + + $template = File::Spec->catfile($options{"DIR"}, $template); + + } elsif ($options{TMPDIR}) { + + $template = File::Spec->catfile(_wrap_file_spec_tmpdir(), $template ); + + } + + } else { + + if ($options{"DIR"}) { + + $template = File::Spec->catfile($options{"DIR"}, TEMPXXX); + + } else { + + $template = File::Spec->catfile(_wrap_file_spec_tmpdir(), TEMPXXX); + + } + + } + + # Now add a suffix + $template .= $options{"SUFFIX"}; + + # Determine whether we should tell _gettemp to unlink the file + # On unix this is irrelevant and can be worked out after the file is + # opened (simply by unlinking the open filehandle). On Windows or VMS + # we have to indicate temporary-ness when we open the file. In general + # we only want a true temporary file if we are returning just the + # filehandle - if the user wants the filename they probably do not + # want the file to disappear as soon as they close it (which may be + # important if they want a child process to use the file) + # For this reason, tie unlink_on_close to the return context regardless + # of OS. + my $unlink_on_close = ( wantarray ? 0 : 1); + + # Create the file + my ($fh, $path, $errstr); + croak "Error in tempfile() using template $template: $errstr" + unless (($fh, $path) = _gettemp($template, + "open" => $options{OPEN}, + "mkdir" => 0, + "unlink_on_close" => $unlink_on_close, + "suffixlen" => length($options{SUFFIX}), + "ErrStr" => \$errstr, + "use_exlock" => $options{EXLOCK}, + "file_permissions" => $options{PERMS}, + ) ); + + # Set up an exit handler that can do whatever is right for the + # system. This removes files at exit when requested explicitly or when + # system is asked to unlink_on_close but is unable to do so because + # of OS limitations. + # The latter should be achieved by using a tied filehandle. + # Do not check return status since this is all done with END blocks. + _deferred_unlink($fh, $path, 0) if $options{"UNLINK"}; + + # Return + if (wantarray()) { + + if ($options{'OPEN'}) { + return ($fh, $path); + } else { + return (undef, $path); + } + + } else { + + # Unlink the file. It is up to unlink0 to decide what to do with + # this (whether to unlink now or to defer until later) + unlink0($fh, $path) or croak "Error unlinking file $path using unlink0"; + + # Return just the filehandle. + return $fh; + } + + +} + +# On Windows under taint mode, File::Spec could suggest "C:\" as a tempdir +# which might not be writable. If that is the case, we fallback to a +# user directory. See https://rt.cpan.org/Ticket/Display.html?id=60340 + +{ + my ($alt_tmpdir, $checked); + + sub _wrap_file_spec_tmpdir { + return File::Spec->tmpdir unless $^O eq "MSWin32" && ${^TAINT}; + + if ( $checked ) { + return $alt_tmpdir ? $alt_tmpdir : File::Spec->tmpdir; + } + + # probe what File::Spec gives and find a fallback + my $xxpath = _replace_XX( "X" x 10, 0 ); + + # First, see if File::Spec->tmpdir is writable + my $tmpdir = File::Spec->tmpdir; + my $testpath = File::Spec->catdir( $tmpdir, $xxpath ); + if (mkdir( $testpath, 0700) ) { + $checked = 1; + rmdir $testpath; + return $tmpdir; + } + + # Next, see if CSIDL_LOCAL_APPDATA is writable + require Win32; + my $local_app = File::Spec->catdir( + Win32::GetFolderPath( Win32::CSIDL_LOCAL_APPDATA() ), 'Temp' + ); + $testpath = File::Spec->catdir( $local_app, $xxpath ); + if ( -e $local_app or mkdir( $local_app, 0700 ) ) { + if (mkdir( $testpath, 0700) ) { + $checked = 1; + rmdir $testpath; + return $alt_tmpdir = $local_app; + } + } + + # Can't find something writable + croak << "HERE"; +Couldn't find a writable temp directory in taint mode. Tried: + $tmpdir + $local_app + +Try setting and untainting the TMPDIR environment variable. +HERE + + } +} + +#pod =item B +#pod +#pod This is the recommended interface for creation of temporary +#pod directories. By default the directory will not be removed on exit +#pod (that is, it won't be temporary; this behaviour can not be changed +#pod because of issues with backwards compatibility). To enable removal +#pod either use the CLEANUP option which will trigger removal on program +#pod exit, or consider using the "newdir" method in the object interface which +#pod will allow the directory to be cleaned up when the object goes out of +#pod scope. +#pod +#pod The behaviour of the function depends on the arguments: +#pod +#pod $tempdir = tempdir(); +#pod +#pod Create a directory in tmpdir() (see L). +#pod +#pod $tempdir = tempdir( $template ); +#pod +#pod Create a directory from the supplied template. This template is +#pod similar to that described for tempfile(). `X' characters at the end +#pod of the template are replaced with random letters to construct the +#pod directory name. At least four `X' characters must be in the template. +#pod +#pod $tempdir = tempdir ( DIR => $dir ); +#pod +#pod Specifies the directory to use for the temporary directory. +#pod The temporary directory name is derived from an internal template. +#pod +#pod $tempdir = tempdir ( $template, DIR => $dir ); +#pod +#pod Prepend the supplied directory name to the template. The template +#pod should not include parent directory specifications itself. Any parent +#pod directory specifications are removed from the template before +#pod prepending the supplied directory. +#pod +#pod $tempdir = tempdir ( $template, TMPDIR => 1 ); +#pod +#pod Using the supplied template, create the temporary directory in +#pod a standard location for temporary files. Equivalent to doing +#pod +#pod $tempdir = tempdir ( $template, DIR => File::Spec->tmpdir); +#pod +#pod but shorter. Parent directory specifications are stripped from the +#pod template itself. The C option is ignored if C is set +#pod explicitly. Additionally, C is implied if neither a template +#pod nor a directory are supplied. +#pod +#pod $tempdir = tempdir( $template, CLEANUP => 1); +#pod +#pod Create a temporary directory using the supplied template, but +#pod attempt to remove it (and all files inside it) when the program +#pod exits. Note that an attempt will be made to remove all files from +#pod the directory even if they were not created by this module (otherwise +#pod why ask to clean it up?). The directory removal is made with +#pod the rmtree() function from the L module. +#pod Of course, if the template is not specified, the temporary directory +#pod will be created in tmpdir() and will also be removed at program exit. +#pod +#pod Will croak() if there is an error. +#pod +#pod Current API available since 0.05. +#pod +#pod =cut + +# ' + +sub tempdir { + if ( @_ && $_[0] eq 'File::Temp' ) { + croak "'tempdir' can't be called as a method"; + } + + # Can not check for argument count since we can have any + # number of args + + # Default options + my %options = ( + "CLEANUP" => 0, # Remove directory on exit + "DIR" => '', # Root directory + "TMPDIR" => 0, # Use tempdir with template + ); + + # Check to see whether we have an odd or even number of arguments + my ($maybe_template, $args) = _parse_args(@_); + my $template = @$maybe_template ? $maybe_template->[0] : undef; + + # Read the options and merge with defaults + %options = (%options, %$args); + + # Modify or generate the template + + # Deal with the DIR and TMPDIR options + if (defined $template) { + + # Need to strip directory path if using DIR or TMPDIR + if ($options{'TMPDIR'} || $options{'DIR'}) { + + # Strip parent directory from the filename + # + # There is no filename at the end + $template = VMS::Filespec::vmspath($template) if $^O eq 'VMS'; + my ($volume, $directories, undef) = File::Spec->splitpath( $template, 1); + + # Last directory is then our template + $template = (File::Spec->splitdir($directories))[-1]; + + # Prepend the supplied directory or temp dir + if ($options{"DIR"}) { + + $template = File::Spec->catdir($options{"DIR"}, $template); + + } elsif ($options{TMPDIR}) { + + # Prepend tmpdir + $template = File::Spec->catdir(_wrap_file_spec_tmpdir(), $template); + + } + + } + + } else { + + if ($options{"DIR"}) { + + $template = File::Spec->catdir($options{"DIR"}, TEMPXXX); + + } else { + + $template = File::Spec->catdir(_wrap_file_spec_tmpdir(), TEMPXXX); + + } + + } + + # Create the directory + my $tempdir; + my $suffixlen = 0; + if ($^O eq 'VMS') { # dir names can end in delimiters + $template =~ m/([\.\]:>]+)$/; + $suffixlen = length($1); + } + if ( ($^O eq 'MacOS') && (substr($template, -1) eq ':') ) { + # dir name has a trailing ':' + ++$suffixlen; + } + + my $errstr; + croak "Error in tempdir() using $template: $errstr" + unless ((undef, $tempdir) = _gettemp($template, + "open" => 0, + "mkdir"=> 1 , + "suffixlen" => $suffixlen, + "ErrStr" => \$errstr, + ) ); + + # Install exit handler; must be dynamic to get lexical + if ( $options{'CLEANUP'} && -d $tempdir) { + _deferred_unlink(undef, $tempdir, 1); + } + + # Return the dir name + return $tempdir; + +} + +#pod =back +#pod +#pod =head1 MKTEMP FUNCTIONS +#pod +#pod The following functions are Perl implementations of the +#pod mktemp() family of temp file generation system calls. +#pod +#pod =over 4 +#pod +#pod =item B +#pod +#pod Given a template, returns a filehandle to the temporary file and the name +#pod of the file. +#pod +#pod ($fh, $name) = mkstemp( $template ); +#pod +#pod In scalar context, just the filehandle is returned. +#pod +#pod The template may be any filename with some number of X's appended +#pod to it, for example F. The trailing X's are replaced +#pod with unique alphanumeric combinations. +#pod +#pod Will croak() if there is an error. +#pod +#pod Current API available since 0.05. +#pod +#pod =cut + + + +sub mkstemp { + + croak "Usage: mkstemp(template)" + if scalar(@_) != 1; + + my $template = shift; + + my ($fh, $path, $errstr); + croak "Error in mkstemp using $template: $errstr" + unless (($fh, $path) = _gettemp($template, + "open" => 1, + "mkdir"=> 0 , + "suffixlen" => 0, + "ErrStr" => \$errstr, + ) ); + + if (wantarray()) { + return ($fh, $path); + } else { + return $fh; + } + +} + + +#pod =item B +#pod +#pod Similar to mkstemp(), except that an extra argument can be supplied +#pod with a suffix to be appended to the template. +#pod +#pod ($fh, $name) = mkstemps( $template, $suffix ); +#pod +#pod For example a template of C and suffix of C<.dat> +#pod would generate a file similar to F. +#pod +#pod Returns just the filehandle alone when called in scalar context. +#pod +#pod Will croak() if there is an error. +#pod +#pod Current API available since 0.05. +#pod +#pod =cut + +sub mkstemps { + + croak "Usage: mkstemps(template, suffix)" + if scalar(@_) != 2; + + + my $template = shift; + my $suffix = shift; + + $template .= $suffix; + + my ($fh, $path, $errstr); + croak "Error in mkstemps using $template: $errstr" + unless (($fh, $path) = _gettemp($template, + "open" => 1, + "mkdir"=> 0 , + "suffixlen" => length($suffix), + "ErrStr" => \$errstr, + ) ); + + if (wantarray()) { + return ($fh, $path); + } else { + return $fh; + } + +} + +#pod =item B +#pod +#pod Create a directory from a template. The template must end in +#pod X's that are replaced by the routine. +#pod +#pod $tmpdir_name = mkdtemp($template); +#pod +#pod Returns the name of the temporary directory created. +#pod +#pod Directory must be removed by the caller. +#pod +#pod Will croak() if there is an error. +#pod +#pod Current API available since 0.05. +#pod +#pod =cut + +#' # for emacs + +sub mkdtemp { + + croak "Usage: mkdtemp(template)" + if scalar(@_) != 1; + + my $template = shift; + my $suffixlen = 0; + if ($^O eq 'VMS') { # dir names can end in delimiters + $template =~ m/([\.\]:>]+)$/; + $suffixlen = length($1); + } + if ( ($^O eq 'MacOS') && (substr($template, -1) eq ':') ) { + # dir name has a trailing ':' + ++$suffixlen; + } + my ($junk, $tmpdir, $errstr); + croak "Error creating temp directory from template $template\: $errstr" + unless (($junk, $tmpdir) = _gettemp($template, + "open" => 0, + "mkdir"=> 1 , + "suffixlen" => $suffixlen, + "ErrStr" => \$errstr, + ) ); + + return $tmpdir; + +} + +#pod =item B +#pod +#pod Returns a valid temporary filename but does not guarantee +#pod that the file will not be opened by someone else. +#pod +#pod $unopened_file = mktemp($template); +#pod +#pod Template is the same as that required by mkstemp(). +#pod +#pod Will croak() if there is an error. +#pod +#pod Current API available since 0.05. +#pod +#pod =cut + +sub mktemp { + + croak "Usage: mktemp(template)" + if scalar(@_) != 1; + + my $template = shift; + + my ($tmpname, $junk, $errstr); + croak "Error getting name to temp file from template $template: $errstr" + unless (($junk, $tmpname) = _gettemp($template, + "open" => 0, + "mkdir"=> 0 , + "suffixlen" => 0, + "ErrStr" => \$errstr, + ) ); + + return $tmpname; +} + +#pod =back +#pod +#pod =head1 POSIX FUNCTIONS +#pod +#pod This section describes the re-implementation of the tmpnam() +#pod and tmpfile() functions described in L +#pod using the mkstemp() from this module. +#pod +#pod Unlike the L implementations, the directory used +#pod for the temporary file is not specified in a system include +#pod file (C) but simply depends on the choice of tmpdir() +#pod returned by L. On some implementations this +#pod location can be set using the C environment variable, which +#pod may not be secure. +#pod If this is a problem, simply use mkstemp() and specify a template. +#pod +#pod =over 4 +#pod +#pod =item B +#pod +#pod When called in scalar context, returns the full name (including path) +#pod of a temporary file (uses mktemp()). The only check is that the file does +#pod not already exist, but there is no guarantee that that condition will +#pod continue to apply. +#pod +#pod $file = tmpnam(); +#pod +#pod When called in list context, a filehandle to the open file and +#pod a filename are returned. This is achieved by calling mkstemp() +#pod after constructing a suitable template. +#pod +#pod ($fh, $file) = tmpnam(); +#pod +#pod If possible, this form should be used to prevent possible +#pod race conditions. +#pod +#pod See L for information on the choice of temporary +#pod directory for a particular operating system. +#pod +#pod Will croak() if there is an error. +#pod +#pod Current API available since 0.05. +#pod +#pod =cut + +sub tmpnam { + + # Retrieve the temporary directory name + my $tmpdir = _wrap_file_spec_tmpdir(); + + # XXX I don't know under what circumstances this occurs, -- xdg 2016-04-02 + croak "Error temporary directory is not writable" + if $tmpdir eq ''; + + # Use a ten character template and append to tmpdir + my $template = File::Spec->catfile($tmpdir, TEMPXXX); + + if (wantarray() ) { + return mkstemp($template); + } else { + return mktemp($template); + } + +} + +#pod =item B +#pod +#pod Returns the filehandle of a temporary file. +#pod +#pod $fh = tmpfile(); +#pod +#pod The file is removed when the filehandle is closed or when the program +#pod exits. No access to the filename is provided. +#pod +#pod If the temporary file can not be created undef is returned. +#pod Currently this command will probably not work when the temporary +#pod directory is on an NFS file system. +#pod +#pod Will croak() if there is an error. +#pod +#pod Available since 0.05. +#pod +#pod Returning undef if unable to create file added in 0.12. +#pod +#pod =cut + +sub tmpfile { + + # Simply call tmpnam() in a list context + my ($fh, $file) = tmpnam(); + + # Make sure file is removed when filehandle is closed + # This will fail on NFS + unlink0($fh, $file) + or return undef; + + return $fh; + +} + +#pod =back +#pod +#pod =head1 ADDITIONAL FUNCTIONS +#pod +#pod These functions are provided for backwards compatibility +#pod with common tempfile generation C library functions. +#pod +#pod They are not exported and must be addressed using the full package +#pod name. +#pod +#pod =over 4 +#pod +#pod =item B +#pod +#pod Return the name of a temporary file in the specified directory +#pod using a prefix. The file is guaranteed not to exist at the time +#pod the function was called, but such guarantees are good for one +#pod clock tick only. Always use the proper form of C +#pod with C if you must open such a filename. +#pod +#pod $filename = File::Temp::tempnam( $dir, $prefix ); +#pod +#pod Equivalent to running mktemp() with $dir/$prefixXXXXXXXX +#pod (using unix file convention as an example) +#pod +#pod Because this function uses mktemp(), it can suffer from race conditions. +#pod +#pod Will croak() if there is an error. +#pod +#pod Current API available since 0.05. +#pod +#pod =cut + +sub tempnam { + + croak 'Usage tempnam($dir, $prefix)' unless scalar(@_) == 2; + + my ($dir, $prefix) = @_; + + # Add a string to the prefix + $prefix .= 'XXXXXXXX'; + + # Concatenate the directory to the file + my $template = File::Spec->catfile($dir, $prefix); + + return mktemp($template); + +} + +#pod =back +#pod +#pod =head1 UTILITY FUNCTIONS +#pod +#pod Useful functions for dealing with the filehandle and filename. +#pod +#pod =over 4 +#pod +#pod =item B +#pod +#pod Given an open filehandle and the associated filename, make a safe +#pod unlink. This is achieved by first checking that the filename and +#pod filehandle initially point to the same file and that the number of +#pod links to the file is 1 (all fields returned by stat() are compared). +#pod Then the filename is unlinked and the filehandle checked once again to +#pod verify that the number of links on that file is now 0. This is the +#pod closest you can come to making sure that the filename unlinked was the +#pod same as the file whose descriptor you hold. +#pod +#pod unlink0($fh, $path) +#pod or die "Error unlinking file $path safely"; +#pod +#pod Returns false on error but croaks() if there is a security +#pod anomaly. The filehandle is not closed since on some occasions this is +#pod not required. +#pod +#pod On some platforms, for example Windows NT, it is not possible to +#pod unlink an open file (the file must be closed first). On those +#pod platforms, the actual unlinking is deferred until the program ends and +#pod good status is returned. A check is still performed to make sure that +#pod the filehandle and filename are pointing to the same thing (but not at +#pod the time the end block is executed since the deferred removal may not +#pod have access to the filehandle). +#pod +#pod Additionally, on Windows NT not all the fields returned by stat() can +#pod be compared. For example, the C and C fields seem to be +#pod different. Also, it seems that the size of the file returned by stat() +#pod does not always agree, with C being more accurate than +#pod C, presumably because of caching issues even when +#pod using autoflush (this is usually overcome by waiting a while after +#pod writing to the tempfile before attempting to C it). +#pod +#pod Finally, on NFS file systems the link count of the file handle does +#pod not always go to zero immediately after unlinking. Currently, this +#pod command is expected to fail on NFS disks. +#pod +#pod This function is disabled if the global variable $KEEP_ALL is true +#pod and an unlink on open file is supported. If the unlink is to be deferred +#pod to the END block, the file is still registered for removal. +#pod +#pod This function should not be called if you are using the object oriented +#pod interface since the it will interfere with the object destructor deleting +#pod the file. +#pod +#pod Available Since 0.05. +#pod +#pod If can not unlink open file, defer removal until later available since 0.06. +#pod +#pod =cut + +sub unlink0 { + + croak 'Usage: unlink0(filehandle, filename)' + unless scalar(@_) == 2; + + # Read args + my ($fh, $path) = @_; + + cmpstat($fh, $path) or return 0; + + # attempt remove the file (does not work on some platforms) + if (_can_unlink_opened_file()) { + + # return early (Without unlink) if we have been instructed to retain files. + return 1 if $KEEP_ALL; + + # XXX: do *not* call this on a directory; possible race + # resulting in recursive removal + croak "unlink0: $path has become a directory!" if -d $path; + unlink($path) or return 0; + + # Stat the filehandle + my @fh = stat $fh; + + print "Link count = $fh[3] \n" if $DEBUG; + + # Make sure that the link count is zero + # - Cygwin provides deferred unlinking, however, + # on Win9x the link count remains 1 + # On NFS the link count may still be 1 but we can't know that + # we are on NFS. Since we can't be sure, we'll defer it + + return 1 if $fh[3] == 0 || $^O eq 'cygwin'; + } + # fall-through if we can't unlink now + _deferred_unlink($fh, $path, 0); + return 1; +} + +#pod =item B +#pod +#pod Compare C of filehandle with C of provided filename. This +#pod can be used to check that the filename and filehandle initially point +#pod to the same file and that the number of links to the file is 1 (all +#pod fields returned by stat() are compared). +#pod +#pod cmpstat($fh, $path) +#pod or die "Error comparing handle with file"; +#pod +#pod Returns false if the stat information differs or if the link count is +#pod greater than 1. Calls croak if there is a security anomaly. +#pod +#pod On certain platforms, for example Windows, not all the fields returned by stat() +#pod can be compared. For example, the C and C fields seem to be +#pod different in Windows. Also, it seems that the size of the file +#pod returned by stat() does not always agree, with C being more +#pod accurate than C, presumably because of caching issues +#pod even when using autoflush (this is usually overcome by waiting a while +#pod after writing to the tempfile before attempting to C it). +#pod +#pod Not exported by default. +#pod +#pod Current API available since 0.14. +#pod +#pod =cut + +sub cmpstat { + + croak 'Usage: cmpstat(filehandle, filename)' + unless scalar(@_) == 2; + + # Read args + my ($fh, $path) = @_; + + warn "Comparing stat\n" + if $DEBUG; + + # Stat the filehandle - which may be closed if someone has manually + # closed the file. Can not turn off warnings without using $^W + # unless we upgrade to 5.006 minimum requirement + my @fh; + { + local ($^W) = 0; + @fh = stat $fh; + } + return unless @fh; + + if ($fh[3] > 1 && $^W) { + carp "unlink0: fstat found too many links; SB=@fh" if $^W; + } + + # Stat the path + my @path = stat $path; + + unless (@path) { + carp "unlink0: $path is gone already" if $^W; + return; + } + + # this is no longer a file, but may be a directory, or worse + unless (-f $path) { + confess "panic: $path is no longer a file: SB=@fh"; + } + + # Do comparison of each member of the array + # On WinNT dev and rdev seem to be different + # depending on whether it is a file or a handle. + # Cannot simply compare all members of the stat return + # Select the ones we can use + my @okstat = (0..$#fh); # Use all by default + if ($^O eq 'MSWin32') { + @okstat = (1,2,3,4,5,7,8,9,10); + } elsif ($^O eq 'os2') { + @okstat = (0, 2..$#fh); + } elsif ($^O eq 'VMS') { # device and file ID are sufficient + @okstat = (0, 1); + } elsif ($^O eq 'dos') { + @okstat = (0,2..7,11..$#fh); + } elsif ($^O eq 'mpeix') { + @okstat = (0..4,8..10); + } + + # Now compare each entry explicitly by number + for (@okstat) { + print "Comparing: $_ : $fh[$_] and $path[$_]\n" if $DEBUG; + # Use eq rather than == since rdev, blksize, and blocks (6, 11, + # and 12) will be '' on platforms that do not support them. This + # is fine since we are only comparing integers. + unless ($fh[$_] eq $path[$_]) { + warn "Did not match $_ element of stat\n" if $DEBUG; + return 0; + } + } + + return 1; +} + +#pod =item B +#pod +#pod Similar to C except after file comparison using cmpstat, the +#pod filehandle is closed prior to attempting to unlink the file. This +#pod allows the file to be removed without using an END block, but does +#pod mean that the post-unlink comparison of the filehandle state provided +#pod by C is not available. +#pod +#pod unlink1($fh, $path) +#pod or die "Error closing and unlinking file"; +#pod +#pod Usually called from the object destructor when using the OO interface. +#pod +#pod Not exported by default. +#pod +#pod This function is disabled if the global variable $KEEP_ALL is true. +#pod +#pod Can call croak() if there is a security anomaly during the stat() +#pod comparison. +#pod +#pod Current API available since 0.14. +#pod +#pod =cut + +sub unlink1 { + croak 'Usage: unlink1(filehandle, filename)' + unless scalar(@_) == 2; + + # Read args + my ($fh, $path) = @_; + + cmpstat($fh, $path) or return 0; + + # Close the file + close( $fh ) or return 0; + + # Make sure the file is writable (for windows) + _force_writable( $path ); + + # return early (without unlink) if we have been instructed to retain files. + return 1 if $KEEP_ALL; + + # remove the file + return unlink($path); +} + +#pod =item B +#pod +#pod Calling this function will cause any temp files or temp directories +#pod that are registered for removal to be removed. This happens automatically +#pod when the process exits but can be triggered manually if the caller is sure +#pod that none of the temp files are required. This method can be registered as +#pod an Apache callback. +#pod +#pod Note that if a temp directory is your current directory, it cannot be +#pod removed. C out of the directory first before calling +#pod C. (For the cleanup at program exit when the CLEANUP flag +#pod is set, this happens automatically.) +#pod +#pod On OSes where temp files are automatically removed when the temp file +#pod is closed, calling this function will have no effect other than to remove +#pod temporary directories (which may include temporary files). +#pod +#pod File::Temp::cleanup(); +#pod +#pod Not exported by default. +#pod +#pod Current API available since 0.15. +#pod +#pod =back +#pod +#pod =head1 PACKAGE VARIABLES +#pod +#pod These functions control the global state of the package. +#pod +#pod =over 4 +#pod +#pod =item B +#pod +#pod Controls the lengths to which the module will go to check the safety of the +#pod temporary file or directory before proceeding. +#pod Options are: +#pod +#pod =over 8 +#pod +#pod =item STANDARD +#pod +#pod Do the basic security measures to ensure the directory exists and is +#pod writable, that temporary files are opened only if they do not already +#pod exist, and that possible race conditions are avoided. Finally the +#pod L function is used to remove files safely. +#pod +#pod =item MEDIUM +#pod +#pod In addition to the STANDARD security, the output directory is checked +#pod to make sure that it is owned either by root or the user running the +#pod program. If the directory is writable by group or by other, it is then +#pod checked to make sure that the sticky bit is set. +#pod +#pod Will not work on platforms that do not support the C<-k> test +#pod for sticky bit. +#pod +#pod =item HIGH +#pod +#pod In addition to the MEDIUM security checks, also check for the +#pod possibility of ``chown() giveaway'' using the L +#pod sysconf() function. If this is a possibility, each directory in the +#pod path is checked in turn for safeness, recursively walking back to the +#pod root directory. +#pod +#pod For platforms that do not support the L +#pod C<_PC_CHOWN_RESTRICTED> symbol (for example, Windows NT) it is +#pod assumed that ``chown() giveaway'' is possible and the recursive test +#pod is performed. +#pod +#pod =back +#pod +#pod The level can be changed as follows: +#pod +#pod File::Temp->safe_level( File::Temp::HIGH ); +#pod +#pod The level constants are not exported by the module. +#pod +#pod Currently, you must be running at least perl v5.6.0 in order to +#pod run with MEDIUM or HIGH security. This is simply because the +#pod safety tests use functions from L that are not +#pod available in older versions of perl. The problem is that the version +#pod number for Fcntl is the same in perl 5.6.0 and in 5.005_03 even though +#pod they are different versions. +#pod +#pod On systems that do not support the HIGH or MEDIUM safety levels +#pod (for example Win NT or OS/2) any attempt to change the level will +#pod be ignored. The decision to ignore rather than raise an exception +#pod allows portable programs to be written with high security in mind +#pod for the systems that can support this without those programs failing +#pod on systems where the extra tests are irrelevant. +#pod +#pod If you really need to see whether the change has been accepted +#pod simply examine the return value of C. +#pod +#pod $newlevel = File::Temp->safe_level( File::Temp::HIGH ); +#pod die "Could not change to high security" +#pod if $newlevel != File::Temp::HIGH; +#pod +#pod Available since 0.05. +#pod +#pod =cut + +{ + # protect from using the variable itself + my $LEVEL = STANDARD; + sub safe_level { + my $self = shift; + if (@_) { + my $level = shift; + if (($level != STANDARD) && ($level != MEDIUM) && ($level != HIGH)) { + carp "safe_level: Specified level ($level) not STANDARD, MEDIUM or HIGH - ignoring\n" if $^W; + } else { + # Don't allow this on perl 5.005 or earlier + if ($] < 5.006 && $level != STANDARD) { + # Cant do MEDIUM or HIGH checks + croak "Currently requires perl 5.006 or newer to do the safe checks"; + } + # Check that we are allowed to change level + # Silently ignore if we can not. + $LEVEL = $level if _can_do_level($level); + } + } + return $LEVEL; + } +} + +#pod =item TopSystemUID +#pod +#pod This is the highest UID on the current system that refers to a root +#pod UID. This is used to make sure that the temporary directory is +#pod owned by a system UID (C, C, C etc) rather than +#pod simply by root. +#pod +#pod This is required since on many unix systems C is not owned +#pod by root. +#pod +#pod Default is to assume that any UID less than or equal to 10 is a root +#pod UID. +#pod +#pod File::Temp->top_system_uid(10); +#pod my $topid = File::Temp->top_system_uid; +#pod +#pod This value can be adjusted to reduce security checking if required. +#pod The value is only relevant when C is set to MEDIUM or higher. +#pod +#pod Available since 0.05. +#pod +#pod =cut + +{ + my $TopSystemUID = 10; + $TopSystemUID = 197108 if $^O eq 'interix'; # "Administrator" + sub top_system_uid { + my $self = shift; + if (@_) { + my $newuid = shift; + croak "top_system_uid: UIDs should be numeric" + unless $newuid =~ /^\d+$/s; + $TopSystemUID = $newuid; + } + return $TopSystemUID; + } +} + +#pod =item B<$KEEP_ALL> +#pod +#pod Controls whether temporary files and directories should be retained +#pod regardless of any instructions in the program to remove them +#pod automatically. This is useful for debugging but should not be used in +#pod production code. +#pod +#pod $File::Temp::KEEP_ALL = 1; +#pod +#pod Default is for files to be removed as requested by the caller. +#pod +#pod In some cases, files will only be retained if this variable is true +#pod when the file is created. This means that you can not create a temporary +#pod file, set this variable and expect the temp file to still be around +#pod when the program exits. +#pod +#pod =item B<$DEBUG> +#pod +#pod Controls whether debugging messages should be enabled. +#pod +#pod $File::Temp::DEBUG = 1; +#pod +#pod Default is for debugging mode to be disabled. +#pod +#pod Available since 0.15. +#pod +#pod =back +#pod +#pod =head1 WARNING +#pod +#pod For maximum security, endeavour always to avoid ever looking at, +#pod touching, or even imputing the existence of the filename. You do not +#pod know that that filename is connected to the same file as the handle +#pod you have, and attempts to check this can only trigger more race +#pod conditions. It's far more secure to use the filehandle alone and +#pod dispense with the filename altogether. +#pod +#pod If you need to pass the handle to something that expects a filename +#pod then on a unix system you can use C<"/dev/fd/" . fileno($fh)> for +#pod arbitrary programs. Perl code that uses the 2-argument version of +#pod C<< open >> can be passed C<< "+<=&" . fileno($fh) >>. Otherwise you +#pod will need to pass the filename. You will have to clear the +#pod close-on-exec bit on that file descriptor before passing it to another +#pod process. +#pod +#pod use Fcntl qw/F_SETFD F_GETFD/; +#pod fcntl($tmpfh, F_SETFD, 0) +#pod or die "Can't clear close-on-exec flag on temp fh: $!\n"; +#pod +#pod =head2 Temporary files and NFS +#pod +#pod Some problems are associated with using temporary files that reside +#pod on NFS file systems and it is recommended that a local filesystem +#pod is used whenever possible. Some of the security tests will most probably +#pod fail when the temp file is not local. Additionally, be aware that +#pod the performance of I/O operations over NFS will not be as good as for +#pod a local disk. +#pod +#pod =head2 Forking +#pod +#pod In some cases files created by File::Temp are removed from within an +#pod END block. Since END blocks are triggered when a child process exits +#pod (unless C is used by the child) File::Temp takes care +#pod to only remove those temp files created by a particular process ID. This +#pod means that a child will not attempt to remove temp files created by the +#pod parent process. +#pod +#pod If you are forking many processes in parallel that are all creating +#pod temporary files, you may need to reset the random number seed using +#pod srand(EXPR) in each child else all the children will attempt to walk +#pod through the same set of random file names and may well cause +#pod themselves to give up if they exceed the number of retry attempts. +#pod +#pod =head2 Directory removal +#pod +#pod Note that if you have chdir'ed into the temporary directory and it is +#pod subsequently cleaned up (either in the END block or as part of object +#pod destruction), then you will get a warning from File::Path::rmtree(). +#pod +#pod =head2 Taint mode +#pod +#pod If you need to run code under taint mode, updating to the latest +#pod L is highly recommended. On Windows, if the directory +#pod given by L isn't writable, File::Temp will attempt +#pod to fallback to the user's local application data directory or croak +#pod with an error. +#pod +#pod =head2 BINMODE +#pod +#pod The file returned by File::Temp will have been opened in binary mode +#pod if such a mode is available. If that is not correct, use the C +#pod function to change the mode of the filehandle. +#pod +#pod Note that you can modify the encoding of a file opened by File::Temp +#pod also by using C. +#pod +#pod =head1 HISTORY +#pod +#pod Originally began life in May 1999 as an XS interface to the system +#pod mkstemp() function. In March 2000, the OpenBSD mkstemp() code was +#pod translated to Perl for total control of the code's +#pod security checking, to ensure the presence of the function regardless of +#pod operating system and to help with portability. The module was shipped +#pod as a standard part of perl from v5.6.1. +#pod +#pod Thanks to Tom Christiansen for suggesting that this module +#pod should be written and providing ideas for code improvements and +#pod security enhancements. +#pod +#pod =head1 SEE ALSO +#pod +#pod L, L, L, L +#pod +#pod See L and L, L for +#pod different implementations of temporary file handling. +#pod +#pod See L for an alternative object-oriented wrapper for +#pod the C function. +#pod +#pod =cut + +package ## hide from PAUSE + File::Temp::Dir; + +our $VERSION = '0.2311'; + +use File::Path qw/ rmtree /; +use strict; +use overload '""' => "STRINGIFY", + '0+' => \&File::Temp::NUMIFY, + fallback => 1; + +# private class specifically to support tempdir objects +# created by File::Temp->newdir + +# ostensibly the same method interface as File::Temp but without +# inheriting all the IO::Seekable methods and other cruft + +# Read-only - returns the name of the temp directory + +sub dirname { + my $self = shift; + return $self->{DIRNAME}; +} + +sub STRINGIFY { + my $self = shift; + return $self->dirname; +} + +sub unlink_on_destroy { + my $self = shift; + if (@_) { + $self->{CLEANUP} = shift; + } + return $self->{CLEANUP}; +} + +sub DESTROY { + my $self = shift; + local($., $@, $!, $^E, $?); + if ($self->unlink_on_destroy && + $$ == $self->{LAUNCHPID} && !$File::Temp::KEEP_ALL) { + if (-d $self->{REALNAME}) { + # Some versions of rmtree will abort if you attempt to remove + # the directory you are sitting in. We protect that and turn it + # into a warning. We do this because this occurs during object + # destruction and so can not be caught by the user. + eval { rmtree($self->{REALNAME}, $File::Temp::DEBUG, 0); }; + warn $@ if ($@ && $^W); + } + } +} + +1; + + +# vim: ts=2 sts=2 sw=2 et: + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +File::Temp - return name and handle of a temporary file safely + +=head1 VERSION + +version 0.2311 + +=head1 SYNOPSIS + + use File::Temp qw/ tempfile tempdir /; + + $fh = tempfile(); + ($fh, $filename) = tempfile(); + + ($fh, $filename) = tempfile( $template, DIR => $dir); + ($fh, $filename) = tempfile( $template, SUFFIX => '.dat'); + ($fh, $filename) = tempfile( $template, TMPDIR => 1 ); + + binmode( $fh, ":utf8" ); + + $dir = tempdir( CLEANUP => 1 ); + ($fh, $filename) = tempfile( DIR => $dir ); + +Object interface: + + require File::Temp; + use File::Temp (); + use File::Temp qw/ :seekable /; + + $fh = File::Temp->new(); + $fname = $fh->filename; + + $fh = File::Temp->new(TEMPLATE => $template); + $fname = $fh->filename; + + $tmp = File::Temp->new( UNLINK => 0, SUFFIX => '.dat' ); + print $tmp "Some data\n"; + print "Filename is $tmp\n"; + $tmp->seek( 0, SEEK_END ); + + $dir = File::Temp->newdir(); # CLEANUP => 1 by default + +The following interfaces are provided for compatibility with +existing APIs. They should not be used in new code. + +MkTemp family: + + use File::Temp qw/ :mktemp /; + + ($fh, $file) = mkstemp( "tmpfileXXXXX" ); + ($fh, $file) = mkstemps( "tmpfileXXXXXX", $suffix); + + $tmpdir = mkdtemp( $template ); + + $unopened_file = mktemp( $template ); + +POSIX functions: + + use File::Temp qw/ :POSIX /; + + $file = tmpnam(); + $fh = tmpfile(); + + ($fh, $file) = tmpnam(); + +Compatibility functions: + + $unopened_file = File::Temp::tempnam( $dir, $pfx ); + +=head1 DESCRIPTION + +C can be used to create and open temporary files in a safe +way. There is both a function interface and an object-oriented +interface. The File::Temp constructor or the tempfile() function can +be used to return the name and the open filehandle of a temporary +file. The tempdir() function can be used to create a temporary +directory. + +The security aspect of temporary file creation is emphasized such that +a filehandle and filename are returned together. This helps guarantee +that a race condition can not occur where the temporary file is +created by another process between checking for the existence of the +file and its opening. Additional security levels are provided to +check, for example, that the sticky bit is set on world writable +directories. See L<"safe_level"> for more information. + +For compatibility with popular C library functions, Perl implementations of +the mkstemp() family of functions are provided. These are, mkstemp(), +mkstemps(), mkdtemp() and mktemp(). + +Additionally, implementations of the standard L +tmpnam() and tmpfile() functions are provided if required. + +Implementations of mktemp(), tmpnam(), and tempnam() are provided, +but should be used with caution since they return only a filename +that was valid when function was called, so cannot guarantee +that the file will not exist by the time the caller opens the filename. + +Filehandles returned by these functions support the seekable methods. + +=begin :__INTERNALS + +=head1 PORTABILITY + +This section is at the top in order to provide easier access to +porters. It is not expected to be rendered by a standard pod +formatting tool. Please skip straight to the SYNOPSIS section if you +are not trying to port this module to a new platform. + +This module is designed to be portable across operating systems and it +currently supports Unix, VMS, DOS, OS/2, Windows and Mac OS +(Classic). When porting to a new OS there are generally three main +issues that have to be solved: + +=over 4 + +=item * + +Can the OS unlink an open file? If it can not then the +C<_can_unlink_opened_file> method should be modified. + +=item * + +Are the return values from C reliable? By default all the +return values from C are compared when unlinking a temporary +file using the filename and the handle. Operating systems other than +unix do not always have valid entries in all fields. If utility function +C fails then the C comparison should be +modified accordingly. + +=item * + +Security. Systems that can not support a test for the sticky bit +on a directory can not use the MEDIUM and HIGH security tests. +The C<_can_do_level> method should be modified accordingly. + +=back + +=end :__INTERNALS + +=head1 OBJECT-ORIENTED INTERFACE + +This is the primary interface for interacting with +C. Using the OO interface a temporary file can be created +when the object is constructed and the file can be removed when the +object is no longer required. + +Note that there is no method to obtain the filehandle from the +C object. The object itself acts as a filehandle. The object +isa C and isa C so all those methods are +available. + +Also, the object is configured such that it stringifies to the name of the +temporary file and so can be compared to a filename directly. It numifies +to the C the same as other handles and so can be compared to other +handles with C<==>. + + $fh eq $filename # as a string + $fh != \*STDOUT # as a number + +Available since 0.14. + +=over 4 + +=item B + +Create a temporary file object. + + my $tmp = File::Temp->new(); + +by default the object is constructed as if C +was called without options, but with the additional behaviour +that the temporary file is removed by the object destructor +if UNLINK is set to true (the default). + +Supported arguments are the same as for C: UNLINK +(defaulting to true), DIR, EXLOCK, PERMS and SUFFIX. +Additionally, the filename +template is specified using the TEMPLATE option. The OPEN option +is not supported (the file is always opened). + + $tmp = File::Temp->new( TEMPLATE => 'tempXXXXX', + DIR => 'mydir', + SUFFIX => '.dat'); + +Arguments are case insensitive. + +Can call croak() if an error occurs. + +Available since 0.14. + +TEMPLATE available since 0.23 + +=item B + +Create a temporary directory using an object oriented interface. + + $dir = File::Temp->newdir(); + +By default the directory is deleted when the object goes out of scope. + +Supports the same options as the C function. Note that directories +created with this method default to CLEANUP => 1. + + $dir = File::Temp->newdir( $template, %options ); + +A template may be specified either with a leading template or +with a TEMPLATE argument. + +Available since 0.19. + +TEMPLATE available since 0.23. + +=item B + +Return the name of the temporary file associated with this object +(if the object was created using the "new" constructor). + + $filename = $tmp->filename; + +This method is called automatically when the object is used as +a string. + +Current API available since 0.14 + +=item B + +Return the name of the temporary directory associated with this +object (if the object was created using the "newdir" constructor). + + $dirname = $tmpdir->dirname; + +This method is called automatically when the object is used in string context. + +=item B + +Control whether the file is unlinked when the object goes out of scope. +The file is removed if this value is true and $KEEP_ALL is not. + + $fh->unlink_on_destroy( 1 ); + +Default is for the file to be removed. + +Current API available since 0.15 + +=item B + +When the object goes out of scope, the destructor is called. This +destructor will attempt to unlink the file (using L) +if the constructor was called with UNLINK set to 1 (the default state +if UNLINK is not specified). + +No error is given if the unlink fails. + +If the object has been passed to a child process during a fork, the +file will be deleted when the object goes out of scope in the parent. + +For a temporary directory object the directory will be removed unless +the CLEANUP argument was used in the constructor (and set to false) or +C was modified after creation. Note that if a temp +directory is your current directory, it cannot be removed - a warning +will be given in this case. C out of the directory before +letting the object go out of scope. + +If the global variable $KEEP_ALL is true, the file or directory +will not be removed. + +=back + +=head1 FUNCTIONS + +This section describes the recommended interface for generating +temporary files and directories. + +=over 4 + +=item B + +This is the basic function to generate temporary files. +The behaviour of the file can be changed using various options: + + $fh = tempfile(); + ($fh, $filename) = tempfile(); + +Create a temporary file in the directory specified for temporary +files, as specified by the tmpdir() function in L. + + ($fh, $filename) = tempfile($template); + +Create a temporary file in the current directory using the supplied +template. Trailing `X' characters are replaced with random letters to +generate the filename. At least four `X' characters must be present +at the end of the template. + + ($fh, $filename) = tempfile($template, SUFFIX => $suffix) + +Same as previously, except that a suffix is added to the template +after the `X' translation. Useful for ensuring that a temporary +filename has a particular extension when needed by other applications. +But see the WARNING at the end. + + ($fh, $filename) = tempfile($template, DIR => $dir); + +Translates the template as before except that a directory name +is specified. + + ($fh, $filename) = tempfile($template, TMPDIR => 1); + +Equivalent to specifying a DIR of "File::Spec->tmpdir", writing the file +into the same temporary directory as would be used if no template was +specified at all. + + ($fh, $filename) = tempfile($template, UNLINK => 1); + +Return the filename and filehandle as before except that the file is +automatically removed when the program exits (dependent on +$KEEP_ALL). Default is for the file to be removed if a file handle is +requested and to be kept if the filename is requested. In a scalar +context (where no filename is returned) the file is always deleted +either (depending on the operating system) on exit or when it is +closed (unless $KEEP_ALL is true when the temp file is created). + +Use the object-oriented interface if fine-grained control of when +a file is removed is required. + +If the template is not specified, a template is always +automatically generated. This temporary file is placed in tmpdir() +(L) unless a directory is specified explicitly with the +DIR option. + + $fh = tempfile( DIR => $dir ); + +If called in scalar context, only the filehandle is returned and the +file will automatically be deleted when closed on operating systems +that support this (see the description of tmpfile() elsewhere in this +document). This is the preferred mode of operation, as if you only +have a filehandle, you can never create a race condition by fumbling +with the filename. On systems that can not unlink an open file or can +not mark a file as temporary when it is opened (for example, Windows +NT uses the C flag) the file is marked for deletion when +the program ends (equivalent to setting UNLINK to 1). The C +flag is ignored if present. + + (undef, $filename) = tempfile($template, OPEN => 0); + +This will return the filename based on the template but +will not open this file. Cannot be used in conjunction with +UNLINK set to true. Default is to always open the file +to protect from possible race conditions. A warning is issued +if warnings are turned on. Consider using the tmpnam() +and mktemp() functions described elsewhere in this document +if opening the file is not required. + +To open the temporary filehandle with O_EXLOCK (open with exclusive +file lock) use C<< EXLOCK=>1 >>. This is supported only by some +operating systems (most notably BSD derived systems). By default +EXLOCK will be false. Former C versions set EXLOCK to +true, so to be sure to get an unlocked filehandle also with older +versions, explicitly set C<< EXLOCK=>0 >>. + + ($fh, $filename) = tempfile($template, EXLOCK => 1); + +By default, the temp file is created with 0600 file permissions. +Use C to change this: + + ($fh, $filename) = tempfile($template, PERMS => 0666); + +Options can be combined as required. + +Will croak() if there is an error. + +Available since 0.05. + +UNLINK flag available since 0.10. + +TMPDIR flag available since 0.19. + +EXLOCK flag available since 0.19. + +PERMS flag available since 0.2310. + +=item B + +This is the recommended interface for creation of temporary +directories. By default the directory will not be removed on exit +(that is, it won't be temporary; this behaviour can not be changed +because of issues with backwards compatibility). To enable removal +either use the CLEANUP option which will trigger removal on program +exit, or consider using the "newdir" method in the object interface which +will allow the directory to be cleaned up when the object goes out of +scope. + +The behaviour of the function depends on the arguments: + + $tempdir = tempdir(); + +Create a directory in tmpdir() (see L). + + $tempdir = tempdir( $template ); + +Create a directory from the supplied template. This template is +similar to that described for tempfile(). `X' characters at the end +of the template are replaced with random letters to construct the +directory name. At least four `X' characters must be in the template. + + $tempdir = tempdir ( DIR => $dir ); + +Specifies the directory to use for the temporary directory. +The temporary directory name is derived from an internal template. + + $tempdir = tempdir ( $template, DIR => $dir ); + +Prepend the supplied directory name to the template. The template +should not include parent directory specifications itself. Any parent +directory specifications are removed from the template before +prepending the supplied directory. + + $tempdir = tempdir ( $template, TMPDIR => 1 ); + +Using the supplied template, create the temporary directory in +a standard location for temporary files. Equivalent to doing + + $tempdir = tempdir ( $template, DIR => File::Spec->tmpdir); + +but shorter. Parent directory specifications are stripped from the +template itself. The C option is ignored if C is set +explicitly. Additionally, C is implied if neither a template +nor a directory are supplied. + + $tempdir = tempdir( $template, CLEANUP => 1); + +Create a temporary directory using the supplied template, but +attempt to remove it (and all files inside it) when the program +exits. Note that an attempt will be made to remove all files from +the directory even if they were not created by this module (otherwise +why ask to clean it up?). The directory removal is made with +the rmtree() function from the L module. +Of course, if the template is not specified, the temporary directory +will be created in tmpdir() and will also be removed at program exit. + +Will croak() if there is an error. + +Current API available since 0.05. + +=back + +=head1 MKTEMP FUNCTIONS + +The following functions are Perl implementations of the +mktemp() family of temp file generation system calls. + +=over 4 + +=item B + +Given a template, returns a filehandle to the temporary file and the name +of the file. + + ($fh, $name) = mkstemp( $template ); + +In scalar context, just the filehandle is returned. + +The template may be any filename with some number of X's appended +to it, for example F. The trailing X's are replaced +with unique alphanumeric combinations. + +Will croak() if there is an error. + +Current API available since 0.05. + +=item B + +Similar to mkstemp(), except that an extra argument can be supplied +with a suffix to be appended to the template. + + ($fh, $name) = mkstemps( $template, $suffix ); + +For example a template of C and suffix of C<.dat> +would generate a file similar to F. + +Returns just the filehandle alone when called in scalar context. + +Will croak() if there is an error. + +Current API available since 0.05. + +=item B + +Create a directory from a template. The template must end in +X's that are replaced by the routine. + + $tmpdir_name = mkdtemp($template); + +Returns the name of the temporary directory created. + +Directory must be removed by the caller. + +Will croak() if there is an error. + +Current API available since 0.05. + +=item B + +Returns a valid temporary filename but does not guarantee +that the file will not be opened by someone else. + + $unopened_file = mktemp($template); + +Template is the same as that required by mkstemp(). + +Will croak() if there is an error. + +Current API available since 0.05. + +=back + +=head1 POSIX FUNCTIONS + +This section describes the re-implementation of the tmpnam() +and tmpfile() functions described in L +using the mkstemp() from this module. + +Unlike the L implementations, the directory used +for the temporary file is not specified in a system include +file (C) but simply depends on the choice of tmpdir() +returned by L. On some implementations this +location can be set using the C environment variable, which +may not be secure. +If this is a problem, simply use mkstemp() and specify a template. + +=over 4 + +=item B + +When called in scalar context, returns the full name (including path) +of a temporary file (uses mktemp()). The only check is that the file does +not already exist, but there is no guarantee that that condition will +continue to apply. + + $file = tmpnam(); + +When called in list context, a filehandle to the open file and +a filename are returned. This is achieved by calling mkstemp() +after constructing a suitable template. + + ($fh, $file) = tmpnam(); + +If possible, this form should be used to prevent possible +race conditions. + +See L for information on the choice of temporary +directory for a particular operating system. + +Will croak() if there is an error. + +Current API available since 0.05. + +=item B + +Returns the filehandle of a temporary file. + + $fh = tmpfile(); + +The file is removed when the filehandle is closed or when the program +exits. No access to the filename is provided. + +If the temporary file can not be created undef is returned. +Currently this command will probably not work when the temporary +directory is on an NFS file system. + +Will croak() if there is an error. + +Available since 0.05. + +Returning undef if unable to create file added in 0.12. + +=back + +=head1 ADDITIONAL FUNCTIONS + +These functions are provided for backwards compatibility +with common tempfile generation C library functions. + +They are not exported and must be addressed using the full package +name. + +=over 4 + +=item B + +Return the name of a temporary file in the specified directory +using a prefix. The file is guaranteed not to exist at the time +the function was called, but such guarantees are good for one +clock tick only. Always use the proper form of C +with C if you must open such a filename. + + $filename = File::Temp::tempnam( $dir, $prefix ); + +Equivalent to running mktemp() with $dir/$prefixXXXXXXXX +(using unix file convention as an example) + +Because this function uses mktemp(), it can suffer from race conditions. + +Will croak() if there is an error. + +Current API available since 0.05. + +=back + +=head1 UTILITY FUNCTIONS + +Useful functions for dealing with the filehandle and filename. + +=over 4 + +=item B + +Given an open filehandle and the associated filename, make a safe +unlink. This is achieved by first checking that the filename and +filehandle initially point to the same file and that the number of +links to the file is 1 (all fields returned by stat() are compared). +Then the filename is unlinked and the filehandle checked once again to +verify that the number of links on that file is now 0. This is the +closest you can come to making sure that the filename unlinked was the +same as the file whose descriptor you hold. + + unlink0($fh, $path) + or die "Error unlinking file $path safely"; + +Returns false on error but croaks() if there is a security +anomaly. The filehandle is not closed since on some occasions this is +not required. + +On some platforms, for example Windows NT, it is not possible to +unlink an open file (the file must be closed first). On those +platforms, the actual unlinking is deferred until the program ends and +good status is returned. A check is still performed to make sure that +the filehandle and filename are pointing to the same thing (but not at +the time the end block is executed since the deferred removal may not +have access to the filehandle). + +Additionally, on Windows NT not all the fields returned by stat() can +be compared. For example, the C and C fields seem to be +different. Also, it seems that the size of the file returned by stat() +does not always agree, with C being more accurate than +C, presumably because of caching issues even when +using autoflush (this is usually overcome by waiting a while after +writing to the tempfile before attempting to C it). + +Finally, on NFS file systems the link count of the file handle does +not always go to zero immediately after unlinking. Currently, this +command is expected to fail on NFS disks. + +This function is disabled if the global variable $KEEP_ALL is true +and an unlink on open file is supported. If the unlink is to be deferred +to the END block, the file is still registered for removal. + +This function should not be called if you are using the object oriented +interface since the it will interfere with the object destructor deleting +the file. + +Available Since 0.05. + +If can not unlink open file, defer removal until later available since 0.06. + +=item B + +Compare C of filehandle with C of provided filename. This +can be used to check that the filename and filehandle initially point +to the same file and that the number of links to the file is 1 (all +fields returned by stat() are compared). + + cmpstat($fh, $path) + or die "Error comparing handle with file"; + +Returns false if the stat information differs or if the link count is +greater than 1. Calls croak if there is a security anomaly. + +On certain platforms, for example Windows, not all the fields returned by stat() +can be compared. For example, the C and C fields seem to be +different in Windows. Also, it seems that the size of the file +returned by stat() does not always agree, with C being more +accurate than C, presumably because of caching issues +even when using autoflush (this is usually overcome by waiting a while +after writing to the tempfile before attempting to C it). + +Not exported by default. + +Current API available since 0.14. + +=item B + +Similar to C except after file comparison using cmpstat, the +filehandle is closed prior to attempting to unlink the file. This +allows the file to be removed without using an END block, but does +mean that the post-unlink comparison of the filehandle state provided +by C is not available. + + unlink1($fh, $path) + or die "Error closing and unlinking file"; + +Usually called from the object destructor when using the OO interface. + +Not exported by default. + +This function is disabled if the global variable $KEEP_ALL is true. + +Can call croak() if there is a security anomaly during the stat() +comparison. + +Current API available since 0.14. + +=item B + +Calling this function will cause any temp files or temp directories +that are registered for removal to be removed. This happens automatically +when the process exits but can be triggered manually if the caller is sure +that none of the temp files are required. This method can be registered as +an Apache callback. + +Note that if a temp directory is your current directory, it cannot be +removed. C out of the directory first before calling +C. (For the cleanup at program exit when the CLEANUP flag +is set, this happens automatically.) + +On OSes where temp files are automatically removed when the temp file +is closed, calling this function will have no effect other than to remove +temporary directories (which may include temporary files). + + File::Temp::cleanup(); + +Not exported by default. + +Current API available since 0.15. + +=back + +=head1 PACKAGE VARIABLES + +These functions control the global state of the package. + +=over 4 + +=item B + +Controls the lengths to which the module will go to check the safety of the +temporary file or directory before proceeding. +Options are: + +=over 8 + +=item STANDARD + +Do the basic security measures to ensure the directory exists and is +writable, that temporary files are opened only if they do not already +exist, and that possible race conditions are avoided. Finally the +L function is used to remove files safely. + +=item MEDIUM + +In addition to the STANDARD security, the output directory is checked +to make sure that it is owned either by root or the user running the +program. If the directory is writable by group or by other, it is then +checked to make sure that the sticky bit is set. + +Will not work on platforms that do not support the C<-k> test +for sticky bit. + +=item HIGH + +In addition to the MEDIUM security checks, also check for the +possibility of ``chown() giveaway'' using the L +sysconf() function. If this is a possibility, each directory in the +path is checked in turn for safeness, recursively walking back to the +root directory. + +For platforms that do not support the L +C<_PC_CHOWN_RESTRICTED> symbol (for example, Windows NT) it is +assumed that ``chown() giveaway'' is possible and the recursive test +is performed. + +=back + +The level can be changed as follows: + + File::Temp->safe_level( File::Temp::HIGH ); + +The level constants are not exported by the module. + +Currently, you must be running at least perl v5.6.0 in order to +run with MEDIUM or HIGH security. This is simply because the +safety tests use functions from L that are not +available in older versions of perl. The problem is that the version +number for Fcntl is the same in perl 5.6.0 and in 5.005_03 even though +they are different versions. + +On systems that do not support the HIGH or MEDIUM safety levels +(for example Win NT or OS/2) any attempt to change the level will +be ignored. The decision to ignore rather than raise an exception +allows portable programs to be written with high security in mind +for the systems that can support this without those programs failing +on systems where the extra tests are irrelevant. + +If you really need to see whether the change has been accepted +simply examine the return value of C. + + $newlevel = File::Temp->safe_level( File::Temp::HIGH ); + die "Could not change to high security" + if $newlevel != File::Temp::HIGH; + +Available since 0.05. + +=item TopSystemUID + +This is the highest UID on the current system that refers to a root +UID. This is used to make sure that the temporary directory is +owned by a system UID (C, C, C etc) rather than +simply by root. + +This is required since on many unix systems C is not owned +by root. + +Default is to assume that any UID less than or equal to 10 is a root +UID. + + File::Temp->top_system_uid(10); + my $topid = File::Temp->top_system_uid; + +This value can be adjusted to reduce security checking if required. +The value is only relevant when C is set to MEDIUM or higher. + +Available since 0.05. + +=item B<$KEEP_ALL> + +Controls whether temporary files and directories should be retained +regardless of any instructions in the program to remove them +automatically. This is useful for debugging but should not be used in +production code. + + $File::Temp::KEEP_ALL = 1; + +Default is for files to be removed as requested by the caller. + +In some cases, files will only be retained if this variable is true +when the file is created. This means that you can not create a temporary +file, set this variable and expect the temp file to still be around +when the program exits. + +=item B<$DEBUG> + +Controls whether debugging messages should be enabled. + + $File::Temp::DEBUG = 1; + +Default is for debugging mode to be disabled. + +Available since 0.15. + +=back + +=head1 WARNING + +For maximum security, endeavour always to avoid ever looking at, +touching, or even imputing the existence of the filename. You do not +know that that filename is connected to the same file as the handle +you have, and attempts to check this can only trigger more race +conditions. It's far more secure to use the filehandle alone and +dispense with the filename altogether. + +If you need to pass the handle to something that expects a filename +then on a unix system you can use C<"/dev/fd/" . fileno($fh)> for +arbitrary programs. Perl code that uses the 2-argument version of +C<< open >> can be passed C<< "+<=&" . fileno($fh) >>. Otherwise you +will need to pass the filename. You will have to clear the +close-on-exec bit on that file descriptor before passing it to another +process. + + use Fcntl qw/F_SETFD F_GETFD/; + fcntl($tmpfh, F_SETFD, 0) + or die "Can't clear close-on-exec flag on temp fh: $!\n"; + +=head2 Temporary files and NFS + +Some problems are associated with using temporary files that reside +on NFS file systems and it is recommended that a local filesystem +is used whenever possible. Some of the security tests will most probably +fail when the temp file is not local. Additionally, be aware that +the performance of I/O operations over NFS will not be as good as for +a local disk. + +=head2 Forking + +In some cases files created by File::Temp are removed from within an +END block. Since END blocks are triggered when a child process exits +(unless C is used by the child) File::Temp takes care +to only remove those temp files created by a particular process ID. This +means that a child will not attempt to remove temp files created by the +parent process. + +If you are forking many processes in parallel that are all creating +temporary files, you may need to reset the random number seed using +srand(EXPR) in each child else all the children will attempt to walk +through the same set of random file names and may well cause +themselves to give up if they exceed the number of retry attempts. + +=head2 Directory removal + +Note that if you have chdir'ed into the temporary directory and it is +subsequently cleaned up (either in the END block or as part of object +destruction), then you will get a warning from File::Path::rmtree(). + +=head2 Taint mode + +If you need to run code under taint mode, updating to the latest +L is highly recommended. On Windows, if the directory +given by L isn't writable, File::Temp will attempt +to fallback to the user's local application data directory or croak +with an error. + +=head2 BINMODE + +The file returned by File::Temp will have been opened in binary mode +if such a mode is available. If that is not correct, use the C +function to change the mode of the filehandle. + +Note that you can modify the encoding of a file opened by File::Temp +also by using C. + +=head1 HISTORY + +Originally began life in May 1999 as an XS interface to the system +mkstemp() function. In March 2000, the OpenBSD mkstemp() code was +translated to Perl for total control of the code's +security checking, to ensure the presence of the function regardless of +operating system and to help with portability. The module was shipped +as a standard part of perl from v5.6.1. + +Thanks to Tom Christiansen for suggesting that this module +should be written and providing ideas for code improvements and +security enhancements. + +=head1 SEE ALSO + +L, L, L, L + +See L and L, L for +different implementations of temporary file handling. + +See L for an alternative object-oriented wrapper for +the C function. + +=for Pod::Coverage STRINGIFY NUMIFY top_system_uid + +=head1 SUPPORT + +Bugs may be submitted through L +(or L). + +There is also a mailing list available for users of this distribution, at +L. + +There is also an irc channel available for users of this distribution, at +L on C|irc://irc.perl.org/#toolchain>. + +=head1 AUTHOR + +Tim Jenness + +=head1 CONTRIBUTORS + +=for stopwords Tim Jenness Karen Etheridge David Golden Slaven Rezic mohawk2 Roy Ivy III Peter Rabbitson Olivier Mengué John Acklam Gim Yee Nicolas R Brian Mowrey Dagfinn Ilmari Mannsåker Steinbrunner Ed Avis Guillem Jover James E. Keenan Kevin Ryde Ben Tilly + +=over 4 + +=item * + +Tim Jenness + +=item * + +Karen Etheridge + +=item * + +David Golden + +=item * + +Slaven Rezic + +=item * + +mohawk2 + +=item * + +Roy Ivy III + +=item * + +Peter Rabbitson + +=item * + +Olivier Mengué + +=item * + +Peter John Acklam + +=item * + +Tim Gim Yee + +=item * + +Nicolas R + +=item * + +Brian Mowrey + +=item * + +Dagfinn Ilmari Mannsåker + +=item * + +David Steinbrunner + +=item * + +Ed Avis + +=item * + +Guillem Jover + +=item * + +James E. Keenan + +=item * + +Kevin Ryde + +=item * + +Ben Tilly + +=back + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Tim Jenness and the UK Particle Physics and Astronomy Research Council. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/core_perl/File/stat.pm b/git/usr/share/perl5/core_perl/File/stat.pm new file mode 100644 index 0000000000000000000000000000000000000000..a2a2b09b56b770f2d3468868daee5899bcc9b38c --- /dev/null +++ b/git/usr/share/perl5/core_perl/File/stat.pm @@ -0,0 +1,350 @@ +package File::stat 1.14; +use v5.38; + +use warnings::register; +use Carp; +use constant _IS_CYGWIN => $^O eq "cygwin"; + +BEGIN { *warnif = \&warnings::warnif } + +our ( $st_dev, $st_ino, $st_mode, + $st_nlink, $st_uid, $st_gid, + $st_rdev, $st_size, + $st_atime, $st_mtime, $st_ctime, + $st_blksize, $st_blocks +); + +use Exporter 'import'; +our @EXPORT = qw(stat lstat); +our @fields = qw( $st_dev $st_ino $st_mode + $st_nlink $st_uid $st_gid + $st_rdev $st_size + $st_atime $st_mtime $st_ctime + $st_blksize $st_blocks + ); +our @EXPORT_OK = ( @fields, "stat_cando" ); +our %EXPORT_TAGS = ( FIELDS => [ @fields, @EXPORT ] ); + +use Fcntl qw(S_IRUSR S_IWUSR S_IXUSR); + +BEGIN { + # These constants will croak on use if the platform doesn't define + # them. It's important to avoid inflicting that on the user. + no strict 'refs'; + for (qw(suid sgid svtx)) { + my $val = eval { &{"Fcntl::S_I\U$_"} }; + *{"_$_"} = defined $val ? sub { $_[0] & $val ? 1 : "" } : sub { "" }; + } + for (qw(SOCK CHR BLK REG DIR LNK)) { + *{"S_IS$_"} = defined eval { &{"Fcntl::S_IF$_"} } + ? \&{"Fcntl::S_IS$_"} : sub { "" }; + } + # FIFO flag and macro don't quite follow the S_IF/S_IS pattern above + # RT #111638 + *{"S_ISFIFO"} = defined &Fcntl::S_IFIFO + ? \&Fcntl::S_ISFIFO : sub { "" }; +} + +# from doio.c +sub _ingroup { + my ($gid, $eff) = @_; + + # I am assuming that since VMS doesn't have getgroups(2), $) will + # always only contain a single entry. + $^O eq "VMS" and return $_[0] == $); + + my ($egid, @supp) = split " ", $); + my ($rgid) = split " ", $(; + + $gid == ($eff ? $egid : $rgid) and return 1; + grep $gid == $_, @supp and return 1; + + return ""; +} + +# VMS uses the Unix version of the routine, even though this is very +# suboptimal. VMS has a permissions structure that doesn't really fit +# into struct stat, and unlike on Win32 the normal -X operators respect +# that, but unfortunately by the time we get here we've already lost the +# information we need. It looks to me as though if we were to preserve +# the st_devnam entry of vmsish.h's fake struct stat (which actually +# holds the filename) it might be possible to do this right, but both +# getting that value out of the struct (perl's stat doesn't return it) +# and interpreting it later would require this module to have an XS +# component (at which point we might as well just call Perl_cando and +# have done with it). + +if (grep $^O eq $_, qw/os2 MSWin32/) { + + # from doio.c + *cando = sub { ($_[0][2] & $_[1]) ? 1 : "" }; +} +else { + + # from doio.c + *cando = sub { + my ($s, $mode, $eff) = @_; + my $uid = $eff ? $> : $<; + my ($stmode, $stuid, $stgid) = @$s[2,4,5]; + + # This code basically assumes that the rwx bits of the mode are + # the 0777 bits, but so does Perl_cando. + + if (_IS_CYGWIN ? _ingroup(544, $eff) : ($uid == 0 && $^O ne "VMS")) { + # If we're root on unix + # not testing for executable status => all file tests are true + return 1 if !($mode & 0111); + # testing for executable status => + # for a file, any x bit will do + # for a directory, always true + return 1 if $stmode & 0111 || S_ISDIR($stmode); + return ""; + } + + if ($stuid == $uid) { + $stmode & $mode and return 1; + } + elsif (_ingroup($stgid, $eff)) { + $stmode & ($mode >> 3) and return 1; + } + else { + $stmode & ($mode >> 6) and return 1; + } + return ""; + }; +} + +# alias for those who don't like objects +*stat_cando = \&cando; + +my %op = ( + r => sub { cando($_[0], S_IRUSR, 1) }, + w => sub { cando($_[0], S_IWUSR, 1) }, + x => sub { cando($_[0], S_IXUSR, 1) }, + o => sub { $_[0][4] == $> }, + + R => sub { cando($_[0], S_IRUSR, 0) }, + W => sub { cando($_[0], S_IWUSR, 0) }, + X => sub { cando($_[0], S_IXUSR, 0) }, + O => sub { $_[0][4] == $< }, + + e => sub { 1 }, + z => sub { $_[0][7] == 0 }, + s => sub { $_[0][7] }, + + f => sub { S_ISREG ($_[0][2]) }, + d => sub { S_ISDIR ($_[0][2]) }, + l => sub { S_ISLNK ($_[0][2]) }, + p => sub { S_ISFIFO($_[0][2]) }, + S => sub { S_ISSOCK($_[0][2]) }, + b => sub { S_ISBLK ($_[0][2]) }, + c => sub { S_ISCHR ($_[0][2]) }, + + u => sub { _suid($_[0][2]) }, + g => sub { _sgid($_[0][2]) }, + k => sub { _svtx($_[0][2]) }, + + M => sub { ($^T - $_[0][9] ) / 86400 }, + C => sub { ($^T - $_[0][10]) / 86400 }, + A => sub { ($^T - $_[0][8] ) / 86400 }, +); + +use constant HINT_FILETEST_ACCESS => 0x00400000; + +# we need fallback=>1 or stringifying breaks +use overload + fallback => 1, + -X => sub { + my ($s, $op) = @_; + + if (index("rwxRWX", $op) >= 0) { + (caller 0)[8] & HINT_FILETEST_ACCESS + and warnif("File::stat ignores use filetest 'access'"); + + $^O eq "VMS" and warnif("File::stat ignores VMS ACLs"); + + # It would be nice to have a warning about using -l on a + # non-lstat, but that would require an extra member in the + # object. + } + + if ($op{$op}) { + return $op{$op}->($_[0]); + } + else { + croak "-$op is not implemented on a File::stat object"; + } + }; + +use Class::Struct qw(struct); +struct 'File::stat' => [ + map { $_ => '$' } qw{ + dev ino mode nlink uid gid rdev size + atime mtime ctime blksize blocks + } +]; + +sub populate { + return unless @_; + my $stob = new(); + @$stob = ( + $st_dev, $st_ino, $st_mode, $st_nlink, $st_uid, $st_gid, $st_rdev, + $st_size, $st_atime, $st_mtime, $st_ctime, $st_blksize, $st_blocks ) + = @_; + return $stob; +} + +sub lstat :prototype($) { populate(CORE::lstat(shift)) } + +sub stat :prototype($) { + my $arg = shift; + my $st = populate(CORE::stat $arg); + return $st if defined $st; + my $fh; + { + local $!; + no strict 'refs'; + require Symbol; + $fh = \*{ Symbol::qualify( $arg, caller() )}; + return unless defined fileno $fh; + } + return populate(CORE::stat $fh); +} + +__END__ + +=head1 NAME + +File::stat - by-name interface to Perl's built-in stat() functions + +=head1 SYNOPSIS + + use File::stat; + my $st = stat($file) or die "No $file: $!"; + if ( ($st->mode & 0111) && ($st->nlink > 1) ) { + print "$file is executable with lotsa links\n"; + } + + if ( -x $st ) { + print "$file is executable\n"; + } + + use Fcntl "S_IRUSR"; + if ( $st->cando(S_IRUSR, 1) ) { + print "My effective uid can read $file\n"; + } + + use File::stat qw(:FIELDS); + stat($file) or die "No $file: $!"; + if ( ($st_mode & 0111) && ($st_nlink > 1) ) { + print "$file is executable with lotsa links\n"; + } + +=head1 DESCRIPTION + +This module's default exports override the core stat() +and lstat() functions, replacing them with versions that return +"File::stat" objects. This object has methods that +return the similarly named structure field name from the +stat(2) function; namely, +dev, +ino, +mode, +nlink, +uid, +gid, +rdev, +size, +atime, +mtime, +ctime, +blksize, +and +blocks. + +As of version 1.02 (provided with perl 5.12) the object provides C<"-X"> +overloading, so you can call filetest operators (C<-f>, C<-x>, and so +on) on it. It also provides a C<< ->cando >> method, called like + + $st->cando( ACCESS, EFFECTIVE ) + +where I is one of C, C or C from the +L module, and I indicates whether to use +effective (true) or real (false) ids. The method interprets the C, +C and C fields, and returns whether or not the current process +would be allowed the specified access. + +If you don't want to use the objects, you may import the C<< ->cando >> +method into your namespace as a regular function called C. +This takes an arrayref containing the return values of C or +C as its first argument, and interprets it for you. + +You may also import all the structure fields directly into your namespace +as regular variables using the :FIELDS import tag. (Note that this still +overrides your stat() and lstat() functions.) Access these fields as +variables named with a preceding C in front their method names. +Thus, C<$stat_obj-Edev()> corresponds to $st_dev if you import +the fields. + +To access this functionality without the core overrides, +pass the C an empty import list, and then access +function functions with their full qualified names. +On the other hand, the built-ins are still available +via the C pseudo-package. + +=head1 BUGS + +As of Perl 5.8.0 after using this module you cannot use the implicit +C<$_> or the special filehandle C<_> with stat() or lstat(), trying +to do so leads into strange errors. The workaround is for C<$_> to +be explicit + + my $stat_obj = stat $_; + +and for C<_> to explicitly populate the object using the unexported +and undocumented populate() function with CORE::stat(): + + my $stat_obj = File::stat::populate(CORE::stat(_)); + +=head1 ERRORS + +=over 4 + +=item -%s is not implemented on a File::stat object + +The filetest operators C<-t>, C<-T> and C<-B> are not implemented, as +they require more information than just a stat buffer. + +=back + +=head1 WARNINGS + +These can all be disabled with + + no warnings "File::stat"; + +=over 4 + +=item File::stat ignores use filetest 'access' + +You have tried to use one of the C<-rwxRWX> filetests with C in effect. C will ignore the pragma, and +just use the information in the C member as usual. + +=item File::stat ignores VMS ACLs + +VMS systems have a permissions structure that cannot be completely +represented in a stat buffer, and unlike on other systems the builtin +filetest operators respect this. The C overloads, however, +do not, since the information required is not available. + +=back + +=head1 NOTE + +While this class is currently implemented using the Class::Struct +module to build a struct-like class, you shouldn't rely upon this. + +=head1 AUTHOR + +Tom Christiansen diff --git a/git/usr/share/perl5/core_perl/Filter/Simple.pm b/git/usr/share/perl5/core_perl/Filter/Simple.pm new file mode 100644 index 0000000000000000000000000000000000000000..924c2aecbd3c87dd071a156c41d3ccdc54d61de8 --- /dev/null +++ b/git/usr/share/perl5/core_perl/Filter/Simple.pm @@ -0,0 +1,805 @@ +package Filter::Simple; + +use Text::Balanced ':ALL'; + +our $VERSION = '0.96'; + +use Filter::Util::Call; +use Carp; + +our @EXPORT = qw( FILTER FILTER_ONLY ); + + +sub import { + if (@_>1) { shift; goto &FILTER } + else { *{caller()."::$_"} = \&$_ foreach @EXPORT } +} + +sub fail { + croak "FILTER_ONLY: ", @_; +} + +my $exql = sub { + my @bits = extract_quotelike $_[0], qr//; + return unless $bits[0]; + return \@bits; +}; + +my $ncws = qr/\s+/; +my $comment = qr/(?()-]|\^[A-Z]?)\} + | (?:\$#?|[*\@\%]|\\&)\$*\s* + (?: \{\s*(?:\^(?=[A-Z_]))?(?:\w|::|'\w)*\s*\} + | (?:\^(?=[A-Z_]))?(?:\w|::|'\w)* + | (?=\{) # ${ block } + ) + ) + | \$\s*(?!::)(?:\d+|[][&`'#+*./|,";%=~:?!\@<>()-]|\^[A-Z]?) + }x; + +my %extractor_for = ( + quotelike => [ $ws, $variable, $id, { MATCH => \&extract_quotelike } ], + regex => [ $ws, $pod_or_DATA, $id, $exql ], + string => [ $ws, $pod_or_DATA, $id, $exql ], + code => [ $ws, { DONT_MATCH => $pod_or_DATA }, $variable, + $id, { DONT_MATCH => \&extract_quotelike } ], + code_no_comments + => [ { DONT_MATCH => $comment }, + $ncws, { DONT_MATCH => $pod_or_DATA }, $variable, + $id, { DONT_MATCH => \&extract_quotelike } ], + executable => [ $ws, { DONT_MATCH => $pod_or_DATA } ], + executable_no_comments + => [ { DONT_MATCH => $comment }, + $ncws, { DONT_MATCH => $pod_or_DATA } ], + all => [ { MATCH => qr/(?s:.*)/ } ], +); + +my %selector_for = ( + all => sub { my ($t)=@_; sub{ $_=$$_; $t->(@_); $_} }, + executable=> sub { my ($t)=@_; sub{ref() ? $_=$$_ : $t->(@_); $_} }, + executable_no_comments=> sub { my ($t)=@_; sub{ref() ? $_=$$_ : $t->(@_); $_} }, + quotelike => sub { my ($t)=@_; sub{ref() && do{$_=$$_; $t->(@_)}; $_} }, + regex => sub { my ($t)=@_; + sub{ref() or return $_; + my ($ql,undef,$pre,$op,$ld,$pat) = @$_; + return $_->[0] unless $op =~ /^(qr|m|s)/ + || !$op && ($ld eq '/' || $ld eq '?'); + $_ = $pat; + $t->(@_); + $ql =~ s/^(\s*\Q$op\E\s*\Q$ld\E)\Q$pat\E/$1$_/; + return "$pre$ql"; + }; + }, + string => sub { my ($t)=@_; + sub{ref() or return $_; + local *args = \@_; + my ($pre,$op,$ld1,$str1,$rd1,$ld2,$str2,$rd2,$flg) = @{$_}[2..10]; + return $_->[0] if $op =~ /^(qr|m)/ + || !$op && ($ld1 eq '/' || $ld1 eq '?'); + if (!$op || $op eq 'tr' || $op eq 'y') { + local *_ = \$str1; + $t->(@args); + } + if ($op =~ /^(tr|y|s)/) { + local *_ = \$str2; + $t->(@args); + } + my $result = "$pre$op$ld1$str1$rd1"; + $result .= $ld2 if $ld1 =~ m/[[({<]/; #])}> + $result .= "$str2$rd2$flg"; + return $result; + }; + }, +); + + +sub gen_std_filter_for { + my ($type, $transform) = @_; + return sub { + my $instr; + local @components; + for (extract_multiple($_,$extractor_for{$type})) { + if (ref()) { push @components, $_; $instr=0 } + elsif ($instr) { $components[-1] .= $_ } + else { push @components, $_; $instr=1 } + } + if ($type =~ /^code/) { + my $count = 0; + local $placeholder = qr/\Q$;\E(.{4})\Q$;\E/s; + my $extractor = qr/\Q$;\E(.{4})\Q$;\E/s; + $_ = join "", + map { ref $_ ? $;.pack('N',$count++).$; : $_ } + @components; + @components = grep { ref $_ } @components; + $transform->(@_); + s/$extractor/${$components[unpack('N',$1)]}/g; + } + else { + my $selector = $selector_for{$type}->($transform); + $_ = join "", map $selector->(@_), @components; + } + } +}; + +sub FILTER (&;$) { + my $caller = caller; + my ($filter, $terminator) = @_; + no warnings 'redefine'; + *{"${caller}::import"} = gen_filter_import($caller,$filter,$terminator); + *{"${caller}::unimport"} = gen_filter_unimport($caller); +} + +sub FILTER_ONLY { + my $caller = caller; + while (@_ > 1) { + my ($what, $how) = splice(@_, 0, 2); + fail "Unknown selector: $what" + unless exists $extractor_for{$what}; + fail "Filter for $what is not a subroutine reference" + unless ref $how eq 'CODE'; + push @transforms, gen_std_filter_for($what,$how); + } + my $terminator = shift; + + my $multitransform = sub { + foreach my $transform ( @transforms ) { + $transform->(@_); + } + }; + no warnings 'redefine'; + *{"${caller}::import"} = + gen_filter_import($caller,$multitransform,$terminator); + *{"${caller}::unimport"} = gen_filter_unimport($caller); +} + +my $ows = qr/(?:[ \t]+|#[^\n]*)*/; + +sub gen_filter_import { + my ($class, $filter, $terminator) = @_; + my %terminator; + my $prev_import = *{$class."::import"}{CODE}; + return sub { + my ($imported_class, @args) = @_; + my $def_terminator = + qr/^(?:\s*no\s+$imported_class\s*;$ows|__(?:END|DATA)__)\r?$/; + if (!defined $terminator) { + $terminator{terminator} = $def_terminator; + } + elsif (!ref $terminator || ref $terminator eq 'Regexp') { + $terminator{terminator} = $terminator; + } + elsif (ref $terminator ne 'HASH') { + croak "Terminator must be specified as scalar or hash ref" + } + elsif (!exists $terminator->{terminator}) { + $terminator{terminator} = $def_terminator; + } + filter_add( + sub { + my ($status, $lastline); + my $count = 0; + my $data = ""; + while ($status = filter_read()) { + return $status if $status < 0; + if ($terminator{terminator} && + m/$terminator{terminator}/) { + $lastline = $_; + $count++; + last; + } + $data .= $_; + $count++; + $_ = ""; + } + return $count if not $count; + $_ = $data; + $filter->($imported_class, @args) unless $status < 0; + if (defined $lastline) { + if (defined $terminator{becomes}) { + $_ .= $terminator{becomes}; + } + elsif ($lastline =~ $def_terminator) { + $_ .= $lastline; + } + } + return $count; + } + ); + if ($prev_import) { + goto &$prev_import; + } + elsif ($class->isa('Exporter')) { + $class->export_to_level(1,@_); + } + } +} + +sub gen_filter_unimport { + my ($class) = @_; + return sub { + filter_del(); + goto &$prev_unimport if $prev_unimport; + } +} + +1; + +__END__ + +=head1 NAME + +Filter::Simple - Simplified source filtering + +=head1 SYNOPSIS + + # in MyFilter.pm: + + package MyFilter; + + use Filter::Simple; + + FILTER { ... }; + + # or just: + # + # use Filter::Simple sub { ... }; + + # in user's code: + + use MyFilter; + + # this code is filtered + + no MyFilter; + + # this code is not + + +=head1 DESCRIPTION + +=head2 The Problem + +Source filtering is an immensely powerful feature of recent versions of Perl. +It allows one to extend the language itself (e.g. the Switch module), to +simplify the language (e.g. Language::Pythonesque), or to completely recast the +language (e.g. Lingua::Romana::Perligata). Effectively, it allows one to use +the full power of Perl as its own, recursively applied, macro language. + +The excellent Filter::Util::Call module (by Paul Marquess) provides a +usable Perl interface to source filtering, but it is often too powerful +and not nearly as simple as it could be. + +To use the module it is necessary to do the following: + +=over 4 + +=item 1. + +Download, build, and install the Filter::Util::Call module. +(If you have Perl 5.7.1 or later, this is already done for you.) + +=item 2. + +Set up a module that does a C. + +=item 3. + +Within that module, create an C subroutine. + +=item 4. + +Within the C subroutine do a call to C, passing +it either a subroutine reference. + +=item 5. + +Within the subroutine reference, call C or C +to "prime" $_ with source code data from the source file that will +C your module. Check the status value returned to see if any +source code was actually read in. + +=item 6. + +Process the contents of $_ to change the source code in the desired manner. + +=item 7. + +Return the status value. + +=item 8. + +If the act of unimporting your module (via a C) should cause source +code filtering to cease, create an C subroutine, and have it call +C. Make sure that the call to C or +C in step 5 will not accidentally read past the +C. Effectively this limits source code filters to line-by-line +operation, unless the C subroutine does some fancy +pre-pre-parsing of the source code it's filtering. + +=back + +For example, here is a minimal source code filter in a module named +BANG.pm. It simply converts every occurrence of the sequence C +to the sequence C in any piece of code following a +C statement (until the next C statement, if any): + + package BANG; + + use Filter::Util::Call ; + + sub import { + filter_add( sub { + my $caller = caller; + my ($status, $no_seen, $data); + while ($status = filter_read()) { + if (/^\s*no\s+$caller\s*;\s*?$/) { + $no_seen=1; + last; + } + $data .= $_; + $_ = ""; + } + $_ = $data; + s/BANG\s+BANG/die 'BANG' if \$BANG/g + unless $status < 0; + $_ .= "no $class;\n" if $no_seen; + return 1; + }) + } + + sub unimport { + filter_del(); + } + + 1 ; + +This level of sophistication puts filtering out of the reach of +many programmers. + + +=head2 A Solution + +The Filter::Simple module provides a simplified interface to +Filter::Util::Call; one that is sufficient for most common cases. + +Instead of the above process, with Filter::Simple the task of setting up +a source code filter is reduced to: + +=over 4 + +=item 1. + +Download and install the Filter::Simple module. +(If you have Perl 5.7.1 or later, this is already done for you.) + +=item 2. + +Set up a module that does a C and then +calls C. + +=item 3. + +Within the anonymous subroutine or block that is passed to +C, process the contents of $_ to change the source code in +the desired manner. + +=back + +In other words, the previous example, would become: + + package BANG; + use Filter::Simple; + + FILTER { + s/BANG\s+BANG/die 'BANG' if \$BANG/g; + }; + + 1 ; + +Note that the source code is passed as a single string, so any regex that +uses C<^> or C<$> to detect line boundaries will need the C flag. + +=head2 Disabling or changing behaviour + +By default, the installed filter only filters up to a line consisting of one of +the three standard source "terminators": + + no ModuleName; # optional comment + +or: + + __END__ + +or: + + __DATA__ + +but this can be altered by passing a second argument to C +or C (just remember: there's I comma after the initial block when +you use C). + +That second argument may be either a C'd regular expression (which is then +used to match the terminator line), or a defined false value (which indicates +that no terminator line should be looked for), or a reference to a hash +(in which case the terminator is the value associated with the key +C<'terminator'>. + +For example, to cause the previous filter to filter only up to a line of the +form: + + GNAB esu; + +you would write: + + package BANG; + use Filter::Simple; + + FILTER { + s/BANG\s+BANG/die 'BANG' if \$BANG/g; + } + qr/^\s*GNAB\s+esu\s*;\s*?$/; + +or: + + FILTER { + s/BANG\s+BANG/die 'BANG' if \$BANG/g; + } + { terminator => qr/^\s*GNAB\s+esu\s*;\s*?$/ }; + +and to prevent the filter's being turned off in any way: + + package BANG; + use Filter::Simple; + + FILTER { + s/BANG\s+BANG/die 'BANG' if \$BANG/g; + } + ""; # or: 0 + +or: + + FILTER { + s/BANG\s+BANG/die 'BANG' if \$BANG/g; + } + { terminator => "" }; + +B be contained on a single source line.> + + +=head2 All-in-one interface + +Separating the loading of Filter::Simple: + + use Filter::Simple; + +from the setting up of the filtering: + + FILTER { ... }; + +is useful because it allows other code (typically parser support code +or caching variables) to be defined before the filter is invoked. +However, there is often no need for such a separation. + +In those cases, it is easier to just append the filtering subroutine and +any terminator specification directly to the C statement that loads +Filter::Simple, like so: + + use Filter::Simple sub { + s/BANG\s+BANG/die 'BANG' if \$BANG/g; + }; + +This is exactly the same as: + + use Filter::Simple; + BEGIN { + Filter::Simple::FILTER { + s/BANG\s+BANG/die 'BANG' if \$BANG/g; + }; + } + +except that the C subroutine is not exported by Filter::Simple. + + +=head2 Filtering only specific components of source code + +One of the problems with a filter like: + + use Filter::Simple; + + FILTER { s/BANG\s+BANG/die 'BANG' if \$BANG/g }; + +is that it indiscriminately applies the specified transformation to +the entire text of your source program. So something like: + + warn 'BANG BANG, YOU'RE DEAD'; + BANG BANG; + +will become: + + warn 'die 'BANG' if $BANG, YOU'RE DEAD'; + die 'BANG' if $BANG; + +It is very common when filtering source to only want to apply the filter +to the non-character-string parts of the code, or alternatively to I +the character strings. + +Filter::Simple supports this type of filtering by automatically +exporting the C subroutine. + +C takes a sequence of specifiers that install separate +(and possibly multiple) filters that act on only parts of the source code. +For example: + + use Filter::Simple; + + FILTER_ONLY + code => sub { s/BANG\s+BANG/die 'BANG' if \$BANG/g }, + quotelike => sub { s/BANG\s+BANG/CHITTY CHITTY/g }; + +The C<"code"> subroutine will only be used to filter parts of the source +code that are not quotelikes, POD, or C<__DATA__>. The C +subroutine only filters Perl quotelikes (including here documents). + +The full list of alternatives is: + +=over + +=item C<"code"> + +Filters only those sections of the source code that are not quotelikes, POD, or +C<__DATA__>. + +=item C<"code_no_comments"> + +Filters only those sections of the source code that are not quotelikes, POD, +comments, or C<__DATA__>. + +=item C<"executable"> + +Filters only those sections of the source code that are not POD or C<__DATA__>. + +=item C<"executable_no_comments"> + +Filters only those sections of the source code that are not POD, comments, or C<__DATA__>. + +=item C<"quotelike"> + +Filters only Perl quotelikes (as interpreted by +C<&Text::Balanced::extract_quotelike>). + +=item C<"string"> + +Filters only the string literal parts of a Perl quotelike (i.e. the +contents of a string literal, either half of a C, the second +half of an C). + +=item C<"regex"> + +Filters only the pattern literal parts of a Perl quotelike (i.e. the +contents of a C or an C, the first half of an C). + +=item C<"all"> + +Filters everything. Identical in effect to C. + +=back + +Except for C<< FILTER_ONLY code => sub {...} >>, each of +the component filters is called repeatedly, once for each component +found in the source code. + +Note that you can also apply two or more of the same type of filter in +a single C. For example, here's a simple +macro-preprocessor that is only applied within regexes, +with a final debugging pass that prints the resulting source code: + + use Regexp::Common; + FILTER_ONLY + regex => sub { s/!\[/[^/g }, + regex => sub { s/%d/$RE{num}{int}/g }, + regex => sub { s/%f/$RE{num}{real}/g }, + all => sub { print if $::DEBUG }; + + + +=head2 Filtering only the code parts of source code + +Most source code ceases to be grammatically correct when it is broken up +into the pieces between string literals and regexes. So the C<'code'> +and C<'code_no_comments'> component filter behave slightly differently +from the other partial filters described in the previous section. + +Rather than calling the specified processor on each individual piece of +code (i.e. on the bits between quotelikes), the C<'code...'> partial +filters operate on the entire source code, but with the quotelike bits +(and, in the case of C<'code_no_comments'>, the comments) "blanked out". + +That is, a C<'code...'> filter I each quoted string, quotelike, +regex, POD, and __DATA__ section with a placeholder. The +delimiters of this placeholder are the contents of the C<$;> variable +at the time the filter is applied (normally C<"\034">). The remaining +four bytes are a unique identifier for the component being replaced. + +This approach makes it comparatively easy to write code preprocessors +without worrying about the form or contents of strings, regexes, etc. + +For convenience, during a C<'code...'> filtering operation, Filter::Simple +provides a package variable (C<$Filter::Simple::placeholder>) that +contains a pre-compiled regex that matches any placeholder...and +captures the identifier within the placeholder. Placeholders can be +moved and re-ordered within the source code as needed. + +In addition, a second package variable (C<@Filter::Simple::components>) +contains a list of the various pieces of C<$_>, as they were originally split +up to allow placeholders to be inserted. + +Once the filtering has been applied, the original strings, regexes, POD, +etc. are re-inserted into the code, by replacing each placeholder with +the corresponding original component (from C<@components>). Note that +this means that the C<@components> variable must be treated with extreme +care within the filter. The C<@components> array stores the "back- +translations" of each placeholder inserted into C<$_>, as well as the +interstitial source code between placeholders. If the placeholder +backtranslations are altered in C<@components>, they will be similarly +changed when the placeholders are removed from C<$_> after the filter +is complete. + +For example, the following filter detects concatenated pairs of +strings/quotelikes and reverses the order in which they are +concatenated: + + package DemoRevCat; + use Filter::Simple; + + FILTER_ONLY code => sub { + my $ph = $Filter::Simple::placeholder; + s{ ($ph) \s* [.] \s* ($ph) }{ $2.$1 }gx + }; + +Thus, the following code: + + use DemoRevCat; + + my $str = "abc" . q(def); + + print "$str\n"; + +would become: + + my $str = q(def)."abc"; + + print "$str\n"; + +and hence print: + + defabc + + +=head2 Using Filter::Simple with an explicit C subroutine + +Filter::Simple generates a special C subroutine for +your module (see L<"How it works">) which would normally replace any +C subroutine you might have explicitly declared. + +However, Filter::Simple is smart enough to notice your existing +C and Do The Right Thing with it. +That is, if you explicitly define an C subroutine in a package +that's using Filter::Simple, that C subroutine will still +be invoked immediately after any filter you install. + +The only thing you have to remember is that the C subroutine +I be declared I the filter is installed. If you use C +to install the filter: + + package Filter::TurnItUpTo11; + + use Filter::Simple; + + FILTER { s/(\w+)/\U$1/ }; + +that will almost never be a problem, but if you install a filtering +subroutine by passing it directly to the C +statement: + + package Filter::TurnItUpTo11; + + use Filter::Simple sub{ s/(\w+)/\U$1/ }; + +then you must make sure that your C subroutine appears before +that C statement. + + +=head2 Using Filter::Simple and Exporter together + +Likewise, Filter::Simple is also smart enough +to Do The Right Thing if you use Exporter: + + package Switch; + use base Exporter; + use Filter::Simple; + + @EXPORT = qw(switch case); + @EXPORT_OK = qw(given when); + + FILTER { $_ = magic_Perl_filter($_) } + +Immediately after the filter has been applied to the source, +Filter::Simple will pass control to Exporter, so it can do its magic too. + +Of course, here too, Filter::Simple has to know you're using Exporter +before it applies the filter. That's almost never a problem, but if you're +nervous about it, you can guarantee that things will work correctly by +ensuring that your C always precedes your +C. + + +=head2 How it works + +The Filter::Simple module exports into the package that calls C +(or Cs it directly) -- such as package "BANG" in the above example -- +two automagically constructed +subroutines -- C and C -- which take care of all the +nasty details. + +In addition, the generated C subroutine passes its own argument +list to the filtering subroutine, so the BANG.pm filter could easily +be made parametric: + + package BANG; + + use Filter::Simple; + + FILTER { + my ($die_msg, $var_name) = @_; + s/BANG\s+BANG/die '$die_msg' if \${$var_name}/g; + }; + + # and in some user code: + + use BANG "BOOM", "BAM"; # "BANG BANG" becomes: die 'BOOM' if $BAM + + +The specified filtering subroutine is called every time a C is +encountered, and passed all the source code following that call, up to +either the next C (or whatever terminator you've set) or the +end of the source file, whichever occurs first. By default, any C call must appear by itself on a separate line, or it is ignored. + + +=head1 AUTHOR + +Damian Conway + +=head1 CONTACT + +Filter::Simple is now maintained by the Perl5-Porters. +Please submit bug via the C tool that comes with your perl. +For usage instructions, read C or possibly C. +For mostly anything else, please contact Eperl5-porters@perl.orgE. + +Maintainer of the CPAN release is Steffen Mueller Esmueller@cpan.orgE. +Contact him with technical difficulties with respect to the packaging of the +CPAN module. + +Praise of the module, flowers, and presents still go to the author, +Damian Conway Edamian@conway.orgE. + +=head1 COPYRIGHT AND LICENSE + + Copyright (c) 2000-2014, Damian Conway. All Rights Reserved. + This module is free software. It may be used, redistributed + and/or modified under the same terms as Perl itself. diff --git a/git/usr/share/perl5/core_perl/Getopt/Long.pm b/git/usr/share/perl5/core_perl/Getopt/Long.pm new file mode 100644 index 0000000000000000000000000000000000000000..cc97aa20fc807194764c390425527d63110194a7 --- /dev/null +++ b/git/usr/share/perl5/core_perl/Getopt/Long.pm @@ -0,0 +1,2749 @@ +#! perl + +# Getopt::Long.pm -- Universal options parsing +# Author : Johan Vromans +# Created On : Tue Sep 11 15:00:12 1990 +# Last Modified On: Tue Jun 11 13:18:11 2024 +# Update Count : 1811 +# Status : Released + +################ Module Preamble ################ + +# Getopt::Long is reported to run under 5.6.1. Thanks Tux! +use 5.006001; + +use strict; +use warnings; + +package Getopt::Long; + +# Must match Getopt::Long::Parser::VERSION! +our $VERSION = 2.58; + +use Exporter; +use base qw(Exporter); + +# Exported subroutines. +sub GetOptions(@); # always +sub GetOptionsFromArray(@); # on demand +sub GetOptionsFromString(@); # on demand +sub Configure(@); # on demand +sub HelpMessage(@); # on demand +sub VersionMessage(@); # in demand + +our @EXPORT; +our @EXPORT_OK; +# Values for $order. See GNU getopt.c for details. +our ($REQUIRE_ORDER, $PERMUTE, $RETURN_IN_ORDER); +BEGIN { + ($REQUIRE_ORDER, $PERMUTE, $RETURN_IN_ORDER) = (0..2); + @EXPORT = qw(&GetOptions $REQUIRE_ORDER $PERMUTE $RETURN_IN_ORDER); + @EXPORT_OK = qw(&HelpMessage &VersionMessage &Configure + &GetOptionsFromArray &GetOptionsFromString); +} + +# User visible variables. +our ($error, $debug, $major_version, $minor_version); +# Deprecated visible variables. +our ($autoabbrev, $getopt_compat, $ignorecase, $bundling, $order, + $passthrough); +# Official invisible variables. +our ($genprefix, $caller, $gnu_compat, $auto_help, $auto_version, $longprefix); + +# Really invisible variables. +my $bundling_values; + +# Public subroutines. +sub config(@); # deprecated name + +# Private subroutines. +sub ConfigDefaults(); +sub ParseOptionSpec($$); +sub OptCtl($); +sub FindOption($$$$$); +sub ValidValue ($$$$$); + +################ Local Variables ################ + +# $requested_version holds the version that was mentioned in the 'use' +# or 'require', if any. It can be used to enable or disable specific +# features. +my $requested_version = 0; + +################ Resident subroutines ################ + +sub ConfigDefaults() { + # Handle POSIX compliancy. + if ( defined $ENV{"POSIXLY_CORRECT"} ) { + $genprefix = "(--|-)"; + $autoabbrev = 0; # no automatic abbrev of options + $bundling = 0; # no bundling of single letter switches + $getopt_compat = 0; # disallow '+' to start options + $order = $REQUIRE_ORDER; + } + else { + $genprefix = "(--|-|\\+)"; + $autoabbrev = 1; # automatic abbrev of options + $bundling = 0; # bundling off by default + $getopt_compat = 1; # allow '+' to start options + $order = $PERMUTE; + } + # Other configurable settings. + $debug = 0; # for debugging + $error = 0; # error tally + $ignorecase = 1; # ignore case when matching options + $passthrough = 0; # leave unrecognized options alone + $gnu_compat = 0; # require --opt=val if value is optional + $longprefix = "(--)"; # what does a long prefix look like + $bundling_values = 0; # no bundling of values +} + +# Override import. +sub import { + my $pkg = shift; # package + my @syms = (); # symbols to import + my @config = (); # configuration + my $dest = \@syms; # symbols first + for ( @_ ) { + if ( $_ eq ':config' ) { + $dest = \@config; # config next + next; + } + push(@$dest, $_); # push + } + # Hide one level and call super. + local $Exporter::ExportLevel = 1; + push(@syms, qw(&GetOptions)) if @syms; # always export GetOptions + $requested_version = 0; + $pkg->SUPER::import(@syms); + # And configure. + Configure(@config) if @config; +} + +################ Initialization ################ + +# Version major/minor numbers. +($major_version, $minor_version) = $VERSION =~ /^(\d+)\.(\d+)/; + +ConfigDefaults(); + +# Store a copy of the default configuration. Since ConfigDefaults has +# just been called, what we get from Configure is the default. +my $default_config = do { + Getopt::Long::Configure () +}; + +# For the parser only. +sub _default_config { $default_config } + +################ Back to Normal ################ + +# The ooparser was traditionally part of the main package. +no warnings 'redefine'; +sub Getopt::Long::Parser::new { + require Getopt::Long::Parser; + goto &Getopt::Long::Parser::new; +} +use warnings 'redefine'; + +# Indices in option control info. +# Note that ParseOptions uses the fields directly. Search for 'hard-wired'. +use constant CTL_TYPE => 0; +#use constant CTL_TYPE_FLAG => ''; +#use constant CTL_TYPE_NEG => '!'; +#use constant CTL_TYPE_INCR => '+'; +#use constant CTL_TYPE_INT => 'i'; +#use constant CTL_TYPE_INTINC => 'I'; +#use constant CTL_TYPE_XINT => 'o'; +#use constant CTL_TYPE_FLOAT => 'f'; +#use constant CTL_TYPE_STRING => 's'; + +use constant CTL_CNAME => 1; + +use constant CTL_DEFAULT => 2; + +use constant CTL_DEST => 3; + use constant CTL_DEST_SCALAR => 0; + use constant CTL_DEST_ARRAY => 1; + use constant CTL_DEST_HASH => 2; + use constant CTL_DEST_CODE => 3; + +use constant CTL_AMIN => 4; +use constant CTL_AMAX => 5; + +# FFU. +#use constant CTL_RANGE => ; +#use constant CTL_REPEAT => ; + +# Rather liberal patterns to match numbers. +use constant PAT_INT => "[-+]?_*[0-9][0-9_]*"; +use constant PAT_XINT => + "(?:". + "[-+]?_*[1-9][0-9_]*". + "|". + "0x_*[0-9a-f][0-9a-f_]*". + "|". + "0b_*[01][01_]*". + "|". + "0[0-7_]*". + ")"; +use constant PAT_FLOAT => + "[-+]?". # optional sign + "(?=\\.?[0-9])". # must start with digit or dec.point + "[0-9_]*". # digits before the dec.point + "(\\.[0-9_]*)?". # optional fraction + "([eE][-+]?[0-9_]+)?"; # optional exponent + +sub GetOptions(@) { + # Shift in default array. + unshift(@_, \@ARGV); + # Try to keep caller() and Carp consistent. + goto &GetOptionsFromArray; +} + +sub GetOptionsFromString(@) { + my ($string) = shift; + require Text::ParseWords; + my $args = [ Text::ParseWords::shellwords($string) ]; + $caller ||= (caller)[0]; # current context + my $ret = GetOptionsFromArray($args, @_); + return ( $ret, $args ) if wantarray; + if ( @$args ) { + $ret = 0; + warn("GetOptionsFromString: Excess data \"@$args\" in string \"$string\"\n"); + } + $ret; +} + +sub GetOptionsFromArray(@) { + + my ($argv, @optionlist) = @_; # local copy of the option descriptions + my $argend = '--'; # option list terminator + my %opctl = (); # table of option specs + my $pkg = $caller || (caller)[0]; # current context + # Needed if linkage is omitted. + my @ret = (); # accum for non-options + my %linkage; # linkage + my $userlinkage; # user supplied HASH + my $opt; # current option + my $prefix = $genprefix; # current prefix + + $error = ''; + + if ( $debug ) { + # Avoid some warnings if debugging. + local ($^W) = 0; + print STDERR + ("Getopt::Long $VERSION ", + "called from package \"$pkg\".", + "\n ", + "argv: ", + defined($argv) + ? UNIVERSAL::isa( $argv, 'ARRAY' ) ? "(@$argv)" : $argv + : "", + "\n ", + "autoabbrev=$autoabbrev,". + "bundling=$bundling,", + "bundling_values=$bundling_values,", + "getopt_compat=$getopt_compat,", + "gnu_compat=$gnu_compat,", + "order=$order,", + "\n ", + "ignorecase=$ignorecase,", + "requested_version=$requested_version,", + "passthrough=$passthrough,", + "genprefix=\"$genprefix\",", + "longprefix=\"$longprefix\".", + "\n"); + } + + # Check for ref HASH as first argument. + # First argument may be an object. It's OK to use this as long + # as it is really a hash underneath. + $userlinkage = undef; + if ( @optionlist && ref($optionlist[0]) and + UNIVERSAL::isa($optionlist[0],'HASH') ) { + $userlinkage = shift (@optionlist); + print STDERR ("=> user linkage: $userlinkage\n") if $debug; + } + + # See if the first element of the optionlist contains option + # starter characters. + # Be careful not to interpret '<>' as option starters. + if ( @optionlist && $optionlist[0] =~ /^\W+$/ + && !($optionlist[0] eq '<>' + && @optionlist > 0 + && ref($optionlist[1])) ) { + $prefix = shift (@optionlist); + # Turn into regexp. Needs to be parenthesized! + $prefix =~ s/(\W)/\\$1/g; + $prefix = "([" . $prefix . "])"; + print STDERR ("=> prefix=\"$prefix\"\n") if $debug; + } + + # Verify correctness of optionlist. + %opctl = (); + while ( @optionlist ) { + my $opt = shift (@optionlist); + + unless ( defined($opt) ) { + $error .= "Undefined argument in option spec\n"; + next; + } + + # Strip leading prefix so people can specify "--foo=i" if they like. + $opt = $+ if $opt =~ /^$prefix+(.*)$/s; + + if ( $opt eq '<>' ) { + if ( (defined $userlinkage) + && !(@optionlist > 0 && ref($optionlist[0])) + && (exists $userlinkage->{$opt}) + && ref($userlinkage->{$opt}) ) { + unshift (@optionlist, $userlinkage->{$opt}); + } + unless ( @optionlist > 0 + && ref($optionlist[0]) && ref($optionlist[0]) eq 'CODE' ) { + $error .= "Option spec <> requires a reference to a subroutine\n"; + # Kill the linkage (to avoid another error). + shift (@optionlist) + if @optionlist && ref($optionlist[0]); + next; + } + $linkage{'<>'} = shift (@optionlist); + next; + } + + # Parse option spec. + my ($name, $orig) = ParseOptionSpec ($opt, \%opctl); + unless ( defined $name ) { + # Failed. $orig contains the error message. Sorry for the abuse. + $error .= $orig; + # Kill the linkage (to avoid another error). + shift (@optionlist) + if @optionlist && ref($optionlist[0]); + next; + } + + # If no linkage is supplied in the @optionlist, copy it from + # the userlinkage if available. + if ( defined $userlinkage ) { + unless ( @optionlist > 0 && ref($optionlist[0]) ) { + if ( exists $userlinkage->{$orig} && + ref($userlinkage->{$orig}) ) { + print STDERR ("=> found userlinkage for \"$orig\": ", + "$userlinkage->{$orig}\n") + if $debug; + unshift (@optionlist, $userlinkage->{$orig}); + } + else { + # Do nothing. Being undefined will be handled later. + next; + } + } + } + + # Copy the linkage. If omitted, link to global variable. + if ( @optionlist > 0 && ref($optionlist[0]) ) { + print STDERR ("=> link \"$orig\" to $optionlist[0]\n") + if $debug; + my $rl = ref($linkage{$orig} = shift (@optionlist)); + + if ( $rl eq "ARRAY" ) { + $opctl{$name}[CTL_DEST] = CTL_DEST_ARRAY; + } + elsif ( $rl eq "HASH" ) { + $opctl{$name}[CTL_DEST] = CTL_DEST_HASH; + } + elsif ( $rl eq "SCALAR" || $rl eq "REF" ) { +# if ( $opctl{$name}[CTL_DEST] == CTL_DEST_ARRAY ) { +# my $t = $linkage{$orig}; +# $$t = $linkage{$orig} = []; +# } +# elsif ( $opctl{$name}[CTL_DEST] == CTL_DEST_HASH ) { +# } +# else { + # Ok. +# } + } + elsif ( $rl eq "CODE" ) { + # Ok. + } + else { + $error .= "Invalid option linkage for \"$opt\"\n"; + } + } + else { + # Link to global $opt_XXX variable. + # Make sure a valid perl identifier results. + my $ov = $orig; + $ov =~ s/\W/_/g; + if ( $opctl{$name}[CTL_DEST] == CTL_DEST_ARRAY ) { + print STDERR ("=> link \"$orig\" to \@$pkg","::opt_$ov\n") + if $debug; + eval ("\$linkage{\$orig} = \\\@".$pkg."::opt_$ov;"); + } + elsif ( $opctl{$name}[CTL_DEST] == CTL_DEST_HASH ) { + print STDERR ("=> link \"$orig\" to \%$pkg","::opt_$ov\n") + if $debug; + eval ("\$linkage{\$orig} = \\\%".$pkg."::opt_$ov;"); + } + else { + print STDERR ("=> link \"$orig\" to \$$pkg","::opt_$ov\n") + if $debug; + eval ("\$linkage{\$orig} = \\\$".$pkg."::opt_$ov;"); + } + } + + if ( $opctl{$name}[CTL_TYPE] eq 'I' + && ( $opctl{$name}[CTL_DEST] == CTL_DEST_ARRAY + || $opctl{$name}[CTL_DEST] == CTL_DEST_HASH ) + ) { + $error .= "Invalid option linkage for \"$opt\"\n"; + } + + } + + $error .= "GetOptionsFromArray: 1st parameter is not an array reference\n" + unless $argv && UNIVERSAL::isa( $argv, 'ARRAY' ); + + # Bail out if errors found. + die ($error) if $error; + $error = 0; + + # Supply --version and --help support, if needed and allowed. + if ( defined($auto_version) ? $auto_version : ($requested_version >= 2.3203) ) { + if ( !defined($opctl{version}) ) { + $opctl{version} = ['','version',0,CTL_DEST_CODE,undef]; + $linkage{version} = \&VersionMessage; + } + $auto_version = 1; + } + if ( defined($auto_help) ? $auto_help : ($requested_version >= 2.3203) ) { + if ( !defined($opctl{help}) && !defined($opctl{'?'}) ) { + $opctl{help} = $opctl{'?'} = ['','help',0,CTL_DEST_CODE,undef]; + $linkage{help} = \&HelpMessage; + } + $auto_help = 1; + } + + # Show the options tables if debugging. + if ( $debug ) { + my ($arrow, $k, $v); + $arrow = "=> "; + while ( ($k,$v) = each(%opctl) ) { + print STDERR ($arrow, "\$opctl{$k} = $v ", OptCtl($v), "\n"); + $arrow = " "; + } + } + + # Process argument list + my $goon = 1; + while ( $goon && @$argv > 0 ) { + + # Get next argument. + $opt = shift (@$argv); + print STDERR ("=> arg \"", $opt, "\"\n") if $debug; + + # Double dash is option list terminator. + if ( defined($opt) && $opt eq $argend ) { + push (@ret, $argend) if $passthrough; + last; + } + + # Look it up. + my $tryopt = $opt; + my $found; # success status + my $key; # key (if hash type) + my $arg; # option argument + my $ctl; # the opctl entry + my $starter; # the actual starter character(s) + + ($found, $opt, $ctl, $starter, $arg, $key) = + FindOption ($argv, $prefix, $argend, $opt, \%opctl); + + if ( $found ) { + + # FindOption undefines $opt in case of errors. + next unless defined $opt; + + my $argcnt = 0; + while ( defined $arg ) { + + # Get the canonical name. + my $given = $opt; + print STDERR ("=> cname for \"$opt\" is ") if $debug; + $opt = $ctl->[CTL_CNAME]; + print STDERR ("\"$ctl->[CTL_CNAME]\"\n") if $debug; + + if ( defined $linkage{$opt} ) { + print STDERR ("=> ref(\$L{$opt}) -> ", + ref($linkage{$opt}), "\n") if $debug; + + if ( ref($linkage{$opt}) eq 'SCALAR' + || ref($linkage{$opt}) eq 'REF' ) { + if ( $ctl->[CTL_TYPE] eq '+' ) { + print STDERR ("=> \$\$L{$opt} += \"$arg\"\n") + if $debug; + if ( defined ${$linkage{$opt}} ) { + ${$linkage{$opt}} += $arg; + } + else { + ${$linkage{$opt}} = $arg; + } + } + elsif ( $ctl->[CTL_DEST] == CTL_DEST_ARRAY ) { + print STDERR ("=> ref(\$L{$opt}) auto-vivified", + " to ARRAY\n") + if $debug; + my $t = $linkage{$opt}; + $$t = $linkage{$opt} = []; + print STDERR ("=> push(\@{\$L{$opt}, \"$arg\")\n") + if $debug; + push (@{$linkage{$opt}}, $arg); + } + elsif ( $ctl->[CTL_DEST] == CTL_DEST_HASH ) { + print STDERR ("=> ref(\$L{$opt}) auto-vivified", + " to HASH\n") + if $debug; + my $t = $linkage{$opt}; + $$t = $linkage{$opt} = {}; + print STDERR ("=> \$\$L{$opt}->{$key} = \"$arg\"\n") + if $debug; + $linkage{$opt}->{$key} = $arg; + } + else { + print STDERR ("=> \$\$L{$opt} = \"$arg\"\n") + if $debug; + ${$linkage{$opt}} = $arg; + } + } + elsif ( ref($linkage{$opt}) eq 'ARRAY' ) { + print STDERR ("=> push(\@{\$L{$opt}, \"$arg\")\n") + if $debug; + push (@{$linkage{$opt}}, $arg); + } + elsif ( ref($linkage{$opt}) eq 'HASH' ) { + print STDERR ("=> \$\$L{$opt}->{$key} = \"$arg\"\n") + if $debug; + $linkage{$opt}->{$key} = $arg; + } + elsif ( ref($linkage{$opt}) eq 'CODE' ) { + print STDERR ("=> &L{$opt}(\"$opt\"", + $ctl->[CTL_DEST] == CTL_DEST_HASH ? ", \"$key\"" : "", + ", \"$arg\")\n") + if $debug; + my $eval_error = do { + local $@; + local $SIG{__DIE__} = 'DEFAULT'; + eval { + &{$linkage{$opt}} + (Getopt::Long::CallBack->new + (name => $opt, + given => $given, + ctl => $ctl, + opctl => \%opctl, + linkage => \%linkage, + prefix => $prefix, + starter => $starter, + ), + $ctl->[CTL_DEST] == CTL_DEST_HASH ? ($key) : (), + $arg); + }; + $@; + }; + print STDERR ("=> die($eval_error)\n") + if $debug && $eval_error ne ''; + if ( $eval_error =~ /^!/ ) { + if ( $eval_error =~ /^!FINISH\b/ ) { + $goon = 0; + } + } + elsif ( $eval_error ne '' ) { + warn ($eval_error); + $error++; + } + } + else { + print STDERR ("Invalid REF type \"", ref($linkage{$opt}), + "\" in linkage\n"); + die("Getopt::Long -- internal error!\n"); + } + } + # No entry in linkage means entry in userlinkage. + elsif ( $ctl->[CTL_DEST] == CTL_DEST_ARRAY ) { + if ( defined $userlinkage->{$opt} ) { + print STDERR ("=> push(\@{\$L{$opt}}, \"$arg\")\n") + if $debug; + push (@{$userlinkage->{$opt}}, $arg); + } + else { + print STDERR ("=>\$L{$opt} = [\"$arg\"]\n") + if $debug; + $userlinkage->{$opt} = [$arg]; + } + } + elsif ( $ctl->[CTL_DEST] == CTL_DEST_HASH ) { + if ( defined $userlinkage->{$opt} ) { + print STDERR ("=> \$L{$opt}->{$key} = \"$arg\"\n") + if $debug; + $userlinkage->{$opt}->{$key} = $arg; + } + else { + print STDERR ("=>\$L{$opt} = {$key => \"$arg\"}\n") + if $debug; + $userlinkage->{$opt} = {$key => $arg}; + } + } + else { + if ( $ctl->[CTL_TYPE] eq '+' ) { + print STDERR ("=> \$L{$opt} += \"$arg\"\n") + if $debug; + if ( defined $userlinkage->{$opt} ) { + $userlinkage->{$opt} += $arg; + } + else { + $userlinkage->{$opt} = $arg; + } + } + else { + print STDERR ("=>\$L{$opt} = \"$arg\"\n") if $debug; + $userlinkage->{$opt} = $arg; + } + } + + $argcnt++; + last if $argcnt >= $ctl->[CTL_AMAX] && $ctl->[CTL_AMAX] != -1; + undef($arg); + + # Need more args? + if ( $argcnt < $ctl->[CTL_AMIN] ) { + if ( @$argv ) { + if ( ValidValue($ctl, $argv->[0], 1, $argend, $prefix) ) { + $arg = shift(@$argv); + if ( $ctl->[CTL_TYPE] =~ /^[iIo]$/ ) { + $arg =~ tr/_//d; + $arg = $ctl->[CTL_TYPE] eq 'o' && $arg =~ /^0/ + ? oct($arg) + : 0+$arg + } + ($key,$arg) = $arg =~ /^([^=]+)=(.*)/ + if $ctl->[CTL_DEST] == CTL_DEST_HASH; + next; + } + warn("Value \"$$argv[0]\" invalid for option $opt\n"); + $error++; + } + else { + warn("Insufficient arguments for option $opt\n"); + $error++; + } + } + + # Any more args? + if ( @$argv && ValidValue($ctl, $argv->[0], 0, $argend, $prefix) ) { + $arg = shift(@$argv); + if ( $ctl->[CTL_TYPE] =~ /^[iIo]$/ ) { + $arg =~ tr/_//d; + $arg = $ctl->[CTL_TYPE] eq 'o' && $arg =~ /^0/ + ? oct($arg) + : 0+$arg + } + ($key,$arg) = $arg =~ /^([^=]+)=(.*)/ + if $ctl->[CTL_DEST] == CTL_DEST_HASH; + next; + } + } + } + + # Not an option. Save it if we $PERMUTE and don't have a <>. + elsif ( $order == $PERMUTE ) { + # Try non-options call-back. + my $cb; + if ( defined ($cb = $linkage{'<>'}) ) { + print STDERR ("=> &L{$tryopt}(\"$tryopt\")\n") + if $debug; + my $eval_error = do { + local $@; + local $SIG{__DIE__} = 'DEFAULT'; + eval { + # The arg to <> cannot be the CallBack object + # since it may be passed to other modules that + # get confused (e.g., Archive::Tar). Well, + # it's not relevant for this callback anyway. + &$cb($tryopt); + }; + $@; + }; + print STDERR ("=> die($eval_error)\n") + if $debug && $eval_error ne ''; + if ( $eval_error =~ /^!/ ) { + if ( $eval_error =~ /^!FINISH\b/ ) { + $goon = 0; + } + } + elsif ( $eval_error ne '' ) { + warn ($eval_error); + $error++; + } + } + else { + print STDERR ("=> saving \"$tryopt\" ", + "(not an option, may permute)\n") if $debug; + push (@ret, $tryopt); + } + next; + } + + # ...otherwise, terminate. + else { + # Push this one back and exit. + unshift (@$argv, $tryopt); + return ($error == 0); + } + + } + + # Finish. + if ( @ret && ( $order == $PERMUTE || $passthrough ) ) { + # Push back accumulated arguments + print STDERR ("=> restoring \"", join('" "', @ret), "\"\n") + if $debug; + unshift (@$argv, @ret); + } + + return ($error == 0); +} + +# A readable representation of what's in an optbl. +sub OptCtl ($) { + my ($v) = @_; + my @v = map { defined($_) ? ($_) : ("") } @$v; + "[". + join(",", + "\"$v[CTL_TYPE]\"", + "\"$v[CTL_CNAME]\"", + "\"$v[CTL_DEFAULT]\"", + ("\$","\@","\%","\&")[$v[CTL_DEST] || 0], + $v[CTL_AMIN] || '', + $v[CTL_AMAX] || '', +# $v[CTL_RANGE] || '', +# $v[CTL_REPEAT] || '', + ). "]"; +} + +# Parse an option specification and fill the tables. +sub ParseOptionSpec ($$) { + my ($opt, $opctl) = @_; + + # Allow period in option name unless passing through, + my $op = $passthrough + ? qr/(?: \w+[-\w]* )/x : qr/(?: \w+[-.\w]* )/x; + + # Match option spec. + if ( $opt !~ m;^ + ( + # Option name + $op + # Aliases + (?: \| (?: . [^|!+=:]* )? )* + )? + ( + # Either modifiers ... + [!+] + | + # ... or a value/dest/repeat specification + [=:] [ionfs] [@%]? (?: \{\d*,?\d*\} )? + | + # ... or an optional-with-default spec + : (?: 0[0-7]+ | 0[xX][0-9a-fA-F]+ | 0[bB][01]+ | -?\d+ | \+ ) [@%]? + )? + $;x ) { + return (undef, "Error in option spec: \"$opt\"\n"); + } + + my ($names, $spec) = ($1, $2); + $spec = '' unless defined $spec; + + # $orig keeps track of the primary name the user specified. + # This name will be used for the internal or external linkage. + # In other words, if the user specifies "FoO|BaR", it will + # match any case combinations of 'foo' and 'bar', but if a global + # variable needs to be set, it will be $opt_FoO in the exact case + # as specified. + my $orig; + + my @names; + if ( defined $names ) { + @names = split (/\|/, $names); + $orig = $names[0]; + } + else { + @names = (''); + $orig = ''; + } + + # Construct the opctl entries. + my $entry; + if ( $spec eq '' || $spec eq '+' || $spec eq '!' ) { + # Fields are hard-wired here. + $entry = [$spec,$orig,undef,CTL_DEST_SCALAR,0,0]; + } + elsif ( $spec =~ /^:(0[0-7]+|0x[0-9a-f]+|0b[01]+|-?\d+|\+)([@%])?$/i ) { + my $def = $1; + my $dest = $2; + my $type = 'i'; # assume integer + if ( $def eq '+' ) { + # Increment. + $type = 'I'; + } + elsif ( $def =~ /^(0[0-7]+|0[xX][0-9a-fA-F]+|0[bB][01]+)$/ ) { + # Octal, binary or hex. + $type = 'o'; + $def = oct($def); + } + elsif ( $def =~ /^-?\d+$/ ) { + # Integer. + $def = 0 + $def; + } + $dest ||= '$'; + $dest = $dest eq '@' ? CTL_DEST_ARRAY + : $dest eq '%' ? CTL_DEST_HASH : CTL_DEST_SCALAR; + # Fields are hard-wired here. + $entry = [$type,$orig,$def eq '+' ? undef : $def, + $dest,0,1]; + } + else { + my ($mand, $type, $dest) = + $spec =~ /^([=:])([ionfs])([@%])?(\{(\d+)?(,)?(\d+)?\})?$/; + return (undef, "Cannot repeat while bundling: \"$opt\"\n") + if $bundling && defined($4); + my ($mi, $cm, $ma) = ($5, $6, $7); + return (undef, "{0} is useless in option spec: \"$opt\"\n") + if defined($mi) && !$mi && !defined($ma) && !defined($cm); + + $type = 'i' if $type eq 'n'; + $dest ||= '$'; + $dest = $dest eq '@' ? CTL_DEST_ARRAY + : $dest eq '%' ? CTL_DEST_HASH : CTL_DEST_SCALAR; + # Default minargs to 1/0 depending on mand status. + $mi = $mand eq '=' ? 1 : 0 unless defined $mi; + # Adjust mand status according to minargs. + $mand = $mi ? '=' : ':'; + # Adjust maxargs. + $ma = $mi ? $mi : 1 unless defined $ma || defined $cm; + return (undef, "Max must be greater than zero in option spec: \"$opt\"\n") + if defined($ma) && !$ma; + return (undef, "Max less than min in option spec: \"$opt\"\n") + if defined($ma) && $ma < $mi; + + # Fields are hard-wired here. + $entry = [$type,$orig,undef,$dest,$mi,$ma||-1]; + } + + # Process all names. First is canonical, the rest are aliases. + my $dups = ''; + foreach ( @names ) { + + $_ = lc ($_) + if $ignorecase > (($bundling && length($_) == 1) ? 1 : 0); + + if ( exists $opctl->{$_} ) { + $dups .= "Duplicate specification \"$opt\" for option \"$_\"\n"; + } + + if ( $spec eq '!' ) { + $opctl->{"no$_"} = $entry; + $opctl->{"no-$_"} = $entry; + $opctl->{$_} = [@$entry]; + $opctl->{$_}->[CTL_TYPE] = ''; + } + else { + $opctl->{$_} = $entry; + } + } + + if ( $dups ) { + # Warn now. Will become fatal in a future release. + foreach ( split(/\n+/, $dups) ) { + warn($_."\n"); + } + } + ($names[0], $orig); +} + +# Option lookup. +sub FindOption ($$$$$) { + + # returns (1, $opt, $ctl, $starter, $arg, $key) if okay, + # returns (1, undef) if option in error, + # returns (0) otherwise. + + my ($argv, $prefix, $argend, $opt, $opctl) = @_; + + print STDERR ("=> find \"$opt\"\n") if $debug; + + return (0) unless defined($opt); + return (0) unless $opt =~ /^($prefix)(.*)$/s; + return (0) if $opt eq "-" && !defined $opctl->{''}; + + $opt = substr( $opt, length($1) ); # retain taintedness + my $starter = $1; + + print STDERR ("=> split \"$starter\"+\"$opt\"\n") if $debug; + + my $optarg; # value supplied with --opt=value + my $rest; # remainder from unbundling + + # If it is a long option, it may include the value. + # With getopt_compat, only if not bundling. + if ( ($starter=~/^$longprefix$/ + || ($getopt_compat && ($bundling == 0 || $bundling == 2))) + && (my $oppos = index($opt, '=', 1)) > 0) { + my $optorg = $opt; + $opt = substr($optorg, 0, $oppos); + $optarg = substr($optorg, $oppos + 1); # retain tainedness + print STDERR ("=> option \"", $opt, + "\", optarg = \"$optarg\"\n") if $debug; + } + + #### Look it up ### + + my $tryopt = $opt; # option to try + + if ( ( $bundling || $bundling_values ) && $starter eq '-' ) { + + # To try overrides, obey case ignore. + $tryopt = $ignorecase ? lc($opt) : $opt; + + # If bundling == 2, long options can override bundles. + if ( $bundling == 2 && length($tryopt) > 1 + && defined ($opctl->{$tryopt}) ) { + print STDERR ("=> $starter$tryopt overrides unbundling\n") + if $debug; + } + + # If bundling_values, option may be followed by the value. + elsif ( $bundling_values ) { + $tryopt = $opt; + # Unbundle single letter option. + $rest = length ($tryopt) > 0 ? substr ($tryopt, 1) : ''; + $tryopt = substr ($tryopt, 0, 1); + $tryopt = lc ($tryopt) if $ignorecase > 1; + print STDERR ("=> $starter$tryopt unbundled from ", + "$starter$tryopt$rest\n") if $debug; + # Whatever remains may not be considered an option. + $optarg = $rest eq '' ? undef : $rest; + $rest = undef; + } + + # Split off a single letter and leave the rest for + # further processing. + else { + $tryopt = $opt; + # Unbundle single letter option. + $rest = length ($tryopt) > 0 ? substr ($tryopt, 1) : ''; + $tryopt = substr ($tryopt, 0, 1); + $tryopt = lc ($tryopt) if $ignorecase > 1; + print STDERR ("=> $starter$tryopt unbundled from ", + "$starter$tryopt$rest\n") if $debug; + $rest = undef unless $rest ne ''; + } + } + + # Try auto-abbreviation. + elsif ( $autoabbrev && $opt ne "" ) { + # Sort the possible long option names. + my @names = sort(keys (%$opctl)); + # Downcase if allowed. + $opt = lc ($opt) if $ignorecase; + $tryopt = $opt; + # Turn option name into pattern. + my $pat = quotemeta ($opt); + # Look up in option names. + my @hits = grep (/^$pat/, @names); + print STDERR ("=> ", scalar(@hits), " hits (@hits) with \"$pat\" ", + "out of ", scalar(@names), "\n") if $debug; + + # Check for ambiguous results. + unless ( (@hits <= 1) || (grep ($_ eq $opt, @hits) == 1) ) { + # See if all matches are for the same option. + my %hit; + foreach ( @hits ) { + my $hit = $opctl->{$_}->[CTL_CNAME] + if defined $opctl->{$_}->[CTL_CNAME]; + $hit = "no" . $hit if $opctl->{$_}->[CTL_TYPE] eq '!'; + $hit{$hit} = 1; + } + # Remove auto-supplied options (version, help). + if ( keys(%hit) == 2 ) { + if ( $auto_version && exists($hit{version}) ) { + delete $hit{version}; + } + elsif ( $auto_help && exists($hit{help}) ) { + delete $hit{help}; + } + } + # Now see if it really is ambiguous. + unless ( keys(%hit) == 1 ) { + return (0) if $passthrough; + warn ("Option ", $opt, " is ambiguous (", + join(", ", @hits), ")\n"); + $error++; + return (1, undef); + } + @hits = keys(%hit); + } + + # Complete the option name, if appropriate. + if ( @hits == 1 && $hits[0] ne $opt ) { + $tryopt = $hits[0]; + $tryopt = lc ($tryopt) + if $ignorecase > (($bundling && length($tryopt) == 1) ? 1 : 0); + print STDERR ("=> option \"$opt\" -> \"$tryopt\"\n") + if $debug; + } + } + + # Map to all lowercase if ignoring case. + elsif ( $ignorecase ) { + $tryopt = lc ($opt); + } + + # Check validity by fetching the info. + my $ctl = $opctl->{$tryopt}; + unless ( defined $ctl ) { + return (0) if $passthrough; + # Pretend one char when bundling. + if ( $bundling == 1 && length($starter) == 1 ) { + $opt = substr($opt,0,1); + unshift (@$argv, $starter.$rest) if defined $rest; + } + if ( $opt eq "" ) { + warn ("Missing option after ", $starter, "\n"); + } + else { + warn ("Unknown option: ", $opt, "\n"); + } + $error++; + return (1, undef); + } + # Apparently valid. + $opt = $tryopt; + print STDERR ("=> found ", OptCtl($ctl), + " for \"", $opt, "\"\n") if $debug; + + #### Determine argument status #### + + # If it is an option w/o argument, we're almost finished with it. + my $type = $ctl->[CTL_TYPE]; + my $arg; + + if ( $type eq '' || $type eq '!' || $type eq '+' ) { + if ( defined $optarg ) { + return (0) if $passthrough; + warn ("Option ", $opt, " does not take an argument\n"); + $error++; + undef $opt; + undef $optarg if $bundling_values; + } + elsif ( $type eq '' || $type eq '+' ) { + # Supply explicit value. + $arg = 1; + } + else { + $opt =~ s/^no-?//i; # strip NO prefix + $arg = 0; # supply explicit value + } + unshift (@$argv, $starter.$rest) if defined $rest; + return (1, $opt, $ctl, $starter, $arg); + } + + # Get mandatory status and type info. + my $mand = $ctl->[CTL_AMIN]; + + # Check if there is an option argument available. + if ( $gnu_compat ) { + my $optargtype = 0; # none, 1 = empty, 2 = nonempty, 3 = aux + if ( defined($optarg) ) { + $optargtype = (length($optarg) == 0) ? 1 : 2; + } + elsif ( defined $rest || @$argv > 0 ) { + # GNU getopt_long() does not accept the (optional) + # argument to be passed to the option without = sign. + # We do, since not doing so breaks existing scripts. + $optargtype = 3; + } + if(($optargtype == 0) && !$mand) { + if ( $type eq 'I' ) { + # Fake incremental type. + my @c = @$ctl; + $c[CTL_TYPE] = '+'; + return (1, $opt, \@c, $starter, 1); + } + my $val + = defined($ctl->[CTL_DEFAULT]) ? $ctl->[CTL_DEFAULT] + : $type eq 's' ? '' + : 0; + return (1, $opt, $ctl, $starter, $val); + } + return (1, $opt, $ctl, $starter, $type eq 's' ? '' : 0) + if $optargtype == 1; # --foo= -> return nothing + } + + # Check if there is an option argument available. + if ( defined $optarg + ? ($optarg eq '') + : !(defined $rest || @$argv > 0) ) { + # Complain if this option needs an argument. +# if ( $mand && !($type eq 's' ? defined($optarg) : 0) ) { + if ( $mand || $ctl->[CTL_DEST] == CTL_DEST_HASH ) { + return (0) if $passthrough; + warn ("Option ", $opt, " requires an argument\n"); + $error++; + return (1, undef); + } + if ( $type eq 'I' ) { + # Fake incremental type. + my @c = @$ctl; + $c[CTL_TYPE] = '+'; + return (1, $opt, \@c, $starter, 1); + } + return (1, $opt, $ctl, $starter, + defined($ctl->[CTL_DEFAULT]) ? $ctl->[CTL_DEFAULT] : + $type eq 's' ? '' : 0); + } + + # Get (possibly optional) argument. + $arg = (defined $rest ? $rest + : (defined $optarg ? $optarg : shift (@$argv))); + + # Get key if this is a "name=value" pair for a hash option. + my $key; + if ($ctl->[CTL_DEST] == CTL_DEST_HASH && defined $arg) { + ($key, $arg) = ($arg =~ /^([^=]*)=(.*)$/s) ? ($1, $2) + : ($arg, defined($ctl->[CTL_DEFAULT]) ? $ctl->[CTL_DEFAULT] : + ($mand ? undef : ($type eq 's' ? "" : 1))); + if (! defined $arg) { + warn ("Option $opt, key \"$key\", requires a value\n"); + $error++; + # Push back. + unshift (@$argv, $starter.$rest) if defined $rest; + return (1, undef); + } + } + + #### Check if the argument is valid for this option #### + + my $key_valid = $ctl->[CTL_DEST] == CTL_DEST_HASH ? "[^=]+=" : ""; + + if ( $type eq 's' ) { # string + # A mandatory string takes anything. + return (1, $opt, $ctl, $starter, $arg, $key) if $mand; + + # Same for optional string as a hash value + return (1, $opt, $ctl, $starter, $arg, $key) + if $ctl->[CTL_DEST] == CTL_DEST_HASH; + + # An optional string takes almost anything. + return (1, $opt, $ctl, $starter, $arg, $key) + if defined $optarg || defined $rest; + return (1, $opt, $ctl, $starter, $arg, $key) if $arg eq "-"; # ?? + + # Check for option or option list terminator. + if ($arg eq $argend || + $arg =~ /^$prefix.+/) { + # Push back. + unshift (@$argv, $arg); + # Supply empty value. + $arg = ''; + } + } + + elsif ( $type eq 'i' # numeric/integer + || $type eq 'I' # numeric/integer w/ incr default + || $type eq 'o' ) { # dec/oct/hex/bin value + + my $o_valid = $type eq 'o' ? PAT_XINT : PAT_INT; + + if ( $bundling && defined $rest + && $rest =~ /^($key_valid)($o_valid)(.*)$/si ) { + ($key, $arg, $rest) = ($1, $2, $+); + chop($key) if $key; + $arg = ($type eq 'o' && $arg =~ /^0/) ? oct($arg) : 0+$arg; + unshift (@$argv, $starter.$rest) if defined $rest && $rest ne ''; + } + elsif ( $arg =~ /^$o_valid$/si ) { + $arg =~ tr/_//d; + $arg = ($type eq 'o' && $arg =~ /^0/) ? oct($arg) : 0+$arg; + } + else { + if ( defined $optarg || $mand ) { + if ( $passthrough ) { + unshift (@$argv, defined $rest ? $starter.$rest : $arg) + unless defined $optarg; + return (0); + } + warn ("Value \"", $arg, "\" invalid for option ", + $opt, " (", + $type eq 'o' ? "extended " : '', + "integer number expected)\n"); + $error++; + # Push back. + unshift (@$argv, $starter.$rest) if defined $rest; + return (1, undef); + } + else { + # Push back. + unshift (@$argv, defined $rest ? $starter.$rest : $arg); + if ( $type eq 'I' ) { + # Fake incremental type. + my @c = @$ctl; + $c[CTL_TYPE] = '+'; + return (1, $opt, \@c, $starter, 1); + } + # Supply default value. + $arg = defined($ctl->[CTL_DEFAULT]) ? $ctl->[CTL_DEFAULT] : 0; + } + } + } + + elsif ( $type eq 'f' ) { # real number, int is also ok + my $o_valid = PAT_FLOAT; + if ( $bundling && defined $rest && + $rest =~ /^($key_valid)($o_valid)(.*)$/s ) { + $arg =~ tr/_//d; + ($key, $arg, $rest) = ($1, $2, $+); + chop($key) if $key; + unshift (@$argv, $starter.$rest) if defined $rest && $rest ne ''; + } + elsif ( $arg =~ /^$o_valid$/ ) { + $arg =~ tr/_//d; + } + else { + if ( defined $optarg || $mand ) { + if ( $passthrough ) { + unshift (@$argv, defined $rest ? $starter.$rest : $arg) + unless defined $optarg; + return (0); + } + warn ("Value \"", $arg, "\" invalid for option ", + $opt, " (real number expected)\n"); + $error++; + # Push back. + unshift (@$argv, $starter.$rest) if defined $rest; + return (1, undef); + } + else { + # Push back. + unshift (@$argv, defined $rest ? $starter.$rest : $arg); + # Supply default value. + $arg = 0.0; + } + } + } + else { + die("Getopt::Long internal error (Can't happen)\n"); + } + return (1, $opt, $ctl, $starter, $arg, $key); +} + +sub ValidValue ($$$$$) { + my ($ctl, $arg, $mand, $argend, $prefix) = @_; + + if ( $ctl->[CTL_DEST] == CTL_DEST_HASH ) { + return 0 unless $arg =~ /[^=]+=(.*)/; + $arg = $1; + } + + my $type = $ctl->[CTL_TYPE]; + + if ( $type eq 's' ) { # string + # A mandatory string takes anything. + return (1) if $mand; + + return (1) if $arg eq "-"; + + # Check for option or option list terminator. + return 0 if $arg eq $argend || $arg =~ /^$prefix.+/; + return 1; + } + + elsif ( $type eq 'i' # numeric/integer + || $type eq 'I' # numeric/integer w/ incr default + || $type eq 'o' ) { # dec/oct/hex/bin value + + my $o_valid = $type eq 'o' ? PAT_XINT : PAT_INT; + return $arg =~ /^$o_valid$/si; + } + + elsif ( $type eq 'f' ) { # real number, int is also ok + my $o_valid = PAT_FLOAT; + return $arg =~ /^$o_valid$/; + } + die("ValidValue: Cannot happen\n"); +} + +# Getopt::Long Configuration. +sub Configure (@) { + my (@options) = @_; + + my $prevconfig = + [ $error, $debug, $major_version, $minor_version, $caller, + $autoabbrev, $getopt_compat, $ignorecase, $bundling, $order, + $gnu_compat, $passthrough, $genprefix, $auto_version, $auto_help, + $longprefix, $bundling_values ]; + + if ( ref($options[0]) eq 'ARRAY' ) { + ( $error, $debug, $major_version, $minor_version, $caller, + $autoabbrev, $getopt_compat, $ignorecase, $bundling, $order, + $gnu_compat, $passthrough, $genprefix, $auto_version, $auto_help, + $longprefix, $bundling_values ) = @{shift(@options)}; + } + + my $opt; + foreach $opt ( @options ) { + my $try = lc ($opt); + my $action = 1; + if ( $try =~ /^no_?(.*)$/s ) { + $action = 0; + $try = $+; + } + if ( ($try eq 'default' or $try eq 'defaults') && $action ) { + ConfigDefaults (); + } + elsif ( ($try eq 'posix_default' or $try eq 'posix_defaults') ) { + local $ENV{POSIXLY_CORRECT}; + $ENV{POSIXLY_CORRECT} = 1 if $action; + ConfigDefaults (); + } + elsif ( $try eq 'auto_abbrev' or $try eq 'autoabbrev' ) { + $autoabbrev = $action; + } + elsif ( $try eq 'getopt_compat' ) { + $getopt_compat = $action; + $genprefix = $action ? "(--|-|\\+)" : "(--|-)"; + } + elsif ( $try eq 'gnu_getopt' ) { + if ( $action ) { + $gnu_compat = 1; + $bundling = 1; + $getopt_compat = 0; + $genprefix = "(--|-)"; + $order = $PERMUTE; + $bundling_values = 0; + } + } + elsif ( $try eq 'gnu_compat' ) { + $gnu_compat = $action; + $bundling = 0; + $bundling_values = 1; + } + elsif ( $try =~ /^(auto_?)?version$/ ) { + $auto_version = $action; + } + elsif ( $try =~ /^(auto_?)?help$/ ) { + $auto_help = $action; + } + elsif ( $try eq 'ignorecase' or $try eq 'ignore_case' ) { + $ignorecase = $action; + } + elsif ( $try eq 'ignorecase_always' or $try eq 'ignore_case_always' ) { + $ignorecase = $action ? 2 : 0; + } + elsif ( $try eq 'bundling' ) { + $bundling = $action; + $bundling_values = 0 if $action; + } + elsif ( $try eq 'bundling_override' ) { + $bundling = $action ? 2 : 0; + $bundling_values = 0 if $action; + } + elsif ( $try eq 'bundling_values' ) { + $bundling_values = $action; + $bundling = 0 if $action; + } + elsif ( $try eq 'require_order' ) { + $order = $action ? $REQUIRE_ORDER : $PERMUTE; + } + elsif ( $try eq 'permute' ) { + $order = $action ? $PERMUTE : $REQUIRE_ORDER; + } + elsif ( $try eq 'pass_through' or $try eq 'passthrough' ) { + $passthrough = $action; + } + elsif ( $try =~ /^prefix=(.+)$/ && $action ) { + $genprefix = $1; + # Turn into regexp. Needs to be parenthesized! + $genprefix = "(" . quotemeta($genprefix) . ")"; + eval { '' =~ /$genprefix/; }; + die("Getopt::Long: invalid pattern \"$genprefix\"\n") if $@; + } + elsif ( $try =~ /^prefix_pattern=(.+)$/ && $action ) { + $genprefix = $1; + # Parenthesize if needed. + $genprefix = "(" . $genprefix . ")" + unless $genprefix =~ /^\(.*\)$/; + eval { '' =~ m"$genprefix"; }; + die("Getopt::Long: invalid pattern \"$genprefix\"\n") if $@; + } + elsif ( $try =~ /^long_prefix_pattern=(.+)$/ && $action ) { + $longprefix = $1; + # Parenthesize if needed. + $longprefix = "(" . $longprefix . ")" + unless $longprefix =~ /^\(.*\)$/; + eval { '' =~ m"$longprefix"; }; + die("Getopt::Long: invalid long prefix pattern \"$longprefix\"\n") if $@; + } + elsif ( $try eq 'debug' ) { + $debug = $action; + } + else { + die("Getopt::Long: unknown or erroneous config parameter \"$opt\"\n") + } + } + $prevconfig; +} + +# Deprecated name. +sub config (@) { + Configure (@_); +} + +# Issue a standard message for --version. +# +# The arguments are mostly the same as for Pod::Usage::pod2usage: +# +# - a number (exit value) +# - a string (lead in message) +# - a hash with options. See Pod::Usage for details. +# +sub VersionMessage(@) { + # Massage args. + my $pa = setup_pa_args("version", @_); + + my $v = $main::VERSION; + my $fh = $pa->{-output} || + ( ($pa->{-exitval} eq "NOEXIT" || $pa->{-exitval} < 2) ? \*STDOUT : \*STDERR ); + + print $fh (defined($pa->{-message}) ? $pa->{-message} : (), + $0, defined $v ? " version $v" : (), + "\n", + "(", __PACKAGE__, "::", "GetOptions", + " version $VERSION,", + " Perl version ", + $] >= 5.006 ? sprintf("%vd", $^V) : $], + ")\n"); + exit($pa->{-exitval}) unless $pa->{-exitval} eq "NOEXIT"; +} + +# Issue a standard message for --help. +# +# The arguments are the same as for Pod::Usage::pod2usage: +# +# - a number (exit value) +# - a string (lead in message) +# - a hash with options. See Pod::Usage for details. +# +sub HelpMessage(@) { + eval { + require Pod::Usage; + Pod::Usage->import; + 1; + } || die("Cannot provide help: cannot load Pod::Usage\n"); + + # Note that pod2usage will issue a warning if -exitval => NOEXIT. + pod2usage(setup_pa_args("help", @_)); + +} + +# Helper routine to set up a normalized hash ref to be used as +# argument to pod2usage. +sub setup_pa_args($@) { + my $tag = shift; # who's calling + + # If called by direct binding to an option, it will get the option + # name and value as arguments. Remove these, if so. + @_ = () if @_ == 2 && $_[0] eq $tag; + + my $pa; + if ( @_ > 1 ) { + $pa = { @_ }; + } + else { + $pa = shift || {}; + } + + # At this point, $pa can be a number (exit value), string + # (message) or hash with options. + + if ( UNIVERSAL::isa($pa, 'HASH') ) { + # Get rid of -msg vs. -message ambiguity. + if (!defined $pa->{-message}) { + $pa->{-message} = delete($pa->{-msg}); + } + } + elsif ( $pa =~ /^-?\d+$/ ) { + $pa = { -exitval => $pa }; + } + else { + $pa = { -message => $pa }; + } + + # These are _our_ defaults. + $pa->{-verbose} = 0 unless exists($pa->{-verbose}); + $pa->{-exitval} = 0 unless exists($pa->{-exitval}); + $pa; +} + +# Sneak way to know what version the user requested. +sub VERSION { + $requested_version = $_[1] if @_ > 1; + shift->SUPER::VERSION(@_); +} + +package Getopt::Long::CallBack; + +sub new { + my ($pkg, %atts) = @_; + bless { %atts }, $pkg; +} + +sub name { + my $self = shift; + ''.$self->{name}; +} + +sub given { + my $self = shift; + $self->{given}; +} + +use overload + # Treat this object as an ordinary string for legacy API. + '""' => \&name, + fallback => 1; + +1; + +################ Documentation ################ + +=head1 NAME + +Getopt::Long - Extended processing of command line options + +=head1 SYNOPSIS + + use Getopt::Long; + my $data = "file.dat"; + my $length = 24; + my $verbose; + GetOptions ("length=i" => \$length, # numeric + "file=s" => \$data, # string + "verbose" => \$verbose) # flag + or die("Error in command line arguments\n"); + +=head1 DESCRIPTION + +The Getopt::Long module implements an extended getopt function called +GetOptions(). It parses the command line from C<@ARGV>, recognizing +and removing specified options and their possible values. + +This function adheres to the POSIX syntax for command +line options, with GNU extensions. In general, this means that options +have long names instead of single letters, and are introduced with a +double dash "--". Support for bundling of command line options, as was +the case with the more traditional single-letter approach, is provided +but not enabled by default. + +=head1 Command Line Options, an Introduction + +Command line operated programs traditionally take their arguments from +the command line, for example filenames or other information that the +program needs to know. Besides arguments, these programs often take +command line I as well. Options are not necessary for the +program to work, hence the name 'option', but are used to modify its +default behaviour. For example, a program could do its job quietly, +but with a suitable option it could provide verbose information about +what it did. + +Command line options come in several flavours. Historically, they are +preceded by a single dash C<->, and consist of a single letter. + + -l -a -c + +Usually, these single-character options can be bundled: + + -lac + +Options can have values, the value is placed after the option +character. Sometimes with whitespace in between, sometimes not: + + -s 24 -s24 + +Due to the very cryptic nature of these options, another style was +developed that used long names. So instead of a cryptic C<-l> one +could use the more descriptive C<--long>. To distinguish between a +bundle of single-character options and a long one, two dashes are used +to precede the option name. Early implementations of long options used +a plus C<+> instead. Also, option values could be specified either +like + + --size=24 + +or + + --size 24 + +The C<+> form is now obsolete and strongly deprecated. + +=head1 Getting Started with Getopt::Long + +Getopt::Long is the Perl5 successor of C. This was the +first Perl module that provided support for handling the new style of +command line options, in particular long option names, hence the Perl5 +name Getopt::Long. This module also supports single-character options +and bundling. + +To use Getopt::Long from a Perl program, you must include the +following line in your Perl program: + + use Getopt::Long; + +This will load the core of the Getopt::Long module and prepare your +program for using it. Most of the actual Getopt::Long code is not +loaded until you really call one of its functions. + +In the default configuration, options names may be abbreviated to +uniqueness, case does not matter, and a single dash is sufficient, +even for long option names. Also, options may be placed between +non-option arguments. See L for more +details on how to configure Getopt::Long. + +=head2 Simple options + +The most simple options are the ones that take no values. Their mere +presence on the command line enables the option. Popular examples are: + + --all --verbose --quiet --debug + +Handling simple options is straightforward: + + my $verbose = ''; # option variable with default value (false) + my $all = ''; # option variable with default value (false) + GetOptions ('verbose' => \$verbose, 'all' => \$all); + +The call to GetOptions() parses the command line arguments that are +present in C<@ARGV> and sets the option variable to the value C<1> if +the option did occur on the command line. Otherwise, the option +variable is not touched. Setting the option value to true is often +called I the option. + +The option name as specified to the GetOptions() function is called +the option I. Later we'll see that this specification +can contain more than just the option name. The reference to the +variable is called the option I. + +GetOptions() will return a true value if the command line could be +processed successfully. Otherwise, it will write error messages using +die() and warn(), and return a false result. + +=head2 A little bit less simple options + +Getopt::Long supports two useful variants of simple options: +I options and I options. + +A negatable option is specified with an exclamation mark C after the +option name: + + my $verbose = ''; # option variable with default value (false) + GetOptions ('verbose!' => \$verbose); + +Now, using C<--verbose> on the command line will enable C<$verbose>, +as expected. But it is also allowed to use C<--noverbose>, which will +disable C<$verbose> by setting its value to C<0>. Using a suitable +default value, the program can find out whether C<$verbose> is false +by default, or disabled by using C<--noverbose>. + +(If both C<--verbose> and C<--noverbose> are given, whichever is given +last takes precedence.) + +An incremental option is specified with a plus C<+> after the +option name: + + my $verbose = ''; # option variable with default value (false) + GetOptions ('verbose+' => \$verbose); + +Using C<--verbose> on the command line will increment the value of +C<$verbose>. This way the program can keep track of how many times the +option occurred on the command line. For example, each occurrence of +C<--verbose> could increase the verbosity level of the program. + +=head2 Mixing command line option with other arguments + +Usually programs take command line options as well as other arguments, +for example, file names. It is good practice to always specify the +options first, and the other arguments last. Getopt::Long will, +however, allow the options and arguments to be mixed and 'filter out' +all the options before passing the rest of the arguments to the +program. To stop Getopt::Long from processing further arguments, +insert a double dash C<--> on the command line: + + --size 24 -- --all + +In this example, C<--all> will I be treated as an option, but +passed to the program unharmed, in C<@ARGV>. + +=head2 Options with values + +For options that take values it must be specified whether the option +value is required or not, and what kind of value the option expects. + +Three kinds of values are supported: integer numbers, floating point +numbers, and strings. + +If the option value is required, Getopt::Long will take the +command line argument that follows the option and assign this to the +option variable. If, however, the option value is specified as +optional, this will only be done if that value does not look like a +valid command line option itself. + + my $tag = ''; # option variable with default value + GetOptions ('tag=s' => \$tag); + +In the option specification, the option name is followed by an equals +sign C<=> and the letter C. The equals sign indicates that this +option requires a value. The letter C indicates that this value is +an arbitrary string. Other possible value types are C for integer +values, and C for floating point values. Using a colon C<:> instead +of the equals sign indicates that the option value is optional. In +this case, if no suitable value is supplied, string valued options get +an empty string C<''> assigned, while numeric options are set to C<0>. + +(If the same option appears more than once on the command line, the +last given value is used. If you want to take all the values, see +below.) + +=head2 Options with multiple values + +Options sometimes take several values. For example, a program could +use multiple directories to search for library files: + + --library lib/stdlib --library lib/extlib + +To accomplish this behaviour, simply specify an array reference as the +destination for the option: + + GetOptions ("library=s" => \@libfiles); + +Alternatively, you can specify that the option can have multiple +values by adding a "@", and pass a reference to a scalar as the +destination: + + GetOptions ("library=s@" => \$libfiles); + +Used with the example above, C<@libfiles> c.q. C<@$libfiles> would +contain two strings upon completion: C<"lib/stdlib"> and +C<"lib/extlib">, in that order. It is also possible to specify that +only integer or floating point numbers are acceptable values. + +Often it is useful to allow comma-separated lists of values as well as +multiple occurrences of the options. This is easy using Perl's split() +and join() operators: + + GetOptions ("library=s" => \@libfiles); + @libfiles = split(/,/,join(',',@libfiles)); + +Of course, it is important to choose the right separator string for +each purpose. + +Warning: What follows is an experimental feature. + +Options can take multiple values at once, for example + + --coordinates 52.2 16.4 --rgbcolor 255 255 149 + +This can be accomplished by adding a repeat specifier to the option +specification. Repeat specifiers are very similar to the C<{...}> +repeat specifiers that can be used with regular expression patterns. +For example, the above command line would be handled as follows: + + GetOptions('coordinates=f{2}' => \@coor, 'rgbcolor=i{3}' => \@color); + +The destination for the option must be an array or array reference. + +It is also possible to specify the minimal and maximal number of +arguments an option takes. C indicates an option that +takes at least two and at most 4 arguments. C indicates one +or more values; C indicates zero or more option values. + +=head2 Options with hash values + +If the option destination is a reference to a hash, the option will +take, as value, strings of the form IC<=>I. The value will +be stored with the specified key in the hash. + + GetOptions ("define=s" => \%defines); + +Alternatively you can use: + + GetOptions ("define=s%" => \$defines); + +When used with command line options: + + --define os=linux --define vendor=redhat + +the hash C<%defines> (or C<%$defines>) will contain two keys, C<"os"> +with value C<"linux"> and C<"vendor"> with value C<"redhat">. It is +also possible to specify that only integer or floating point numbers +are acceptable values. The keys are always taken to be strings. + +=head2 User-defined subroutines to handle options + +Ultimate control over what should be done when (actually: each time) +an option is encountered on the command line can be achieved by +designating a reference to a subroutine (or an anonymous subroutine) +as the option destination. When GetOptions() encounters the option, it +will call the subroutine with two or three arguments. The first +argument is the name of the option. (Actually, it is an object that +stringifies to the name of the option.) For a scalar or array destination, +the second argument is the value to be stored. For a hash destination, +the second argument is the key to the hash, and the third argument +the value to be stored. It is up to the subroutine to store the value, +or do whatever it thinks is appropriate. + +A trivial application of this mechanism is to implement options that +are related to each other. For example: + + my $verbose = ''; # option variable with default value (false) + GetOptions ('verbose' => \$verbose, + 'quiet' => sub { $verbose = 0 }); + +Here C<--verbose> and C<--quiet> control the same variable +C<$verbose>, but with opposite values. + +If the subroutine needs to signal an error, it should call die() with +the desired error message as its argument. GetOptions() will catch the +die(), issue the error message, and record that an error result must +be returned upon completion. + +If the text of the error message starts with an exclamation mark C +it is interpreted specially by GetOptions(). There is currently one +special command implemented: C will cause GetOptions() +to stop processing options, as if it encountered a double dash C<-->. + +Here is an example of how to access the option name and value from within +a subroutine: + + GetOptions ('opt=i' => \&handler); + sub handler { + my ($opt_name, $opt_value) = @_; + print("Option name is $opt_name and value is $opt_value\n"); + } + +=head2 Options with multiple names + +Often it is user friendly to supply alternate mnemonic names for +options. For example C<--height> could be an alternate name for +C<--length>. Alternate names can be included in the option +specification, separated by vertical bar C<|> characters. To implement +the above example: + + GetOptions ('length|height=f' => \$length); + +The first name is called the I name, the other names are +called I. When using a hash to store options, the key will +always be the primary name. + +Multiple alternate names are possible. + +=head2 Case and abbreviations + +Without additional configuration, GetOptions() will ignore the case of +option names, and allow the options to be abbreviated to uniqueness. + + GetOptions ('length|height=f' => \$length, "head" => \$head); + +This call will allow C<--l> and C<--L> for the length option, but +requires a least C<--hea> and C<--hei> for the head and height options. + +=head2 Summary of Option Specifications + +Each option specifier consists of two parts: the name specification +and the argument specification. + +The name specification contains the name of the option, optionally +followed by a list of alternative names separated by vertical bar +characters. The name is made up of alphanumeric characters, hyphens, +underscores. If C is disabled, a period is also allowed in +option names. + + length option name is "length" + length|size|l name is "length", aliases are "size" and "l" + +The argument specification is optional. If omitted, the option is +considered boolean, a value of 1 will be assigned when the option is +used on the command line. + +The argument specification can be + +=over 4 + +=item ! + +The option does not take an argument and may be negated by prefixing +it with "no" or "no-". E.g. C<"foo!"> will allow C<--foo> (a value of +1 will be assigned) as well as C<--nofoo> and C<--no-foo> (a value of +0 will be assigned). If the option has aliases, this applies to the +aliases as well. + +Using negation on a single letter option when bundling is in effect is +pointless and will result in a warning. + +=item + + +The option does not take an argument and will be incremented by 1 +every time it appears on the command line. E.g. C<"more+">, when used +with C<--more --more --more>, will increment the value three times, +resulting in a value of 3 (provided it was 0 or undefined at first). + +The C<+> specifier is ignored if the option destination is not a scalar. + +=item = I [ I ] [ I ] + +The option requires an argument of the given type. Supported types +are: + +=over 4 + +=item s + +String. An arbitrary sequence of characters. It is valid for the +argument to start with C<-> or C<-->. + +=item i + +Integer. An optional leading plus or minus sign, followed by a +sequence of digits. + +=item o + +Extended integer, Perl style. This can be either an optional leading +plus or minus sign, followed by a sequence of digits, or an octal +string (a zero, optionally followed by '0', '1', .. '7'), or a +hexadecimal string (C<0x> followed by '0' .. '9', 'a' .. 'f', case +insensitive), or a binary string (C<0b> followed by a series of '0' +and '1'). + +=item f + +Real number. For example C<3.14>, C<-6.23E24> and so on. + +=back + +The I can be C<@> or C<%> to specify that the option is +list or a hash valued. This is only needed when the destination for +the option value is not otherwise specified. It should be omitted when +not needed. + +The I specifies the number of values this option takes per +occurrence on the command line. It has the format C<{> [ I ] [ C<,> [ I ] ] C<}>. + +I denotes the minimal number of arguments. It defaults to 1 for +options with C<=> and to 0 for options with C<:>, see below. Note that +I overrules the C<=> / C<:> semantics. + +I denotes the maximum number of arguments. It must be at least +I. If I is omitted, I, there is no +upper bound to the number of argument values taken. + +=item : I [ I ] + +Like C<=>, but designates the argument as optional. +If omitted, an empty string will be assigned to string values options, +and the value zero to numeric options. + +Note that if a string argument starts with C<-> or C<-->, it will be +considered an option on itself. + +=item : I [ I ] + +Like C<:i>, but if the value is omitted, the I will be assigned. + +If the I is octal, hexadecimal or binary, behaves like C<:o>. + +=item : + [ I ] + +Like C<:i>, but if the value is omitted, the current value for the +option will be incremented. + +=back + +=head1 Advanced Possibilities + +=head2 Object oriented interface + +See L. + +=head2 Callback object + +In version 2.37 the first argument to the callback function was +changed from string to object. This was done to make room for +extensions and more detailed control. The object stringifies to the +option name so this change should not introduce compatibility +problems. + +The callback object has the following methods: + +=over + +=item name + +The name of the option, unabbreviated. For an option with multiple +names it return the first (canonical) name. + +=item given + +The name of the option as actually used, unabbreveated. + +=back + +=head2 Thread Safety + +Getopt::Long is thread safe when using ithreads as of Perl 5.8. It is +I thread safe when using the older (experimental and now +obsolete) threads implementation that was added to Perl 5.005. + +=head2 Documentation and help texts + +Getopt::Long encourages the use of Pod::Usage to produce help +messages. For example: + + use Getopt::Long; + use Pod::Usage; + + my $man = 0; + my $help = 0; + + GetOptions('help|?' => \$help, man => \$man) or pod2usage(2); + pod2usage(1) if $help; + pod2usage(-exitval => 0, -verbose => 2) if $man; + + __END__ + + =head1 NAME + + sample - Using Getopt::Long and Pod::Usage + + =head1 SYNOPSIS + + sample [options] [file ...] + + Options: + -help brief help message + -man full documentation + + =head1 OPTIONS + + =over 8 + + =item B<-help> + + Print a brief help message and exits. + + =item B<-man> + + Prints the manual page and exits. + + =back + + =head1 DESCRIPTION + + B will read the given input file(s) and do something + useful with the contents thereof. + + =cut + +See L for details. + +=head2 Parsing options from an arbitrary array + +By default, GetOptions parses the options that are present in the +global array C<@ARGV>. A special entry C can be +used to parse options from an arbitrary array. + + use Getopt::Long qw(GetOptionsFromArray); + $ret = GetOptionsFromArray(\@myopts, ...); + +When used like this, options and their possible values are removed +from C<@myopts>, the global C<@ARGV> is not touched at all. + +The following two calls behave identically: + + $ret = GetOptions( ... ); + $ret = GetOptionsFromArray(\@ARGV, ... ); + +This also means that a first argument hash reference now becomes the +second argument: + + $ret = GetOptions(\%opts, ... ); + $ret = GetOptionsFromArray(\@ARGV, \%opts, ... ); + +=head2 Parsing options from an arbitrary string + +A special entry C can be used to parse options +from an arbitrary string. + + use Getopt::Long qw(GetOptionsFromString); + $ret = GetOptionsFromString($string, ...); + +The contents of the string are split into arguments using a call to +C. As with C, the +global C<@ARGV> is not touched. + +It is possible that, upon completion, not all arguments in the string +have been processed. C will, when called in list +context, return both the return status and an array reference to any +remaining arguments: + + ($ret, $args) = GetOptionsFromString($string, ... ); + +If any arguments remain, and C was not called in +list context, a message will be given and C will +return failure. + +As with GetOptionsFromArray, a first argument hash reference now +becomes the second argument. See the next section. + +=head2 Storing options values in a hash + +Sometimes, for example when there are a lot of options, having a +separate variable for each of them can be cumbersome. GetOptions() +supports, as an alternative mechanism, storing options values in a +hash. + +To obtain this, a reference to a hash must be passed I to GetOptions(). For each option that is specified on the +command line, the option value will be stored in the hash with the +option name as key. Options that are not actually used on the command +line will not be put in the hash, on other words, +C (or defined()) can be used to test if an option +was used. The drawback is that warnings will be issued if the program +runs under C and uses C<$h{option}> without testing with +exists() or defined() first. + + my %h = (); + GetOptions (\%h, 'length=i'); # will store in $h{length} + +For options that take list or hash values, it is necessary to indicate +this by appending an C<@> or C<%> sign after the type: + + GetOptions (\%h, 'colours=s@'); # will push to @{$h{colours}} + +To make things more complicated, the hash may contain references to +the actual destinations, for example: + + my $len = 0; + my %h = ('length' => \$len); + GetOptions (\%h, 'length=i'); # will store in $len + +This example is fully equivalent with: + + my $len = 0; + GetOptions ('length=i' => \$len); # will store in $len + +Any mixture is possible. For example, the most frequently used options +could be stored in variables while all other options get stored in the +hash: + + my $verbose = 0; # frequently referred + my $debug = 0; # frequently referred + my %h = ('verbose' => \$verbose, 'debug' => \$debug); + GetOptions (\%h, 'verbose', 'debug', 'filter', 'size=i'); + if ( $verbose ) { ... } + if ( exists $h{filter} ) { ... option 'filter' was specified ... } + +=head2 Bundling + +With bundling it is possible to set several single-character options +at once. For example if C, C and C are all valid options, + + -vax + +will set all three. + +Getopt::Long supports three styles of bundling. To enable bundling, a +call to Getopt::Long::Configure is required. + +The simplest style of bundling can be enabled with: + + Getopt::Long::Configure ("bundling"); + +Configured this way, single-character options can be bundled but long +options (and any of their auto-abbreviated shortened forms) B +always start with a double dash C<--> to avoid ambiguity. For example, +when C, C, C and C are all valid options, + + -vax + +will set C, C and C, but + + --vax + +will set C. + +The second style of bundling lifts this restriction. It can be enabled +with: + + Getopt::Long::Configure ("bundling_override"); + +Now, C<-vax> will set the option C. + +In all of the above cases, option values may be inserted in the +bundle. For example: + + -h24w80 + +is equivalent to + + -h 24 -w 80 + +A third style of bundling allows only values to be bundled with +options. It can be enabled with: + + Getopt::Long::Configure ("bundling_values"); + +Now, C<-h24> will set the option C to C<24>, but option bundles +like C<-vxa> and C<-h24w80> are flagged as errors. + +Enabling C will disable the other two styles of +bundling. + +When configured for bundling, single-character options are matched +case sensitive while long options are matched case insensitive. To +have the single-character options matched case insensitive as well, +use: + + Getopt::Long::Configure ("bundling", "ignorecase_always"); + +It goes without saying that bundling can be quite confusing. + +=head2 The lonesome dash + +Normally, a lone dash C<-> on the command line will not be considered +an option. Option processing will terminate (unless "permute" is +configured) and the dash will be left in C<@ARGV>. + +It is possible to get special treatment for a lone dash. This can be +achieved by adding an option specification with an empty name, for +example: + + GetOptions ('' => \$stdio); + +A lone dash on the command line will now be a legal option, and using +it will set variable C<$stdio>. + +=head2 Argument callback + +A special option 'name' C<< <> >> can be used to designate a subroutine +to handle non-option arguments. When GetOptions() encounters an +argument that does not look like an option, it will immediately call this +subroutine and passes it one parameter: the argument name. + +For example: + + my $width = 80; + sub process { ... } + GetOptions ('width=i' => \$width, '<>' => \&process); + +When applied to the following command line: + + arg1 --width=72 arg2 --width=60 arg3 + +This will call +C while C<$width> is C<80>, +C while C<$width> is C<72>, and +C while C<$width> is C<60>. + +This feature requires configuration option B, see section +L. + +=head1 Configuring Getopt::Long + +Getopt::Long can be configured by calling subroutine +Getopt::Long::Configure(). This subroutine takes a list of quoted +strings, each specifying a configuration option to be enabled, e.g. +C. To disable, prefix with C or C, e.g. +C. Case does not matter. Multiple calls to Configure() +are possible. + +Alternatively, as of version 2.24, the configuration options may be +passed together with the C statement: + + use Getopt::Long qw(:config no_ignore_case bundling); + +The following options are available: + +=over 12 + +=item default + +This option causes all configuration options to be reset to their +default values. + +=item posix_default + +This option causes all configuration options to be reset to their +default values as if the environment variable POSIXLY_CORRECT had +been set. + +=item auto_abbrev + +Allow option names to be abbreviated to uniqueness. +Default is enabled unless environment variable +POSIXLY_CORRECT has been set, in which case C is disabled. + +=item getopt_compat + +Allow C<+> to start options. +Default is enabled unless environment variable +POSIXLY_CORRECT has been set, in which case C is disabled. + +=item gnu_compat + +C controls whether C<--opt=> is allowed, and what it should +do. Without C, C<--opt=> gives an error. With C, +C<--opt=> will give option C an empty value. +This is the way GNU getopt_long() does it. + +Note that for options with optional arguments, C<--opt value> is still +accepted, even though GNU getopt_long() requires writing C<--opt=value> +in this case. + +=item gnu_getopt + +This is a short way of setting C C C +C. With C, command line handling should be +reasonably compatible with GNU getopt_long(). + +=item require_order + +Whether command line arguments are allowed to be mixed with options. +Default is disabled unless environment variable +POSIXLY_CORRECT has been set, in which case C is enabled. + +See also C, which is the opposite of C. + +=item permute + +Whether command line arguments are allowed to be mixed with options. +Default is enabled unless environment variable +POSIXLY_CORRECT has been set, in which case C is disabled. +Note that C is the opposite of C. + +If C is enabled, this means that + + --foo arg1 --bar arg2 arg3 + +is equivalent to + + --foo --bar arg1 arg2 arg3 + +If an argument callback routine is specified, C<@ARGV> will always be +empty upon successful return of GetOptions() since all options have been +processed. The only exception is when C<--> is used: + + --foo arg1 --bar arg2 -- arg3 + +This will call the callback routine for arg1 and arg2, and then +terminate GetOptions() leaving C<"arg3"> in C<@ARGV>. + +If C is enabled, options processing +terminates when the first non-option is encountered. + + --foo arg1 --bar arg2 arg3 + +is equivalent to + + --foo -- arg1 --bar arg2 arg3 + +If C is also enabled, options processing will terminate +at the first unrecognized option, or non-option, whichever comes +first. + +=item bundling (default: disabled) + +Enabling this option will allow single-character options to be +bundled. To distinguish bundles from long option names, long options +(and any of their auto-abbreviated shortened forms) I be +introduced with C<--> and bundles with C<->. + +Note that, if you have options C, C and C, and +auto_abbrev enabled, possible arguments and option settings are: + + using argument sets option(s) + ------------------------------------------ + -a, --a a + -l, --l l + -al, -la, -ala, -all,... a, l + --al, --all all + +The surprising part is that C<--a> sets option C (due to auto +completion), not C. + +Note: disabling C also disables C. + +=item bundling_override (default: disabled) + +If C is enabled, bundling is enabled as with +C but now long option names override option bundles. + +Note: disabling C also disables C. + +B Using option bundling can easily lead to unexpected results, +especially when mixing long options and bundles. Caveat emptor. + +=item ignore_case (default: enabled) + +If enabled, case is ignored when matching option names. If, however, +bundling is enabled as well, single character options will be treated +case-sensitive. + +With C, option specifications for options that only +differ in case, e.g., C<"foo"> and C<"Foo">, will be flagged as +duplicates. + +Note: disabling C also disables C. + +=item ignore_case_always (default: disabled) + +When bundling is in effect, case is ignored on single-character +options also. + +Note: disabling C also disables C. + +=item auto_version (default:disabled) + +Automatically provide support for the B<--version> option if +the application did not specify a handler for this option itself. + +Getopt::Long will provide a standard version message that includes the +program name, its version (if $main::VERSION is defined), and the +versions of Getopt::Long and Perl. The message will be written to +standard output and processing will terminate. + +C will be enabled if the calling program explicitly +specified a version number higher than 2.32 in the C or +C statement. + +=item auto_help (default:disabled) + +Automatically provide support for the B<--help> and B<-?> options if +the application did not specify a handler for this option itself. + +Getopt::Long will provide a help message using module L. The +message, derived from the SYNOPSIS POD section, will be written to +standard output and processing will terminate. + +C will be enabled if the calling program explicitly +specified a version number higher than 2.32 in the C or +C statement. + +=item pass_through (default: disabled) + +With C anything that is unknown, ambiguous or supplied with +an invalid option will not be flagged as an error. Instead the unknown +option(s) will be passed to the catchall C<< <> >> if present, otherwise +through to C<@ARGV>. This makes it possible to write wrapper scripts that +process only part of the user supplied command line arguments, and pass the +remaining options to some other program. + +If C is enabled, options processing will terminate at the +first unrecognized option, or non-option, whichever comes first and all +remaining arguments are passed to C<@ARGV> instead of the catchall +C<< <> >> if present. However, if C is enabled instead, results +can become confusing. + +Note that the options terminator (default C<-->), if present, will +also be passed through in C<@ARGV>. + +=item prefix + +The string that starts options. If a constant string is not +sufficient, see C. + +=item prefix_pattern + +A Perl pattern that identifies the strings that introduce options. +Default is C<--|-|\+> unless environment variable +POSIXLY_CORRECT has been set, in which case it is C<--|->. + +=item long_prefix_pattern + +A Perl pattern that allows the disambiguation of long and short +prefixes. Default is C<-->. + +Typically you only need to set this if you are using nonstandard +prefixes and want some or all of them to have the same semantics as +'--' does under normal circumstances. + +For example, setting prefix_pattern to C<--|-|\+|\/> and +long_prefix_pattern to C<--|\/> would add Win32 style argument +handling. + +=item debug (default: disabled) + +Enable debugging output. + +=back + +=head1 Exportable Methods + +=over + +=item VersionMessage + +This subroutine provides a standard version message. Its argument can be: + +=over 4 + +=item * + +A string containing the text of a message to print I printing +the standard message. + +=item * + +A numeric value corresponding to the desired exit status. + +=item * + +A reference to a hash. + +=back + +If more than one argument is given then the entire argument list is +assumed to be a hash. If a hash is supplied (either as a reference or +as a list) it should contain one or more elements with the following +keys: + +=over 4 + +=item C<-message> + +=item C<-msg> + +The text of a message to print immediately prior to printing the +program's usage message. + +=item C<-exitval> + +The desired exit status to pass to the B function. +This should be an integer, or else the string "NOEXIT" to +indicate that control should simply be returned without +terminating the invoking process. + +=item C<-output> + +A reference to a filehandle, or the pathname of a file to which the +usage message should be written. The default is C<\*STDERR> unless the +exit value is less than 2 (in which case the default is C<\*STDOUT>). + +=back + +You cannot tie this routine directly to an option, e.g.: + + GetOptions("version" => \&VersionMessage); + +Use this instead: + + GetOptions("version" => sub { VersionMessage() }); + +=item HelpMessage + +This subroutine produces a standard help message, derived from the +program's POD section SYNOPSIS using L. It takes the same +arguments as VersionMessage(). In particular, you cannot tie it +directly to an option, e.g.: + + GetOptions("help" => \&HelpMessage); + +Use this instead: + + GetOptions("help" => sub { HelpMessage() }); + +=back + +=head1 Return values and Errors + +Configuration errors and errors in the option definitions are +signalled using die() and will terminate the calling program unless +the call to Getopt::Long::GetOptions() was embedded in C, or die() was trapped using C<$SIG{__DIE__}>. + +GetOptions returns true to indicate success. +It returns false when the function detected one or more errors during +option parsing. These errors are signalled using warn() and can be +trapped with C<$SIG{__WARN__}>. + +=head1 Legacy + +The earliest development of C started in 1990, with Perl +version 4. As a result, its development, and the development of +Getopt::Long, has gone through several stages. Since backward +compatibility has always been extremely important, the current version +of Getopt::Long still supports a lot of constructs that nowadays are +no longer necessary or otherwise unwanted. This section describes +briefly some of these 'features'. + +=head2 Default destinations + +When no destination is specified for an option, GetOptions will store +the resultant value in a global variable named CI, where +I is the primary name of this option. When a program executes +under C (recommended), these variables must be +pre-declared with our(). + + our $opt_length = 0; + GetOptions ('length=i'); # will store in $opt_length + +To yield a usable Perl variable, characters that are not part of the +syntax for variables are translated to underscores. For example, +C<--fpp-struct-return> will set the variable +C<$opt_fpp_struct_return>. Note that this variable resides in the +namespace of the calling program, not necessarily C
. For +example: + + GetOptions ("size=i", "sizes=i@"); + +with command line "-size 10 -sizes 24 -sizes 48" will perform the +equivalent of the assignments + + $opt_size = 10; + @opt_sizes = (24, 48); + +=head2 Alternative option starters + +A string of alternative option starter characters may be passed as the +first argument (or the first argument after a leading hash reference +argument). + + my $len = 0; + GetOptions ('/', 'length=i' => $len); + +Now the command line may look like: + + /length 24 -- arg + +Note that to terminate options processing still requires a double dash +C<-->. + +GetOptions() will not interpret a leading C<< "<>" >> as option starters +if the next argument is a reference. To force C<< "<" >> and C<< ">" >> as +option starters, use C<< "><" >>. Confusing? Well, B anyway. + +=head2 Configuration variables + +Previous versions of Getopt::Long used variables for the purpose of +configuring. Although manipulating these variables still work, it is +strongly encouraged to use the C routine that was introduced +in version 2.17. Besides, it is much easier. + +=head1 Tips and Techniques + +=head2 Pushing multiple values in a hash option + +Sometimes you want to combine the best of hashes and arrays. For +example, the command line: + + --list add=first --list add=second --list add=third + +where each successive 'list add' option will push the value of add +into array ref $list->{'add'}. The result would be like + + $list->{add} = [qw(first second third)]; + +This can be accomplished with a destination routine: + + GetOptions('list=s%' => + sub { push(@{$list{$_[1]}}, $_[2]) }); + +=head1 Troubleshooting + +=head2 GetOptions does not return a false result when an option is not supplied + +That's why they're called 'options'. + +=head2 GetOptions does not split the command line correctly + +The command line is not split by GetOptions, but by the command line +interpreter (CLI). On Unix, this is the shell. On Windows, it is +COMMAND.COM or CMD.EXE. Other operating systems have other CLIs. + +It is important to know that these CLIs may behave different when the +command line contains special characters, in particular quotes or +backslashes. For example, with Unix shells you can use single quotes +(C<'>) and double quotes (C<">) to group words together. The following +alternatives are equivalent on Unix: + + "two words" + 'two words' + two\ words + +In case of doubt, insert the following statement in front of your Perl +program: + + print STDERR (join("|",@ARGV),"\n"); + +to verify how your CLI passes the arguments to the program. + +=head2 Undefined subroutine &main::GetOptions called + +Are you running Windows, and did you write + + use GetOpt::Long; + +(note the capital 'O')? + +=head2 How do I put a "-?" option into a Getopt::Long? + +You can only obtain this using an alias, and Getopt::Long of at least +version 2.13. + + use Getopt::Long; + GetOptions ("help|?"); # -help and -? will both set $opt_help + +Other characters that can't appear in Perl identifiers are also +supported in aliases with Getopt::Long of at version 2.39. Note that +the characters C, C<|>, C<+>, C<=>, and C<:> can only appear as the +first (or only) character of an alias. + +As of version 2.32 Getopt::Long provides auto-help, a quick and easy way +to add the options --help and -? to your program, and handle them. + +See C in section L. + +=head1 AUTHOR + +Johan Vromans + +=head1 COPYRIGHT AND DISCLAIMER + +This program is Copyright 1990,2015,2023 by Johan Vromans. +This program is free software; you can redistribute it and/or +modify it under the terms of the Perl Artistic License or 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. + +If you do not have a copy of the GNU General Public License write to +the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, +MA 02139, USA. + +=cut + diff --git a/git/usr/share/perl5/core_perl/Getopt/Std.pm b/git/usr/share/perl5/core_perl/Getopt/Std.pm new file mode 100644 index 0000000000000000000000000000000000000000..855d3c1c129b2474ce962c54d63821916e1b8266 --- /dev/null +++ b/git/usr/share/perl5/core_perl/Getopt/Std.pm @@ -0,0 +1,312 @@ +package Getopt::Std; + +use strict; +use warnings; + +require Exporter; + +=head1 NAME + +Getopt::Std - Process single-character switches with switch clustering + +=head1 SYNOPSIS + + use Getopt::Std; + + getopts('oif:'); # -o & -i are boolean flags, -f takes an argument + # Sets $opt_* global variables as a side effect + getopts('oif:', \my %opts); # Options as above, values in %opts + getopt('oDI'); # -o, -D & -I take arguments + # Sets $opt_* global variables as a side effect + getopt('oDI', \my %opts); # -o, -D & -I take arg, values in %opts + +=head1 DESCRIPTION + +The C function processes single-character switches with switch +clustering. Pass one argument which is a string containing all switches to be +recognized. For each switch found, if an argument is expected and provided, +C sets C<$opt_x> (where C is the switch name) to the value of +the argument. If an argument is expected but none is provided, C<$opt_x> is +set to an undefined value. If a switch does not take an argument, C<$opt_x> +is set to C<1>. + +Switches which take an argument don't care whether there is a space between +the switch and the argument. If unspecified switches are found on the +command-line, the user will be warned that an unknown option was given. + +The C function returns true unless an invalid option was found. + +The C function is similar, but its argument is a string containing +all switches that take an argument. If no argument is provided for a switch, +say, C, the corresponding C<$opt_y> will be set to an undefined value. +Unspecified switches are silently accepted. Use of C is B. + +Note that, if your code is running under the recommended C pragma, you will need to declare these package variables +with C: + + our($opt_x, $opt_y); + +For those of you who don't like additional global variables being created, +C and C will also accept a hash reference as an optional +second argument. Hash keys will be C (where C is the switch name) with +key values the value of the argument or C<1> if no argument is specified. + +To allow programs to process arguments that look like switches, but aren't, +both functions will stop processing switches when they see the argument +C<-->. The C<--> will be removed from C<@ARGV>. + +=head1 C<--help> and C<--version> + +If C<-> is not a recognized switch letter, C supports arguments +C<--help> and C<--version>. If C and/or +C are defined, they are called; the arguments are +the output file handle, the name of option-processing package, its version, +and the switches string. If the subroutines are not defined, an attempt is +made to generate intelligent messages; for best results, define C<$main::VERSION>. + +If embedded documentation (in pod format, see L) is detected +in the script, C<--help> will also show how to access the documentation. + +Note that due to excessive paranoia, if C<$Getopt::Std::STANDARD_HELP_VERSION> +isn't true (the default is false), then the messages are printed on C, +and the processing continues after the messages are printed. This being +the opposite of the standard-conforming behaviour, it is strongly recommended +to set C<$Getopt::Std::STANDARD_HELP_VERSION> to true. + +One can change the output file handle of the messages by setting +C<$Getopt::Std::OUTPUT_HELP_VERSION>. One can print the messages of C<--help> +(without the C line) and C<--version> by calling functions C +and C with the switches string as an argument. + +=cut + +our @ISA = qw(Exporter); +our @EXPORT = qw(getopt getopts); +our $VERSION = '1.14'; +# uncomment the next line to disable 1.03-backward compatibility paranoia +# $STANDARD_HELP_VERSION = 1; + +# Process single-character switches with switch clustering. Pass one argument +# which is a string containing all switches that take an argument. For each +# switch found, sets $opt_x (where x is the switch name) to the value of the +# argument, or 1 if no argument. Switches which take an argument don't care +# whether there is a space between the switch and the argument. + +# Usage: +# getopt('oDI'); # -o, -D & -I take arg. Sets opt_* as a side effect. + +sub getopt (;$$) { + my ($argumentative, $hash) = @_; + $argumentative = '' if !defined $argumentative; + my ($first, $rest); + local $_; + local @EXPORT; + + while (@ARGV && ($_ = $ARGV[0]) =~ /^-(.)(.*)/) { + ($first, $rest) = ($1, $2); + if (/^--$/) { # early exit if -- + shift @ARGV; + last; + } + if (index($argumentative, $first) >= 0) { + if ($rest ne '') { + shift(@ARGV); + } + else { + shift(@ARGV); + $rest = shift(@ARGV); + } + if (ref $hash) { + $$hash{$first} = $rest; + } + else { + no strict 'refs'; + ${"opt_$first"} = $rest; + push( @EXPORT, "\$opt_$first" ); + } + } + else { + if (ref $hash) { + $$hash{$first} = 1; + } + else { + no strict 'refs'; + ${"opt_$first"} = 1; + push( @EXPORT, "\$opt_$first" ); + } + if ($rest ne '') { + $ARGV[0] = "-$rest"; + } + else { + shift(@ARGV); + } + } + } + unless (ref $hash) { + local $Exporter::ExportLevel = 1; + Getopt::Std->import; + } +} + +our ($OUTPUT_HELP_VERSION, $STANDARD_HELP_VERSION); +sub output_h () { + return $OUTPUT_HELP_VERSION if defined $OUTPUT_HELP_VERSION; + return \*STDOUT if $STANDARD_HELP_VERSION; + return \*STDERR; +} + +sub try_exit () { + exit 0 if $STANDARD_HELP_VERSION; + my $p = __PACKAGE__; + print {output_h()} <= 5.006; + print $h <) { + $has_pod = 1, last if /^=(pod|head1)/; + } + } + print $h <= 0) { + if (defined($args[$pos+1]) and ($args[$pos+1] eq ':')) { + shift(@ARGV); + if ($rest eq '') { + ++$errs unless @ARGV; + $rest = shift(@ARGV); + } + if (ref $hash) { + $$hash{$first} = $rest; + } + else { + no strict 'refs'; + ${"opt_$first"} = $rest; + push( @EXPORT, "\$opt_$first" ); + } + } + else { + if (ref $hash) { + $$hash{$first} = 1; + } + else { + no strict 'refs'; + ${"opt_$first"} = 1; + push( @EXPORT, "\$opt_$first" ); + } + if ($rest eq '') { + shift(@ARGV); + } + else { + $ARGV[0] = "-$rest"; + } + } + } + else { + if ($first eq '-' and $rest eq 'help') { + version_mess($argumentative, 'main'); + help_mess($argumentative, 'main'); + try_exit(); + shift(@ARGV); + next; + } elsif ($first eq '-' and $rest eq 'version') { + version_mess($argumentative, 'main'); + try_exit(); + shift(@ARGV); + next; + } + warn "Unknown option: $first\n"; + ++$errs; + if ($rest ne '') { + $ARGV[0] = "-$rest"; + } + else { + shift(@ARGV); + } + } + } + unless (ref $hash) { + local $Exporter::ExportLevel = 1; + Getopt::Std->import; + } + $errs == 0; +} + +1; diff --git a/git/usr/share/perl5/core_perl/HTTP/Tiny.pm b/git/usr/share/perl5/core_perl/HTTP/Tiny.pm new file mode 100644 index 0000000000000000000000000000000000000000..6ce4e044bb6509022674ec930f0524c14458313d --- /dev/null +++ b/git/usr/share/perl5/core_perl/HTTP/Tiny.pm @@ -0,0 +1,2581 @@ +# vim: ts=4 sts=4 sw=4 et: +package HTTP::Tiny; +use strict; +use warnings; +# ABSTRACT: A small, simple, correct HTTP/1.1 client + +our $VERSION = '0.090'; + +sub _croak { require Carp; Carp::croak(@_) } + +#pod =method new +#pod +#pod $http = HTTP::Tiny->new( %attributes ); +#pod +#pod This constructor returns a new HTTP::Tiny object. Valid attributes include: +#pod +#pod =for :list +#pod * C — A user-agent string (defaults to 'HTTP-Tiny/$VERSION'). If +#pod C — ends in a space character, the default user-agent string is +#pod appended. +#pod * C — An instance of L — or equivalent class +#pod that supports the C and C methods +#pod * C — A hashref of default headers to apply to requests +#pod * C — The local IP address to bind to +#pod * C — Whether to reuse the last connection (if for the same +#pod scheme, host and port) (defaults to 1) +#pod * C — Maximum number of redirects allowed (defaults to 5) +#pod * C — Maximum response size in bytes (only when not using a data +#pod callback). If defined, requests with responses larger than this will return +#pod a 599 status code. +#pod * C — URL of a proxy server to use for HTTP connections +#pod (default is C<$ENV{http_proxy}> — if set) +#pod * C — URL of a proxy server to use for HTTPS connections +#pod (default is C<$ENV{https_proxy}> — if set) +#pod * C — URL of a generic proxy server for both HTTP and HTTPS +#pod connections (default is C<$ENV{all_proxy}> — if set) +#pod * C — List of domain suffixes that should not be proxied. Must +#pod be a comma-separated string or an array reference. (default is +#pod C<$ENV{no_proxy}> —) +#pod * C — Request timeout in seconds (default is 60) If a socket open, +#pod read or write takes longer than the timeout, the request response status code +#pod will be 599. +#pod * C — A boolean that indicates whether to validate the TLS/SSL +#pod certificate of an C — connection (default is true). Changed from false +#pod to true in version 0.083. +#pod * C — A hashref of C — options to pass through to +#pod L +#pod * C<$ENV{PERL_HTTP_TINY_SSL_INSECURE_BY_DEFAULT}> - Changes the default +#pod certificate verification behavior to not check server identity if set to 1. +#pod Only effective if C is not set. Added in version 0.083. +#pod +#pod +#pod An accessor/mutator method exists for each attribute. +#pod +#pod Passing an explicit C for C, C or C will +#pod prevent getting the corresponding proxies from the environment. +#pod +#pod Errors during request execution will result in a pseudo-HTTP status code of 599 +#pod and a reason of "Internal Exception". The content field in the response will +#pod contain the text of the error. +#pod +#pod The C parameter enables a persistent connection, but only to a +#pod single destination scheme, host and port. If any connection-relevant +#pod attributes are modified via accessor, or if the process ID or thread ID change, +#pod the persistent connection will be dropped. If you want persistent connections +#pod across multiple destinations, use multiple HTTP::Tiny objects. +#pod +#pod See L for more on the C and C +#pod attributes. +#pod +#pod =cut + +my @attributes; +BEGIN { + @attributes = qw( + cookie_jar default_headers http_proxy https_proxy keep_alive + local_address max_redirect max_size proxy no_proxy + SSL_options verify_SSL + ); + my %persist_ok = map {; $_ => 1 } qw( + cookie_jar default_headers max_redirect max_size + ); + no strict 'refs'; + no warnings 'uninitialized'; + for my $accessor ( @attributes ) { + *{$accessor} = sub { + @_ > 1 + ? do { + delete $_[0]->{handle} if !$persist_ok{$accessor} && $_[1] ne $_[0]->{$accessor}; + $_[0]->{$accessor} = $_[1] + } + : $_[0]->{$accessor}; + }; + } +} + +sub agent { + my($self, $agent) = @_; + if( @_ > 1 ){ + $self->{agent} = + (defined $agent && $agent =~ / $/) ? $agent . $self->_agent : $agent; + } + return $self->{agent}; +} + +sub timeout { + my ($self, $timeout) = @_; + if ( @_ > 1 ) { + $self->{timeout} = $timeout; + if ($self->{handle}) { + $self->{handle}->timeout($timeout); + } + } + return $self->{timeout}; +} + +sub new { + my($class, %args) = @_; + + # Support lower case verify_ssl argument, but only if verify_SSL is not + # true. + if ( exists $args{verify_ssl} ) { + $args{verify_SSL} ||= $args{verify_ssl}; + } + + my $self = { + max_redirect => 5, + timeout => defined $args{timeout} ? $args{timeout} : 60, + keep_alive => 1, + verify_SSL => defined $args{verify_SSL} ? $args{verify_SSL} : _verify_SSL_default(), + no_proxy => $ENV{no_proxy}, + }; + + bless $self, $class; + + $class->_validate_cookie_jar( $args{cookie_jar} ) if $args{cookie_jar}; + + for my $key ( @attributes ) { + $self->{$key} = $args{$key} if exists $args{$key} + } + + $self->agent( exists $args{agent} ? $args{agent} : $class->_agent ); + + $self->_set_proxies; + + return $self; +} + +sub _verify_SSL_default { + my ($self) = @_; + # Check if insecure default certificate verification behaviour has been + # changed by the user by setting PERL_HTTP_TINY_SSL_INSECURE_BY_DEFAULT=1 + return (($ENV{PERL_HTTP_TINY_SSL_INSECURE_BY_DEFAULT} || '') eq '1') ? 0 : 1; +} + +sub _set_proxies { + my ($self) = @_; + + # get proxies from %ENV only if not provided; explicit undef will disable + # getting proxies from the environment + + # generic proxy + if (! exists $self->{proxy} ) { + $self->{proxy} = $ENV{all_proxy} || $ENV{ALL_PROXY}; + } + + if ( defined $self->{proxy} ) { + $self->_split_proxy( 'generic proxy' => $self->{proxy} ); # validate + } + else { + delete $self->{proxy}; + } + + # http proxy + if (! exists $self->{http_proxy} ) { + # under CGI, bypass HTTP_PROXY as request sets it from Proxy header + local $ENV{HTTP_PROXY} = ($ENV{CGI_HTTP_PROXY} || "") if $ENV{REQUEST_METHOD}; + $self->{http_proxy} = $ENV{http_proxy} || $ENV{HTTP_PROXY} || $self->{proxy}; + } + + if ( defined $self->{http_proxy} ) { + $self->_split_proxy( http_proxy => $self->{http_proxy} ); # validate + $self->{_has_proxy}{http} = 1; + } + else { + delete $self->{http_proxy}; + } + + # https proxy + if (! exists $self->{https_proxy} ) { + $self->{https_proxy} = $ENV{https_proxy} || $ENV{HTTPS_PROXY} || $self->{proxy}; + } + + if ( $self->{https_proxy} ) { + $self->_split_proxy( https_proxy => $self->{https_proxy} ); # validate + $self->{_has_proxy}{https} = 1; + } + else { + delete $self->{https_proxy}; + } + + # Split no_proxy to array reference if not provided as such + unless ( ref $self->{no_proxy} eq 'ARRAY' ) { + $self->{no_proxy} = + (defined $self->{no_proxy}) ? [ split /\s*,\s*/, $self->{no_proxy} ] : []; + } + + return; +} + +#pod =method get|head|put|post|patch|delete +#pod +#pod $response = $http->get($url); +#pod $response = $http->get($url, \%options); +#pod $response = $http->head($url); +#pod +#pod These methods are shorthand for calling C for the given method. The +#pod URL must have unsafe characters escaped and international domain names encoded. +#pod See C for valid options and a description of the response. +#pod +#pod The C field of the response will be true if the status code is 2XX. +#pod +#pod =cut + +for my $sub_name ( qw/get head put post patch delete/ ) { + my $req_method = uc $sub_name; + no strict 'refs'; + eval <<"HERE"; ## no critic + sub $sub_name { + my (\$self, \$url, \$args) = \@_; + \@_ == 2 || (\@_ == 3 && ref \$args eq 'HASH') + or _croak(q/Usage: \$http->$sub_name(URL, [HASHREF])/ . "\n"); + return \$self->request('$req_method', \$url, \$args || {}); + } +HERE +} + +#pod =method post_form +#pod +#pod $response = $http->post_form($url, $form_data); +#pod $response = $http->post_form($url, $form_data, \%options); +#pod +#pod This method executes a C request and sends the key/value pairs from a +#pod form data hash or array reference to the given URL with a C of +#pod C. If data is provided as an array +#pod reference, the order is preserved; if provided as a hash reference, the terms +#pod are sorted by key for consistency. See documentation for the +#pod C method for details on the encoding. +#pod +#pod The URL must have unsafe characters escaped and international domain names +#pod encoded. See C for valid options and a description of the response. +#pod Any C header or content in the options hashref will be ignored. +#pod +#pod The C field of the response will be true if the status code is 2XX. +#pod +#pod =cut + +sub post_form { + my ($self, $url, $data, $args) = @_; + (@_ == 3 || @_ == 4 && ref $args eq 'HASH') + or _croak(q/Usage: $http->post_form(URL, DATAREF, [HASHREF])/ . "\n"); + + my $headers = {}; + while ( my ($key, $value) = each %{$args->{headers} || {}} ) { + $headers->{lc $key} = $value; + } + + return $self->request('POST', $url, { + # Any existing 'headers' key in $args will be overridden with a + # normalized version below. + %$args, + content => $self->www_form_urlencode($data), + headers => { + %$headers, + 'content-type' => 'application/x-www-form-urlencoded' + }, + } + ); +} + +#pod =method mirror +#pod +#pod $response = $http->mirror($url, $file, \%options) +#pod if ( $response->{success} ) { +#pod print "$file is up to date\n"; +#pod } +#pod +#pod Executes a C request for the URL and saves the response body to the file +#pod name provided. The URL must have unsafe characters escaped and international +#pod domain names encoded. If the file already exists, the request will include an +#pod C header with the modification timestamp of the file. You +#pod may specify a different C header yourself in the C<< +#pod $options->{headers} >> hash. +#pod +#pod The C field of the response will be true if the status code is 2XX +#pod or if the status code is 304 (unmodified). +#pod +#pod If the file was modified and the server response includes a properly +#pod formatted C header, the file modification time will +#pod be updated accordingly. +#pod +#pod =cut + +sub mirror { + my ($self, $url, $file, $args) = @_; + @_ == 3 || (@_ == 4 && ref $args eq 'HASH') + or _croak(q/Usage: $http->mirror(URL, FILE, [HASHREF])/ . "\n"); + + if ( exists $args->{headers} ) { + my $headers = {}; + while ( my ($key, $value) = each %{$args->{headers} || {}} ) { + $headers->{lc $key} = $value; + } + $args->{headers} = $headers; + } + + if ( -e $file and my $mtime = (stat($file))[9] ) { + $args->{headers}{'if-modified-since'} ||= $self->_http_date($mtime); + } + my $tempfile = $file . int(rand(2**31)); + + require Fcntl; + sysopen my $fh, $tempfile, Fcntl::O_CREAT()|Fcntl::O_EXCL()|Fcntl::O_WRONLY() + or _croak(qq/Error: Could not create temporary file $tempfile for downloading: $!\n/); + binmode $fh; + $args->{data_callback} = sub { print {$fh} $_[0] }; + my $response = $self->request('GET', $url, $args); + close $fh + or _croak(qq/Error: Caught error closing temporary file $tempfile: $!\n/); + + if ( $response->{success} ) { + rename $tempfile, $file + or _croak(qq/Error replacing $file with $tempfile: $!\n/); + my $lm = $response->{headers}{'last-modified'}; + if ( $lm and my $mtime = $self->_parse_http_date($lm) ) { + utime $mtime, $mtime, $file; + } + } + $response->{success} ||= $response->{status} eq '304'; + unlink $tempfile; + return $response; +} + +#pod =method request +#pod +#pod $response = $http->request($method, $url); +#pod $response = $http->request($method, $url, \%options); +#pod +#pod Executes an HTTP request of the given method type ('GET', 'HEAD', 'POST', +#pod 'PUT', etc.) on the given URL. The URL must have unsafe characters escaped and +#pod international domain names encoded. +#pod +#pod B: Method names are B per the HTTP/1.1 specification. +#pod Don't use C when you really want C. See L for +#pod how this applies to redirection. +#pod +#pod If the URL includes a "user:password" stanza, they will be used for Basic-style +#pod authorization headers. (Authorization headers will not be included in a +#pod redirected request.) For example: +#pod +#pod $http->request('GET', 'http://Aladdin:open sesame@example.com/'); +#pod +#pod If the "user:password" stanza contains reserved characters, they must +#pod be percent-escaped: +#pod +#pod $http->request('GET', 'http://john%40example.com:password@example.com/'); +#pod +#pod A hashref of options may be appended to modify the request. +#pod +#pod Valid options are: +#pod +#pod =for :list +#pod * C — +#pod A hashref containing headers to include with the request. If the value for +#pod a header is an array reference, the header will be output multiple times with +#pod each value in the array. These headers over-write any default headers. +#pod * C — +#pod A scalar to include as the body of the request OR a code reference +#pod that will be called iteratively to produce the body of the request +#pod * C — +#pod A code reference that will be called if it exists to provide a hashref +#pod of trailing headers (only used with chunked transfer-encoding) +#pod * C — +#pod A code reference that will be called for each chunks of the response +#pod body received. +#pod * C — +#pod Override host resolution and force all connections to go only to a +#pod specific peer address, regardless of the URL of the request. This will +#pod include any redirections! This options should be used with extreme +#pod caution (e.g. debugging or very special circumstances). It can be given as +#pod either a scalar or a code reference that will receive the hostname and +#pod whose response will be taken as the address. +#pod +#pod The C header is generated from the URL in accordance with RFC 2616. It +#pod is a fatal error to specify C in the C option. Other headers +#pod may be ignored or overwritten if necessary for transport compliance. +#pod +#pod If the C option is a code reference, it will be called iteratively +#pod to provide the content body of the request. It should return the empty +#pod string or undef when the iterator is exhausted. +#pod +#pod If the C option is the empty string, no C or +#pod C headers will be generated. +#pod +#pod If the C option is provided, it will be called iteratively until +#pod the entire response body is received. The first argument will be a string +#pod containing a chunk of the response body, the second argument will be the +#pod in-progress response hash reference, as described below. (This allows +#pod customizing the action of the callback based on the C or C +#pod received prior to the content body.) +#pod +#pod Content data in the request/response is handled as "raw bytes". Any +#pod encoding/decoding (with associated headers) are the responsibility of the +#pod caller. +#pod +#pod The C method returns a hashref containing the response. The hashref +#pod will have the following keys: +#pod +#pod =for :list +#pod * C — +#pod Boolean indicating whether the operation returned a 2XX status code +#pod * C — +#pod URL that provided the response. This is the URL of the request unless +#pod there were redirections, in which case it is the last URL queried +#pod in a redirection chain +#pod * C — +#pod The HTTP status code of the response +#pod * C — +#pod The response phrase returned by the server +#pod * C — +#pod The body of the response. If the response does not have any content +#pod or if a data callback is provided to consume the response body, +#pod this will be the empty string +#pod * C — +#pod A hashref of header fields. All header field names will be normalized +#pod to be lower case. If a header is repeated, the value will be an arrayref; +#pod it will otherwise be a scalar string containing the value +#pod * C - +#pod If this field exists, it is the protocol of the response +#pod such as HTTP/1.0 or HTTP/1.1 +#pod * C +#pod If this field exists, it is an arrayref of response hash references from +#pod redirects in the same order that redirections occurred. If it does +#pod not exist, then no redirections occurred. +#pod +#pod On an error during the execution of the request, the C field will +#pod contain 599, and the C field will contain the text of the error. +#pod +#pod =cut + +my %idempotent = map { $_ => 1 } qw/GET HEAD PUT DELETE OPTIONS TRACE/; + +sub request { + my ($self, $method, $url, $args) = @_; + @_ == 3 || (@_ == 4 && ref $args eq 'HASH') + or _croak(q/Usage: $http->request(METHOD, URL, [HASHREF])/ . "\n"); + $args ||= {}; # we keep some state in this during _request + + # RFC 2616 Section 8.1.4 mandates a single retry on broken socket + my $response; + for ( 0 .. 1 ) { + $response = eval { $self->_request($method, $url, $args) }; + last unless $@ && $idempotent{$method} + && $@ =~ m{^(?:Socket closed|Unexpected end|SSL read error)}; + } + + if (my $e = $@) { + # maybe we got a response hash thrown from somewhere deep + if ( ref $e eq 'HASH' && exists $e->{status} ) { + $e->{redirects} = delete $args->{_redirects} if @{ $args->{_redirects} || []}; + return $e; + } + + # otherwise, stringify it + $e = "$e"; + $response = { + url => $url, + success => q{}, + status => 599, + reason => 'Internal Exception', + content => $e, + headers => { + 'content-type' => 'text/plain', + 'content-length' => length $e, + }, + ( @{$args->{_redirects} || []} ? (redirects => delete $args->{_redirects}) : () ), + }; + } + return $response; +} + +#pod =method www_form_urlencode +#pod +#pod $params = $http->www_form_urlencode( $data ); +#pod $response = $http->get("http://example.com/query?$params"); +#pod +#pod This method converts the key/value pairs from a data hash or array reference +#pod into a C string. The keys and values from the data +#pod reference will be UTF-8 encoded and escaped per RFC 3986. If a value is an +#pod array reference, the key will be repeated with each of the values of the array +#pod reference. If data is provided as a hash reference, the key/value pairs in the +#pod resulting string will be sorted by key and value for consistent ordering. +#pod +#pod =cut + +sub www_form_urlencode { + my ($self, $data) = @_; + (@_ == 2 && ref $data) + or _croak(q/Usage: $http->www_form_urlencode(DATAREF)/ . "\n"); + (ref $data eq 'HASH' || ref $data eq 'ARRAY') + or _croak("form data must be a hash or array reference\n"); + + my @params + = ref $data eq 'HASH' + ? map { ($_ => $data->{$_}) } sort keys %$data + : @$data; + @params % 2 == 0 + or _croak("form data reference must have an even number of terms\n"); + + my @terms; + while( @params ) { + my ($key, $value) = splice(@params, 0, 2); + _croak("form data keys must not be undef") + if !defined($key); + if ( ref $value eq 'ARRAY' ) { + unshift @params, map { $key => $_ } @$value; + } + else { + push @terms, join("=", map { $self->_uri_escape($_) } $key, $value); + } + } + + return join("&", @terms); +} + +#pod =method can_ssl +#pod +#pod $ok = HTTP::Tiny->can_ssl; +#pod ($ok, $why) = HTTP::Tiny->can_ssl; +#pod ($ok, $why) = $http->can_ssl; +#pod +#pod Indicates if SSL support is available. When called as a class object, it +#pod checks for the correct version of L and L. +#pod When called as an object methods, if C is true or if C +#pod is set in C, it checks that a CA file is available. +#pod +#pod In scalar context, returns a boolean indicating if SSL is available. +#pod In list context, returns the boolean and a (possibly multi-line) string of +#pod errors indicating why SSL isn't available. +#pod +#pod =cut + +sub can_ssl { + my ($self) = @_; + + my($ok, $reason) = (1, ''); + + # Need IO::Socket::SSL 1.968 for default_ca() + local @INC = @INC; + pop @INC if $INC[-1] eq '.'; + unless (eval {require IO::Socket::SSL; IO::Socket::SSL->VERSION(1.968)}) { + $ok = 0; + $reason .= qq/IO::Socket::SSL 1.968 or later must be installed for https support\n/; + } + + # Need Net::SSLeay 1.49 for MODE_AUTO_RETRY + unless (eval {require Net::SSLeay; Net::SSLeay->VERSION(1.49)}) { + $ok = 0; + $reason .= qq/Net::SSLeay 1.49 or later must be installed for https support\n/; + } + + # If an object, check that SSL config lets us get a CA if necessary + if ( ref($self) && ( $self->{verify_SSL} || $self->{SSL_options}{SSL_verify_mode} ) ) { + my $handle = HTTP::Tiny::Handle->new( + SSL_options => $self->{SSL_options}, + verify_SSL => $self->{verify_SSL}, + ); + unless ( eval { $handle->_find_CA; 1 } ) { + $ok = 0; + $reason .= "$@"; + } + } + + wantarray ? ($ok, $reason) : $ok; +} + +#pod =method connected +#pod +#pod $host = $http->connected; +#pod ($host, $port) = $http->connected; +#pod +#pod Indicates if a connection to a peer is being kept alive, per the C +#pod option. +#pod +#pod In scalar context, returns the peer host and port, joined with a colon, or +#pod C (if no peer is connected). +#pod In list context, returns the peer host and port or an empty list (if no peer +#pod is connected). +#pod +#pod B: This method cannot reliably be used to discover whether the remote +#pod host has closed its end of the socket. +#pod +#pod =cut + +sub connected { + my ($self) = @_; + + if ( $self->{handle} ) { + return $self->{handle}->connected; + } + return; +} + +#--------------------------------------------------------------------------# +# private methods +#--------------------------------------------------------------------------# + +my %DefaultPort = ( + http => 80, + https => 443, +); + +sub _agent { + my $class = ref($_[0]) || $_[0]; + (my $default_agent = $class) =~ s{::}{-}g; + my $version = $class->VERSION; + $default_agent .= "/$version" if defined $version; + return $default_agent; +} + +sub _request { + my ($self, $method, $url, $args) = @_; + + my ($scheme, $host, $port, $path_query, $auth) = $self->_split_url($url); + + if ($scheme ne 'http' && $scheme ne 'https') { + die(qq/Unsupported URL scheme '$scheme'\n/); + } + + my $request = { + method => $method, + scheme => $scheme, + host => $host, + port => $port, + host_port => ($port == $DefaultPort{$scheme} ? $host : "$host:$port"), + uri => $path_query, + headers => {}, + }; + + my $peer = $args->{peer} || $host; + + # Allow 'peer' to be a coderef. + if ('CODE' eq ref $peer) { + $peer = $peer->($host); + } + + # We remove the cached handle so it is not reused in the case of redirect. + # If all is well, it will be recached at the end of _request. We only + # reuse for the same scheme, host and port + my $handle = delete $self->{handle}; + if ( $handle ) { + unless ( $handle->can_reuse( $scheme, $host, $port, $peer ) ) { + $handle->close; + undef $handle; + } + } + $handle ||= $self->_open_handle( $request, $scheme, $host, $port, $peer ); + + $self->_prepare_headers_and_cb($request, $args, $url, $auth); + $handle->write_request($request); + + my $response; + do { $response = $handle->read_response_header } + until (substr($response->{status},0,1) ne '1'); + + $self->_update_cookie_jar( $url, $response ) if $self->{cookie_jar}; + my @redir_args = $self->_maybe_redirect($request, $response, $args); + + my $known_message_length; + if ($method eq 'HEAD' || $response->{status} =~ /^[23]04/) { + # response has no message body + $known_message_length = 1; + } + else { + # Ignore any data callbacks during redirection. + my $cb_args = @redir_args ? +{} : $args; + my $data_cb = $self->_prepare_data_cb($response, $cb_args); + $known_message_length = $handle->read_body($data_cb, $response); + } + + if ( $self->{keep_alive} + && $handle->connected + && $known_message_length + && $response->{protocol} eq 'HTTP/1.1' + && ($response->{headers}{connection} || '') ne 'close' + ) { + $self->{handle} = $handle; + } + else { + $handle->close; + } + + $response->{success} = substr( $response->{status}, 0, 1 ) eq '2'; + $response->{url} = $url; + + # Push the current response onto the stack of redirects if redirecting. + if (@redir_args) { + push @{$args->{_redirects}}, $response; + return $self->_request(@redir_args, $args); + } + + # Copy the stack of redirects into the response before returning. + $response->{redirects} = delete $args->{_redirects} + if @{$args->{_redirects}}; + return $response; +} + +sub _open_handle { + my ($self, $request, $scheme, $host, $port, $peer) = @_; + + my $handle = HTTP::Tiny::Handle->new( + timeout => $self->{timeout}, + SSL_options => $self->{SSL_options}, + verify_SSL => $self->{verify_SSL}, + local_address => $self->{local_address}, + keep_alive => $self->{keep_alive} + ); + + if ($self->{_has_proxy}{$scheme} && ! grep { $host =~ /\Q$_\E$/ } @{$self->{no_proxy}}) { + return $self->_proxy_connect( $request, $handle ); + } + else { + return $handle->connect($scheme, $host, $port, $peer); + } +} + +sub _proxy_connect { + my ($self, $request, $handle) = @_; + + my @proxy_vars; + if ( $request->{scheme} eq 'https' ) { + _croak(qq{No https_proxy defined}) unless $self->{https_proxy}; + @proxy_vars = $self->_split_proxy( https_proxy => $self->{https_proxy} ); + if ( $proxy_vars[0] eq 'https' ) { + _croak(qq{Can't proxy https over https: $request->{uri} via $self->{https_proxy}}); + } + } + else { + _croak(qq{No http_proxy defined}) unless $self->{http_proxy}; + @proxy_vars = $self->_split_proxy( http_proxy => $self->{http_proxy} ); + } + + my ($p_scheme, $p_host, $p_port, $p_auth) = @proxy_vars; + + if ( length $p_auth && ! defined $request->{headers}{'proxy-authorization'} ) { + $self->_add_basic_auth_header( $request, 'proxy-authorization' => $p_auth ); + } + + $handle->connect($p_scheme, $p_host, $p_port, $p_host); + + if ($request->{scheme} eq 'https') { + $self->_create_proxy_tunnel( $request, $handle ); + } + else { + # non-tunneled proxy requires absolute URI + $request->{uri} = "$request->{scheme}://$request->{host_port}$request->{uri}"; + } + + return $handle; +} + +sub _split_proxy { + my ($self, $type, $proxy) = @_; + + my ($scheme, $host, $port, $path_query, $auth) = eval { $self->_split_url($proxy) }; + + unless( + defined($scheme) && length($scheme) && length($host) && length($port) + && $path_query eq '/' + ) { + _croak(qq{$type URL must be in format http[s]://[auth@]:/\n}); + } + + return ($scheme, $host, $port, $auth); +} + +sub _create_proxy_tunnel { + my ($self, $request, $handle) = @_; + + $handle->_assert_ssl; + + my $agent = exists($request->{headers}{'user-agent'}) + ? $request->{headers}{'user-agent'} : $self->{agent}; + + my $connect_request = { + method => 'CONNECT', + uri => "$request->{host}:$request->{port}", + headers => { + host => "$request->{host}:$request->{port}", + 'user-agent' => $agent, + } + }; + + if ( $request->{headers}{'proxy-authorization'} ) { + $connect_request->{headers}{'proxy-authorization'} = + delete $request->{headers}{'proxy-authorization'}; + } + + $handle->write_request($connect_request); + my $response; + do { $response = $handle->read_response_header } + until (substr($response->{status},0,1) ne '1'); + + # if CONNECT failed, throw the response so it will be + # returned from the original request() method; + unless (substr($response->{status},0,1) eq '2') { + die $response; + } + + # tunnel established, so start SSL handshake + $handle->start_ssl( $request->{host} ); + + return; +} + +sub _prepare_headers_and_cb { + my ($self, $request, $args, $url, $auth) = @_; + + for ($self->{default_headers}, $args->{headers}) { + next unless defined; + while (my ($k, $v) = each %$_) { + $request->{headers}{lc $k} = $v; + $request->{header_case}{lc $k} = $k; + } + } + + if (exists $request->{headers}{'host'}) { + die(qq/The 'Host' header must not be provided as header option\n/); + } + + $request->{headers}{'host'} = $request->{host_port}; + $request->{headers}{'user-agent'} ||= $self->{agent}; + $request->{headers}{'connection'} = "close" + unless $self->{keep_alive}; + + # Some servers error on an empty-body PUT/POST without a content-length + if ( $request->{method} eq 'PUT' || $request->{method} eq 'POST' ) { + if (!defined($args->{content}) || !length($args->{content}) ) { + $request->{headers}{'content-length'} = 0; + } + } + + if ( defined $args->{content} ) { + if ( ref $args->{content} eq 'CODE' ) { + if ( exists $request->{'content-length'} && $request->{'content-length'} == 0 ) { + $request->{cb} = sub { "" }; + } + else { + $request->{headers}{'content-type'} ||= "application/octet-stream"; + $request->{headers}{'transfer-encoding'} = 'chunked' + unless exists $request->{headers}{'content-length'} + || $request->{headers}{'transfer-encoding'}; + $request->{cb} = $args->{content}; + } + } + elsif ( length $args->{content} ) { + my $content = $args->{content}; + if ( $] ge '5.008' ) { + utf8::downgrade($content, 1) + or die(qq/Wide character in request message body\n/); + } + $request->{headers}{'content-type'} ||= "application/octet-stream"; + $request->{headers}{'content-length'} = length $content + unless $request->{headers}{'content-length'} + || $request->{headers}{'transfer-encoding'}; + $request->{cb} = sub { substr $content, 0, length $content, '' }; + } + $request->{trailer_cb} = $args->{trailer_callback} + if ref $args->{trailer_callback} eq 'CODE'; + } + + ### If we have a cookie jar, then maybe add relevant cookies + if ( $self->{cookie_jar} ) { + my $cookies = $self->cookie_jar->cookie_header( $url ); + $request->{headers}{cookie} = $cookies if length $cookies; + } + + # if we have Basic auth parameters, add them + if ( length $auth && ! defined $request->{headers}{authorization} ) { + $self->_add_basic_auth_header( $request, 'authorization' => $auth ); + } + + return; +} + +sub _add_basic_auth_header { + my ($self, $request, $header, $auth) = @_; + require MIME::Base64; + $request->{headers}{$header} = + "Basic " . MIME::Base64::encode_base64($auth, ""); + return; +} + +sub _prepare_data_cb { + my ($self, $response, $args) = @_; + my $data_cb = $args->{data_callback}; + $response->{content} = ''; + + if (!$data_cb || $response->{status} !~ /^2/) { + if (defined $self->{max_size}) { + $data_cb = sub { + $_[1]->{content} .= $_[0]; + die(qq/Size of response body exceeds the maximum allowed of $self->{max_size}\n/) + if length $_[1]->{content} > $self->{max_size}; + }; + } + else { + $data_cb = sub { $_[1]->{content} .= $_[0] }; + } + } + return $data_cb; +} + +sub _update_cookie_jar { + my ($self, $url, $response) = @_; + + my $cookies = $response->{headers}->{'set-cookie'}; + return unless defined $cookies; + + my @cookies = ref $cookies ? @$cookies : $cookies; + + $self->cookie_jar->add( $url, $_ ) for @cookies; + + return; +} + +sub _validate_cookie_jar { + my ($class, $jar) = @_; + + # duck typing + for my $method ( qw/add cookie_header/ ) { + _croak(qq/Cookie jar must provide the '$method' method\n/) + unless ref($jar) && ref($jar)->can($method); + } + + return; +} + +sub _maybe_redirect { + my ($self, $request, $response, $args) = @_; + my $headers = $response->{headers}; + my ($status, $method) = ($response->{status}, $request->{method}); + $args->{_redirects} ||= []; + + if (($status eq '303' or ($status =~ /^30[1278]/ && $method =~ /^GET|HEAD$/)) + and $headers->{location} + and @{$args->{_redirects}} < $self->{max_redirect} + ) { + my $location = ($headers->{location} =~ /^\//) + ? "$request->{scheme}://$request->{host_port}$headers->{location}" + : $headers->{location} ; + return (($status eq '303' ? 'GET' : $method), $location); + } + return; +} + +sub _split_url { + my $url = pop; + + # URI regex adapted from the URI module + my ($scheme, $host, $path_query) = $url =~ m<\A([^:/?#]+)://([^/?#]*)([^#]*)> + or die(qq/Cannot parse URL: '$url'\n/); + + $scheme = lc $scheme; + $path_query = "/$path_query" unless $path_query =~ m<\A/>; + + my $auth = ''; + if ( (my $i = index $host, '@') != -1 ) { + # user:pass@host + $auth = substr $host, 0, $i, ''; # take up to the @ for auth + substr $host, 0, 1, ''; # knock the @ off the host + + # userinfo might be percent escaped, so recover real auth info + $auth =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg; + } + my $port = $host =~ s/:(\d*)\z// && length $1 ? $1 + : $scheme eq 'http' ? 80 + : $scheme eq 'https' ? 443 + : undef; + + return ($scheme, (length $host ? lc $host : "localhost") , $port, $path_query, $auth); +} + +# Date conversions adapted from HTTP::Date +my $DoW = "Sun|Mon|Tue|Wed|Thu|Fri|Sat"; +my $MoY = "Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec"; +sub _http_date { + my ($sec, $min, $hour, $mday, $mon, $year, $wday) = gmtime($_[1]); + return sprintf("%s, %02d %s %04d %02d:%02d:%02d GMT", + substr($DoW,$wday*4,3), + $mday, substr($MoY,$mon*4,3), $year+1900, + $hour, $min, $sec + ); +} + +sub _parse_http_date { + my ($self, $str) = @_; + require Time::Local; + my @tl_parts; + if ($str =~ /^[SMTWF][a-z]+, +(\d{1,2}) ($MoY) +(\d\d\d\d) +(\d\d):(\d\d):(\d\d) +GMT$/) { + @tl_parts = ($6, $5, $4, $1, (index($MoY,$2)/4), $3); + } + elsif ($str =~ /^[SMTWF][a-z]+, +(\d\d)-($MoY)-(\d{2,4}) +(\d\d):(\d\d):(\d\d) +GMT$/ ) { + @tl_parts = ($6, $5, $4, $1, (index($MoY,$2)/4), $3); + } + elsif ($str =~ /^[SMTWF][a-z]+ +($MoY) +(\d{1,2}) +(\d\d):(\d\d):(\d\d) +(?:[^0-9]+ +)?(\d\d\d\d)$/ ) { + @tl_parts = ($5, $4, $3, $2, (index($MoY,$1)/4), $6); + } + return eval { + my $t = @tl_parts ? Time::Local::timegm(@tl_parts) : -1; + $t < 0 ? undef : $t; + }; +} + +# URI escaping adapted from URI::Escape +# c.f. http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1 +# perl 5.6 ready UTF-8 encoding adapted from JSON::PP +my %escapes = map { chr($_) => sprintf("%%%02X", $_) } 0..255; +$escapes{' '}="+"; +my $unsafe_char = qr/[^A-Za-z0-9\-\._~]/; + +sub _uri_escape { + my ($self, $str) = @_; + return "" if !defined $str; + if ( $] ge '5.008' ) { + utf8::encode($str); + } + else { + $str = pack("U*", unpack("C*", $str)) # UTF-8 encode a byte string + if ( length $str == do { use bytes; length $str } ); + $str = pack("C*", unpack("C*", $str)); # clear UTF-8 flag + } + $str =~ s/($unsafe_char)/$escapes{$1}/g; + return $str; +} + +package + HTTP::Tiny::Handle; # hide from PAUSE/indexers +use strict; +use warnings; + +use Errno qw[EINTR EPIPE]; +use IO::Socket qw[SOCK_STREAM]; +use Socket qw[SOL_SOCKET SO_KEEPALIVE]; + +# PERL_HTTP_TINY_IPV4_ONLY is a private environment variable to force old +# behavior if someone is unable to boostrap CPAN from a new perl install; it is +# not intended for general, per-client use and may be removed in the future +my $SOCKET_CLASS = + $ENV{PERL_HTTP_TINY_IPV4_ONLY} ? 'IO::Socket::INET' : + eval { require IO::Socket::IP; IO::Socket::IP->VERSION(0.32) } ? 'IO::Socket::IP' : + 'IO::Socket::INET'; + +sub BUFSIZE () { 32768 } ## no critic + +my $Printable = sub { + local $_ = shift; + s/\r/\\r/g; + s/\n/\\n/g; + s/\t/\\t/g; + s/([^\x20-\x7E])/sprintf('\\x%.2X', ord($1))/ge; + $_; +}; + +my $Token = qr/[\x21\x23-\x27\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5A\x5E-\x7A\x7C\x7E]/; +my $Field_Content = qr/[[:print:]]+ (?: [\x20\x09]+ [[:print:]]+ )*/x; + +sub new { + my ($class, %args) = @_; + return bless { + rbuf => '', + timeout => 60, + max_line_size => 16384, + max_header_lines => 64, + verify_SSL => HTTP::Tiny::_verify_SSL_default(), + SSL_options => {}, + %args + }, $class; +} + +sub timeout { + my ($self, $timeout) = @_; + if ( @_ > 1 ) { + $self->{timeout} = $timeout; + if ( $self->{fh} && $self->{fh}->can('timeout') ) { + $self->{fh}->timeout($timeout); + } + } + return $self->{timeout}; +} + +sub connect { + @_ == 5 || die(q/Usage: $handle->connect(scheme, host, port, peer)/ . "\n"); + my ($self, $scheme, $host, $port, $peer) = @_; + + if ( $scheme eq 'https' ) { + $self->_assert_ssl; + } + + $self->{fh} = $SOCKET_CLASS->new( + PeerHost => $peer, + PeerPort => $port, + $self->{local_address} ? + ( LocalAddr => $self->{local_address} ) : (), + Proto => 'tcp', + Type => SOCK_STREAM, + Timeout => $self->{timeout}, + ) or die(qq/Could not connect to '$host:$port': $@\n/); + + binmode($self->{fh}) + or die(qq/Could not binmode() socket: '$!'\n/); + + if ( $self->{keep_alive} ) { + unless ( defined( $self->{fh}->setsockopt( SOL_SOCKET, SO_KEEPALIVE, 1 ) ) ) { + CORE::close($self->{fh}); + die(qq/Could not set SO_KEEPALIVE on socket: '$!'\n/); + } + } + + $self->start_ssl($host) if $scheme eq 'https'; + + $self->{scheme} = $scheme; + $self->{host} = $host; + $self->{peer} = $peer; + $self->{port} = $port; + $self->{pid} = $$; + $self->{tid} = _get_tid(); + + return $self; +} + +sub connected { + my ($self) = @_; + if ( $self->{fh} && $self->{fh}->connected ) { + return wantarray + ? ( $self->{fh}->peerhost, $self->{fh}->peerport ) + : join( ':', $self->{fh}->peerhost, $self->{fh}->peerport ); + } + return; +} + +sub start_ssl { + my ($self, $host) = @_; + + # As this might be used via CONNECT after an SSL session + # to a proxy, we shut down any existing SSL before attempting + # the handshake + if ( ref($self->{fh}) eq 'IO::Socket::SSL' ) { + unless ( $self->{fh}->stop_SSL ) { + my $ssl_err = IO::Socket::SSL->errstr; + die(qq/Error halting prior SSL connection: $ssl_err/); + } + } + + my $ssl_args = $self->_ssl_args($host); + IO::Socket::SSL->start_SSL( + $self->{fh}, + %$ssl_args, + SSL_create_ctx_callback => sub { + my $ctx = shift; + Net::SSLeay::CTX_set_mode($ctx, Net::SSLeay::MODE_AUTO_RETRY()); + }, + ); + + unless ( ref($self->{fh}) eq 'IO::Socket::SSL' ) { + my $ssl_err = IO::Socket::SSL->errstr; + die(qq/SSL connection failed for $host: $ssl_err\n/); + } +} + +sub close { + @_ == 1 || die(q/Usage: $handle->close()/ . "\n"); + my ($self) = @_; + CORE::close($self->{fh}) + or die(qq/Could not close socket: '$!'\n/); +} + +sub write { + @_ == 2 || die(q/Usage: $handle->write(buf)/ . "\n"); + my ($self, $buf) = @_; + + if ( $] ge '5.008' ) { + utf8::downgrade($buf, 1) + or die(qq/Wide character in write()\n/); + } + + my $len = length $buf; + my $off = 0; + + local $SIG{PIPE} = 'IGNORE'; + + while () { + $self->can_write + or die(qq/Timed out while waiting for socket to become ready for writing\n/); + my $r = syswrite($self->{fh}, $buf, $len, $off); + if (defined $r) { + $len -= $r; + $off += $r; + last unless $len > 0; + } + elsif ($! == EPIPE) { + die(qq/Socket closed by remote server: $!\n/); + } + elsif ($! != EINTR) { + if ($self->{fh}->can('errstr')){ + my $err = $self->{fh}->errstr(); + die (qq/Could not write to SSL socket: '$err'\n /); + } + else { + die(qq/Could not write to socket: '$!'\n/); + } + + } + } + return $off; +} + +sub read { + @_ == 2 || @_ == 3 || die(q/Usage: $handle->read(len [, allow_partial])/ . "\n"); + my ($self, $len, $allow_partial) = @_; + + my $buf = ''; + my $got = length $self->{rbuf}; + + if ($got) { + my $take = ($got < $len) ? $got : $len; + $buf = substr($self->{rbuf}, 0, $take, ''); + $len -= $take; + } + + # Ignore SIGPIPE because SSL reads can result in writes that might error. + # See "Expecting exactly the same behavior as plain sockets" in + # https://metacpan.org/dist/IO-Socket-SSL/view/lib/IO/Socket/SSL.pod#Common-Usage-Errors + local $SIG{PIPE} = 'IGNORE'; + + while ($len > 0) { + $self->can_read + or die(q/Timed out while waiting for socket to become ready for reading/ . "\n"); + my $r = sysread($self->{fh}, $buf, $len, length $buf); + if (defined $r) { + last unless $r; + $len -= $r; + } + elsif ($! != EINTR) { + if ($self->{fh}->can('errstr')){ + my $err = $self->{fh}->errstr(); + die (qq/Could not read from SSL socket: '$err'\n /); + } + else { + die(qq/Could not read from socket: '$!'\n/); + } + } + } + if ($len && !$allow_partial) { + die(qq/Unexpected end of stream\n/); + } + return $buf; +} + +sub readline { + @_ == 1 || die(q/Usage: $handle->readline()/ . "\n"); + my ($self) = @_; + + while () { + if ($self->{rbuf} =~ s/\A ([^\x0D\x0A]* \x0D?\x0A)//x) { + return $1; + } + if (length $self->{rbuf} >= $self->{max_line_size}) { + die(qq/Line size exceeds the maximum allowed size of $self->{max_line_size}\n/); + } + $self->can_read + or die(qq/Timed out while waiting for socket to become ready for reading\n/); + my $r = sysread($self->{fh}, $self->{rbuf}, BUFSIZE, length $self->{rbuf}); + if (defined $r) { + last unless $r; + } + elsif ($! != EINTR) { + if ($self->{fh}->can('errstr')){ + my $err = $self->{fh}->errstr(); + die (qq/Could not read from SSL socket: '$err'\n /); + } + else { + die(qq/Could not read from socket: '$!'\n/); + } + } + } + die(qq/Unexpected end of stream while looking for line\n/); +} + +sub read_header_lines { + @_ == 1 || @_ == 2 || die(q/Usage: $handle->read_header_lines([headers])/ . "\n"); + my ($self, $headers) = @_; + $headers ||= {}; + my $lines = 0; + my $val; + + while () { + my $line = $self->readline; + + if (++$lines >= $self->{max_header_lines}) { + die(qq/Header lines exceeds maximum number allowed of $self->{max_header_lines}\n/); + } + elsif ($line =~ /\A ([^\x00-\x1F\x7F:]+) : [\x09\x20]* ([^\x0D\x0A]*)/x) { + my ($field_name) = lc $1; + if (exists $headers->{$field_name}) { + for ($headers->{$field_name}) { + $_ = [$_] unless ref $_ eq "ARRAY"; + push @$_, $2; + $val = \$_->[-1]; + } + } + else { + $val = \($headers->{$field_name} = $2); + } + } + elsif ($line =~ /\A [\x09\x20]+ ([^\x0D\x0A]*)/x) { + $val + or die(qq/Unexpected header continuation line\n/); + next unless length $1; + $$val .= ' ' if length $$val; + $$val .= $1; + } + elsif ($line =~ /\A \x0D?\x0A \z/x) { + last; + } + else { + die(q/Malformed header line: / . $Printable->($line) . "\n"); + } + } + return $headers; +} + +sub write_request { + @_ == 2 || die(q/Usage: $handle->write_request(request)/ . "\n"); + my($self, $request) = @_; + $self->write_request_header(@{$request}{qw/method uri headers header_case/}); + $self->write_body($request) if $request->{cb}; + return; +} + +# Standard request header names/case from HTTP/1.1 RFCs +my @rfc_request_headers = qw( + Accept Accept-Charset Accept-Encoding Accept-Language Authorization + Cache-Control Connection Content-Length Expect From Host + If-Match If-Modified-Since If-None-Match If-Range If-Unmodified-Since + Max-Forwards Pragma Proxy-Authorization Range Referer TE Trailer + Transfer-Encoding Upgrade User-Agent Via +); + +my @other_request_headers = qw( + Content-Encoding Content-MD5 Content-Type Cookie DNT Date Origin + X-XSS-Protection +); + +my %HeaderCase = map { lc($_) => $_ } @rfc_request_headers, @other_request_headers; + +# to avoid multiple small writes and hence nagle, you can pass the method line or anything else to +# combine writes. +sub write_header_lines { + (@_ >= 2 && @_ <= 4 && ref $_[1] eq 'HASH') || die(q/Usage: $handle->write_header_lines(headers, [header_case, prefix])/ . "\n"); + my($self, $headers, $header_case, $prefix_data) = @_; + $header_case ||= {}; + + my $buf = (defined $prefix_data ? $prefix_data : ''); + + # Per RFC, control fields should be listed first + my %seen; + for my $k ( qw/host cache-control expect max-forwards pragma range te/ ) { + next unless exists $headers->{$k}; + $seen{$k}++; + my $field_name = $HeaderCase{$k}; + my $v = $headers->{$k}; + for (ref $v eq 'ARRAY' ? @$v : $v) { + $_ = '' unless defined $_; + $buf .= "$field_name: $_\x0D\x0A"; + } + } + + # Other headers sent in arbitrary order + while (my ($k, $v) = each %$headers) { + my $field_name = lc $k; + next if $seen{$field_name}; + if (exists $HeaderCase{$field_name}) { + $field_name = $HeaderCase{$field_name}; + } + else { + if (exists $header_case->{$field_name}) { + $field_name = $header_case->{$field_name}; + } + else { + $field_name =~ s/\b(\w)/\u$1/g; + } + $field_name =~ /\A $Token+ \z/xo + or die(q/Invalid HTTP header field name: / . $Printable->($field_name) . "\n"); + $HeaderCase{lc $field_name} = $field_name; + } + for (ref $v eq 'ARRAY' ? @$v : $v) { + # unwrap a field value if pre-wrapped by user + s/\x0D?\x0A\s+/ /g; + die(qq/Invalid HTTP header field value ($field_name): / . $Printable->($_). "\n") + unless $_ eq '' || /\A $Field_Content \z/xo; + $_ = '' unless defined $_; + $buf .= "$field_name: $_\x0D\x0A"; + } + } + $buf .= "\x0D\x0A"; + return $self->write($buf); +} + +# return value indicates whether message length was defined; this is generally +# true unless there was no content-length header and we just read until EOF. +# Other message length errors are thrown as exceptions +sub read_body { + @_ == 3 || die(q/Usage: $handle->read_body(callback, response)/ . "\n"); + my ($self, $cb, $response) = @_; + my $te = $response->{headers}{'transfer-encoding'} || ''; + my $chunked = grep { /chunked/i } ( ref $te eq 'ARRAY' ? @$te : $te ) ; + return $chunked + ? $self->read_chunked_body($cb, $response) + : $self->read_content_body($cb, $response); +} + +sub write_body { + @_ == 2 || die(q/Usage: $handle->write_body(request)/ . "\n"); + my ($self, $request) = @_; + if (exists $request->{headers}{'content-length'}) { + return unless $request->{headers}{'content-length'}; + return $self->write_content_body($request); + } + else { + return $self->write_chunked_body($request); + } +} + +sub read_content_body { + @_ == 3 || @_ == 4 || die(q/Usage: $handle->read_content_body(callback, response, [read_length])/ . "\n"); + my ($self, $cb, $response, $content_length) = @_; + $content_length ||= $response->{headers}{'content-length'}; + + if ( defined $content_length ) { + my $len = $content_length; + while ($len > 0) { + my $read = ($len > BUFSIZE) ? BUFSIZE : $len; + $cb->($self->read($read, 0), $response); + $len -= $read; + } + return length($self->{rbuf}) == 0; + } + + my $chunk; + $cb->($chunk, $response) while length( $chunk = $self->read(BUFSIZE, 1) ); + + return; +} + +sub write_content_body { + @_ == 2 || die(q/Usage: $handle->write_content_body(request)/ . "\n"); + my ($self, $request) = @_; + + my ($len, $content_length) = (0, $request->{headers}{'content-length'}); + while () { + my $data = $request->{cb}->(); + + defined $data && length $data + or last; + + if ( $] ge '5.008' ) { + utf8::downgrade($data, 1) + or die(qq/Wide character in write_content()\n/); + } + + $len += $self->write($data); + } + + $len == $content_length + or die(qq/Content-Length mismatch (got: $len expected: $content_length)\n/); + + return $len; +} + +sub read_chunked_body { + @_ == 3 || die(q/Usage: $handle->read_chunked_body(callback, $response)/ . "\n"); + my ($self, $cb, $response) = @_; + + while () { + my $head = $self->readline; + + $head =~ /\A ([A-Fa-f0-9]+)/x + or die(q/Malformed chunk head: / . $Printable->($head) . "\n"); + + my $len = hex($1) + or last; + + $self->read_content_body($cb, $response, $len); + + $self->read(2) eq "\x0D\x0A" + or die(qq/Malformed chunk: missing CRLF after chunk data\n/); + } + $self->read_header_lines($response->{headers}); + return 1; +} + +sub write_chunked_body { + @_ == 2 || die(q/Usage: $handle->write_chunked_body(request)/ . "\n"); + my ($self, $request) = @_; + + my $len = 0; + while () { + my $data = $request->{cb}->(); + + defined $data && length $data + or last; + + if ( $] ge '5.008' ) { + utf8::downgrade($data, 1) + or die(qq/Wide character in write_chunked_body()\n/); + } + + $len += length $data; + + my $chunk = sprintf '%X', length $data; + $chunk .= "\x0D\x0A"; + $chunk .= $data; + $chunk .= "\x0D\x0A"; + + $self->write($chunk); + } + $self->write("0\x0D\x0A"); + if ( ref $request->{trailer_cb} eq 'CODE' ) { + $self->write_header_lines($request->{trailer_cb}->()) + } + else { + $self->write("\x0D\x0A"); + } + return $len; +} + +sub read_response_header { + @_ == 1 || die(q/Usage: $handle->read_response_header()/ . "\n"); + my ($self) = @_; + + my $line = $self->readline; + + $line =~ /\A (HTTP\/(0*\d+\.0*\d+)) [\x09\x20]+ ([0-9]{3}) (?: [\x09\x20]+ ([^\x0D\x0A]*) )? \x0D?\x0A/x + or die(q/Malformed Status-Line: / . $Printable->($line). "\n"); + + my ($protocol, $version, $status, $reason) = ($1, $2, $3, $4); + $reason = "" unless defined $reason; + + die (qq/Unsupported HTTP protocol: $protocol\n/) + unless $version =~ /0*1\.0*[01]/; + + return { + status => $status, + reason => $reason, + headers => $self->read_header_lines, + protocol => $protocol, + }; +} + +sub write_request_header { + @_ == 5 || die(q/Usage: $handle->write_request_header(method, request_uri, headers, header_case)/ . "\n"); + my ($self, $method, $request_uri, $headers, $header_case) = @_; + + return $self->write_header_lines($headers, $header_case, "$method $request_uri HTTP/1.1\x0D\x0A"); +} + +sub _do_timeout { + my ($self, $type, $timeout) = @_; + $timeout = $self->{timeout} + unless defined $timeout && $timeout >= 0; + + my $fd = fileno $self->{fh}; + defined $fd && $fd >= 0 + or die(qq/select(2): 'Bad file descriptor'\n/); + + my $initial = time; + my $pending = $timeout; + my $nfound; + + vec(my $fdset = '', $fd, 1) = 1; + + while () { + $nfound = ($type eq 'read') + ? select($fdset, undef, undef, $pending) + : select(undef, $fdset, undef, $pending) ; + if ($nfound == -1) { + $! == EINTR + or die(qq/select(2): '$!'\n/); + redo if !$timeout || ($pending = $timeout - (time - $initial)) > 0; + $nfound = 0; + } + last; + } + $! = 0; + return $nfound; +} + +sub can_read { + @_ == 1 || @_ == 2 || die(q/Usage: $handle->can_read([timeout])/ . "\n"); + my $self = shift; + if ( ref($self->{fh}) eq 'IO::Socket::SSL' ) { + return 1 if $self->{fh}->pending; + } + return $self->_do_timeout('read', @_) +} + +sub can_write { + @_ == 1 || @_ == 2 || die(q/Usage: $handle->can_write([timeout])/ . "\n"); + my $self = shift; + return $self->_do_timeout('write', @_) +} + +sub _assert_ssl { + my($ok, $reason) = HTTP::Tiny->can_ssl(); + die $reason unless $ok; +} + +sub can_reuse { + my ($self,$scheme,$host,$port,$peer) = @_; + return 0 if + $self->{pid} != $$ + || $self->{tid} != _get_tid() + || length($self->{rbuf}) + || $scheme ne $self->{scheme} + || $host ne $self->{host} + || $port ne $self->{port} + || $peer ne $self->{peer} + || eval { $self->can_read(0) } + || $@ ; + return 1; +} + +sub _find_CA { + my $self = shift; + + my $ca_file = $self->{SSL_options}->{SSL_ca_file}; + + if ( defined $ca_file ) { + unless ( -r $ca_file ) { + die qq/SSL_ca_file '$ca_file' not found or not readable\n/; + } + return ( SSL_ca_file => $ca_file ); + } + + # Return default_ca() parameters from IO::Socket::SSL. It looks for the + # default bundle and directory from Net::SSLeay, handles $ENV{SSL_CERT_FILE} + # and $ENV{SSL_CERT_DIR}, and finally fails over to Mozilla::CA + # + my %default_ca = IO::Socket::SSL::default_ca(); + return %default_ca if %default_ca; + + # If IO::Socket::SSL::default_ca() was unable to find a CA bundle, look for + # one in well known locations as a last resort. Cert list copied from golang + # src/crypto/x509/root_unix.go + # + foreach my $ca_bundle ( + "/etc/ssl/certs/ca-certificates.crt", # Debian/Ubuntu/Gentoo etc. + "/etc/pki/tls/certs/ca-bundle.crt", # Fedora/RHEL + "/etc/ssl/ca-bundle.pem", # OpenSUSE + "/etc/openssl/certs/ca-certificates.crt", # NetBSD + "/etc/ssl/cert.pem", # OpenBSD + "/usr/local/share/certs/ca-root-nss.crt", # FreeBSD/DragonFly + "/etc/pki/tls/cacert.pem", # OpenELEC + "/etc/certs/ca-certificates.crt", # Solaris 11.2+ + ) { + return ( SSL_ca_file => $ca_bundle ) if -e $ca_bundle; + } + + die qq/Couldn't find a CA bundle with which to verify the SSL certificate.\n/ + . qq/Try installing one from your OS vendor, or Mozilla::CA from CPAN\n/; +} + +# not for internal use; backcompat shim only +sub _find_CA_file { + my $self = shift; + my %res = $self->_find_CA(); + return $res{SSL_ca_file}; +} + +# for thread safety, we need to know thread id if threads are loaded +sub _get_tid { + no warnings 'reserved'; # for 'threads' + return threads->can("tid") ? threads->tid : 0; +} + +sub _ssl_args { + my ($self, $host) = @_; + + my %ssl_args; + + # This test reimplements IO::Socket::SSL::can_client_sni(), which wasn't + # added until IO::Socket::SSL 1.84 + if ( Net::SSLeay::OPENSSL_VERSION_NUMBER() >= 0x01000000 ) { + $ssl_args{SSL_hostname} = $host, # Sane SNI support + } + + if ($self->{verify_SSL}) { + $ssl_args{SSL_verifycn_scheme} = 'http'; # enable CN validation + $ssl_args{SSL_verifycn_name} = $host; # set validation hostname + $ssl_args{SSL_verify_mode} = 0x01; # enable cert validation + + %ssl_args = ( %ssl_args, $self->_find_CA ); + } + else { + $ssl_args{SSL_verifycn_scheme} = 'none'; # disable CN validation + $ssl_args{SSL_verify_mode} = 0x00; # disable cert validation + } + + # user options override settings from verify_SSL + for my $k ( keys %{$self->{SSL_options}} ) { + $ssl_args{$k} = $self->{SSL_options}{$k} if $k =~ m/^SSL_/; + } + + return \%ssl_args; +} + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +HTTP::Tiny - A small, simple, correct HTTP/1.1 client + +=head1 VERSION + +version 0.090 + +=head1 SYNOPSIS + + use HTTP::Tiny; + + my $response = HTTP::Tiny->new->get('http://example.com/'); + + die "Failed!\n" unless $response->{success}; + + print "$response->{status} $response->{reason}\n"; + + while (my ($k, $v) = each %{$response->{headers}}) { + for (ref $v eq 'ARRAY' ? @$v : $v) { + print "$k: $_\n"; + } + } + + print $response->{content} if length $response->{content}; + +=head1 DESCRIPTION + +This is a very simple HTTP/1.1 client, designed for doing simple +requests without the overhead of a large framework like L. + +It is more correct and more complete than L. It supports +proxies and redirection. It also correctly resumes after EINTR. + +If L 0.25 or later is installed, HTTP::Tiny will use it instead +of L for transparent support for both IPv4 and IPv6. + +Cookie support requires L or an equivalent class. + +=head1 METHODS + +=head2 new + + $http = HTTP::Tiny->new( %attributes ); + +This constructor returns a new HTTP::Tiny object. Valid attributes include: + +=over 4 + +=item * + +C — A user-agent string (defaults to 'HTTP-Tiny/$VERSION'). If C — ends in a space character, the default user-agent string is appended. + +=item * + +C — An instance of L — or equivalent class that supports the C and C methods + +=item * + +C — A hashref of default headers to apply to requests + +=item * + +C — The local IP address to bind to + +=item * + +C — Whether to reuse the last connection (if for the same scheme, host and port) (defaults to 1) + +=item * + +C — Maximum number of redirects allowed (defaults to 5) + +=item * + +C — Maximum response size in bytes (only when not using a data callback). If defined, requests with responses larger than this will return a 599 status code. + +=item * + +C — URL of a proxy server to use for HTTP connections (default is C<$ENV{http_proxy}> — if set) + +=item * + +C — URL of a proxy server to use for HTTPS connections (default is C<$ENV{https_proxy}> — if set) + +=item * + +C — URL of a generic proxy server for both HTTP and HTTPS connections (default is C<$ENV{all_proxy}> — if set) + +=item * + +C — List of domain suffixes that should not be proxied. Must be a comma-separated string or an array reference. (default is C<$ENV{no_proxy}> —) + +=item * + +C — Request timeout in seconds (default is 60) If a socket open, read or write takes longer than the timeout, the request response status code will be 599. + +=item * + +C — A boolean that indicates whether to validate the TLS/SSL certificate of an C — connection (default is true). Changed from false to true in version 0.083. + +=item * + +C — A hashref of C — options to pass through to L + +=item * + +C<$ENV{PERL_HTTP_TINY_SSL_INSECURE_BY_DEFAULT}> - Changes the default certificate verification behavior to not check server identity if set to 1. Only effective if C is not set. Added in version 0.083. + +=back + +An accessor/mutator method exists for each attribute. + +Passing an explicit C for C, C or C will +prevent getting the corresponding proxies from the environment. + +Errors during request execution will result in a pseudo-HTTP status code of 599 +and a reason of "Internal Exception". The content field in the response will +contain the text of the error. + +The C parameter enables a persistent connection, but only to a +single destination scheme, host and port. If any connection-relevant +attributes are modified via accessor, or if the process ID or thread ID change, +the persistent connection will be dropped. If you want persistent connections +across multiple destinations, use multiple HTTP::Tiny objects. + +See L for more on the C and C +attributes. + +=head2 get|head|put|post|patch|delete + + $response = $http->get($url); + $response = $http->get($url, \%options); + $response = $http->head($url); + +These methods are shorthand for calling C for the given method. The +URL must have unsafe characters escaped and international domain names encoded. +See C for valid options and a description of the response. + +The C field of the response will be true if the status code is 2XX. + +=head2 post_form + + $response = $http->post_form($url, $form_data); + $response = $http->post_form($url, $form_data, \%options); + +This method executes a C request and sends the key/value pairs from a +form data hash or array reference to the given URL with a C of +C. If data is provided as an array +reference, the order is preserved; if provided as a hash reference, the terms +are sorted by key for consistency. See documentation for the +C method for details on the encoding. + +The URL must have unsafe characters escaped and international domain names +encoded. See C for valid options and a description of the response. +Any C header or content in the options hashref will be ignored. + +The C field of the response will be true if the status code is 2XX. + +=head2 mirror + + $response = $http->mirror($url, $file, \%options) + if ( $response->{success} ) { + print "$file is up to date\n"; + } + +Executes a C request for the URL and saves the response body to the file +name provided. The URL must have unsafe characters escaped and international +domain names encoded. If the file already exists, the request will include an +C header with the modification timestamp of the file. You +may specify a different C header yourself in the C<< +$options->{headers} >> hash. + +The C field of the response will be true if the status code is 2XX +or if the status code is 304 (unmodified). + +If the file was modified and the server response includes a properly +formatted C header, the file modification time will +be updated accordingly. + +=head2 request + + $response = $http->request($method, $url); + $response = $http->request($method, $url, \%options); + +Executes an HTTP request of the given method type ('GET', 'HEAD', 'POST', +'PUT', etc.) on the given URL. The URL must have unsafe characters escaped and +international domain names encoded. + +B: Method names are B per the HTTP/1.1 specification. +Don't use C when you really want C. See L for +how this applies to redirection. + +If the URL includes a "user:password" stanza, they will be used for Basic-style +authorization headers. (Authorization headers will not be included in a +redirected request.) For example: + + $http->request('GET', 'http://Aladdin:open sesame@example.com/'); + +If the "user:password" stanza contains reserved characters, they must +be percent-escaped: + + $http->request('GET', 'http://john%40example.com:password@example.com/'); + +A hashref of options may be appended to modify the request. + +Valid options are: + +=over 4 + +=item * + +C — A hashref containing headers to include with the request. If the value for a header is an array reference, the header will be output multiple times with each value in the array. These headers over-write any default headers. + +=item * + +C — A scalar to include as the body of the request OR a code reference that will be called iteratively to produce the body of the request + +=item * + +C — A code reference that will be called if it exists to provide a hashref of trailing headers (only used with chunked transfer-encoding) + +=item * + +C — A code reference that will be called for each chunks of the response body received. + +=item * + +C — Override host resolution and force all connections to go only to a specific peer address, regardless of the URL of the request. This will include any redirections! This options should be used with extreme caution (e.g. debugging or very special circumstances). It can be given as either a scalar or a code reference that will receive the hostname and whose response will be taken as the address. + +=back + +The C header is generated from the URL in accordance with RFC 2616. It +is a fatal error to specify C in the C option. Other headers +may be ignored or overwritten if necessary for transport compliance. + +If the C option is a code reference, it will be called iteratively +to provide the content body of the request. It should return the empty +string or undef when the iterator is exhausted. + +If the C option is the empty string, no C or +C headers will be generated. + +If the C option is provided, it will be called iteratively until +the entire response body is received. The first argument will be a string +containing a chunk of the response body, the second argument will be the +in-progress response hash reference, as described below. (This allows +customizing the action of the callback based on the C or C +received prior to the content body.) + +Content data in the request/response is handled as "raw bytes". Any +encoding/decoding (with associated headers) are the responsibility of the +caller. + +The C method returns a hashref containing the response. The hashref +will have the following keys: + +=over 4 + +=item * + +C — Boolean indicating whether the operation returned a 2XX status code + +=item * + +C — URL that provided the response. This is the URL of the request unless there were redirections, in which case it is the last URL queried in a redirection chain + +=item * + +C — The HTTP status code of the response + +=item * + +C — The response phrase returned by the server + +=item * + +C — The body of the response. If the response does not have any content or if a data callback is provided to consume the response body, this will be the empty string + +=item * + +C — A hashref of header fields. All header field names will be normalized to be lower case. If a header is repeated, the value will be an arrayref; it will otherwise be a scalar string containing the value + +=item * + +C - If this field exists, it is the protocol of the response such as HTTP/1.0 or HTTP/1.1 + +=item * + +C If this field exists, it is an arrayref of response hash references from redirects in the same order that redirections occurred. If it does not exist, then no redirections occurred. + +=back + +On an error during the execution of the request, the C field will +contain 599, and the C field will contain the text of the error. + +=head2 www_form_urlencode + + $params = $http->www_form_urlencode( $data ); + $response = $http->get("http://example.com/query?$params"); + +This method converts the key/value pairs from a data hash or array reference +into a C string. The keys and values from the data +reference will be UTF-8 encoded and escaped per RFC 3986. If a value is an +array reference, the key will be repeated with each of the values of the array +reference. If data is provided as a hash reference, the key/value pairs in the +resulting string will be sorted by key and value for consistent ordering. + +=head2 can_ssl + + $ok = HTTP::Tiny->can_ssl; + ($ok, $why) = HTTP::Tiny->can_ssl; + ($ok, $why) = $http->can_ssl; + +Indicates if SSL support is available. When called as a class object, it +checks for the correct version of L and L. +When called as an object methods, if C is true or if C +is set in C, it checks that a CA file is available. + +In scalar context, returns a boolean indicating if SSL is available. +In list context, returns the boolean and a (possibly multi-line) string of +errors indicating why SSL isn't available. + +=head2 connected + + $host = $http->connected; + ($host, $port) = $http->connected; + +Indicates if a connection to a peer is being kept alive, per the C +option. + +In scalar context, returns the peer host and port, joined with a colon, or +C (if no peer is connected). +In list context, returns the peer host and port or an empty list (if no peer +is connected). + +B: This method cannot reliably be used to discover whether the remote +host has closed its end of the socket. + +=for Pod::Coverage SSL_options +agent +cookie_jar +default_headers +http_proxy +https_proxy +keep_alive +local_address +max_redirect +max_size +no_proxy +proxy +timeout +verify_SSL + +=head1 TLS/SSL SUPPORT + +Direct C connections are supported only if L 1.56 or +greater and L 1.49 or greater are installed. An error will occur +if new enough versions of these modules are not installed or if the TLS +encryption fails. You can also use C utility function +that returns boolean to see if the required modules are installed. + +An C connection may be made via an C proxy that supports the CONNECT +command (i.e. RFC 2817). You may not proxy C via a proxy that itself +requires C to communicate. + +TLS/SSL provides two distinct capabilities: + +=over 4 + +=item * + +Encrypted communication channel + +=item * + +Verification of server identity + +=back + +B. + +This was changed in version 0.083 due to security concerns. The previous default +behavior can be enabled by setting C<$ENV{PERL_HTTP_TINY_SSL_INSECURE_BY_DEFAULT}> +to 1. + +Verification is done by checking that that the TLS/SSL connection has a valid +certificate corresponding to the host name of the connection and that the +certificate has been verified by a CA. Assuming you trust the CA, this will +protect against L. + +Certificate verification requires a file or directory containing trusted CA +certificates. + +C is called to detect the default location of +your CA certificates. This also supports the environment variables +C and C, and will fail over to L if no +certs are found. + +If C is not able to find usable CA certificates, +HTTP::Tiny will search several well-known system-specific default locations for +a CA certificate file as a last resort: + +=over 4 + +=item * + +/etc/ssl/certs/ca-certificates.crt + +=item * + +/etc/pki/tls/certs/ca-bundle.crt + +=item * + +/etc/ssl/ca-bundle.pem + +=item * + +/etc/openssl/certs/ca-certificates.crt + +=item * + +/etc/ssl/cert.pem + +=item * + +/usr/local/share/certs/ca-root-nss.crt + +=item * + +/etc/pki/tls/cacert.pem + +=item * + +/etc/certs/ca-certificates.crt + +=back + +An error will be occur if C is true and no CA certificate file +is available. + +If you desire complete control over TLS/SSL connections, the C +attribute lets you provide a hash reference that will be passed through to +C, overriding any options set by HTTP::Tiny. For +example, to provide your own trusted CA file: + + SSL_options => { + SSL_ca_file => $file_path, + } + +The C attribute could also be used for such things as providing a +client certificate for authentication to a server or controlling the choice of +cipher used for the TLS/SSL connection. See L documentation for +details. + +=head1 PROXY SUPPORT + +HTTP::Tiny can proxy both C and C requests. Only Basic proxy +authorization is supported and it must be provided as part of the proxy URL: +C. + +HTTP::Tiny supports the following proxy environment variables: + +=over 4 + +=item * + +http_proxy or HTTP_PROXY + +=item * + +https_proxy or HTTPS_PROXY + +=item * + +all_proxy or ALL_PROXY + +=back + +If the C environment variable is set, then this might be a CGI +process and C would be set from the C header, which is a +security risk. If C is set, C (the upper case +variant only) is ignored, but C is considered instead. + +Tunnelling C over an C proxy using the CONNECT method is +supported. If your proxy uses C itself, you can not tunnel C +over it. + +Be warned that proxying an C connection opens you to the risk of a +man-in-the-middle attack by the proxy server. + +The C environment variable is supported in the format of a +comma-separated list of domain extensions proxy should not be used for. + +Proxy arguments passed to C will override their corresponding +environment variables. + +=head1 LIMITATIONS + +HTTP::Tiny is I with the +L: + +=over 4 + +=item * + +"Message Syntax and Routing" [RFC7230] + +=item * + +"Semantics and Content" [RFC7231] + +=item * + +"Conditional Requests" [RFC7232] + +=item * + +"Range Requests" [RFC7233] + +=item * + +"Caching" [RFC7234] + +=item * + +"Authentication" [RFC7235] + +=back + +It attempts to meet all "MUST" requirements of the specification, but does not +implement all "SHOULD" requirements. (Note: it was developed against the +earlier RFC 2616 specification and may not yet meet the revised RFC 7230-7235 +spec.) Additionally, HTTP::Tiny supports the C method of RFC 5789. + +Some particular limitations of note include: + +=over + +=item * + +HTTP::Tiny focuses on correct transport. Users are responsible for ensuring +that user-defined headers and content are compliant with the HTTP/1.1 +specification. + +=item * + +Users must ensure that URLs are properly escaped for unsafe characters and that +international domain names are properly encoded to ASCII. See L, +L and L. + +=item * + +Redirection is very strict against the specification. Redirection is only +automatic for response codes 301, 302, 307 and 308 if the request method is +'GET' or 'HEAD'. Response code 303 is always converted into a 'GET' +redirection, as mandated by the specification. There is no automatic support +for status 305 ("Use proxy") redirections. + +=item * + +There is no provision for delaying a request body using an C header. +Unexpected C<1XX> responses are silently ignored as per the specification. + +=item * + +Only 'chunked' C is supported. + +=item * + +There is no support for a Request-URI of '*' for the 'OPTIONS' request. + +=item * + +Headers mentioned in the RFCs and some other, well-known headers are +generated with their canonical case. Other headers are sent in the +case provided by the user. Except for control headers (which are sent first), +headers are sent in arbitrary order. + +=back + +Despite the limitations listed above, HTTP::Tiny is considered +feature-complete. New feature requests should be directed to +L. + +=head1 SEE ALSO + +=over 4 + +=item * + +L - Higher level UA features for HTTP::Tiny + +=item * + +L - HTTP::Tiny wrapper with L/L compatibility + +=item * + +L - Wrap L instance in HTTP::Tiny compatible interface + +=item * + +L - Required for IPv6 support + +=item * + +L - Required for SSL support + +=item * + +L - If HTTP::Tiny isn't enough for you, this is the "standard" way to do things + +=item * + +L - Required for SSL support + +=back + +=for :stopwords cpan testmatrix url bugtracker rt cpants kwalitee diff irc mailto metadata placeholders metacpan + +=head1 SUPPORT + +=head2 Bugs / Feature Requests + +Please report any bugs or feature requests through the issue tracker +at L. +You will be notified automatically of any progress on your issue. + +=head2 Source Code + +This is open source software. The code repository is available for +public review and contribution under the terms of the license. + +L + + git clone https://github.com/Perl-Toolchain-Gang/HTTP-Tiny.git + +=head1 AUTHORS + +=over 4 + +=item * + +Christian Hansen + +=item * + +David Golden + +=back + +=head1 CONTRIBUTORS + +=for stopwords Alan Gardner Alessandro Ghedini A. Sinan Unur Brad Gilbert brian m. carlson Chris Nehren Weyl Claes Jakobsson Clinton Gormley Craig Berry David Golden Mitchell Dean Pearce Edward Zborowski Felipe Gasper Graham Knop Greg Kennedy James E Keenan Raspass Jeremy Mates Jess Robinson Karen Etheridge Lukas Eklund Martin J. Evans Martin-Louis Bright Matthew Horsfall Michael R. Davis Mike Doherty Nicolas Rochelemagne Olaf Alders Olivier Mengué Petr Písař sanjay-cpu Serguei Trouchelle Shoichi Kaji SkyMarshal Sören Kornetzki Steve Grazzini Stig Palmquist Syohei YOSHIDA Tatsuhiko Miyagawa Tom Hukins Tony Cook Xavier Guimard + +=over 4 + +=item * + +Alan Gardner + +=item * + +Alessandro Ghedini + +=item * + +A. Sinan Unur + +=item * + +Brad Gilbert + +=item * + +brian m. carlson + +=item * + +Chris Nehren + +=item * + +Chris Weyl + +=item * + +Claes Jakobsson + +=item * + +Clinton Gormley + +=item * + +Craig A. Berry + +=item * + +David Golden + +=item * + +David Mitchell + +=item * + +Dean Pearce + +=item * + +Edward Zborowski + +=item * + +Felipe Gasper + +=item * + +Graham Knop + +=item * + +Greg Kennedy + +=item * + +James E Keenan + +=item * + +James Raspass + +=item * + +Jeremy Mates + +=item * + +Jess Robinson + +=item * + +Karen Etheridge + +=item * + +Lukas Eklund + +=item * + +Martin J. Evans + +=item * + +Martin-Louis Bright + +=item * + +Matthew Horsfall + +=item * + +Michael R. Davis + +=item * + +Mike Doherty + +=item * + +Nicolas Rochelemagne + +=item * + +Olaf Alders + +=item * + +Olivier Mengué + +=item * + +Petr Písař + +=item * + +sanjay-cpu + +=item * + +Serguei Trouchelle + +=item * + +Shoichi Kaji + +=item * + +SkyMarshal + +=item * + +Sören Kornetzki + +=item * + +Steve Grazzini + +=item * + +Stig Palmquist + +=item * + +Syohei YOSHIDA + +=item * + +Tatsuhiko Miyagawa + +=item * + +Tom Hukins + +=item * + +Tony Cook + +=item * + +Xavier Guimard + +=back + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2024 by Christian Hansen. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/core_perl/I18N/Collate.pm b/git/usr/share/perl5/core_perl/I18N/Collate.pm new file mode 100644 index 0000000000000000000000000000000000000000..e080fe6eabc065a3b7f3f7a4b601b5485d963c41 --- /dev/null +++ b/git/usr/share/perl5/core_perl/I18N/Collate.pm @@ -0,0 +1,196 @@ +package I18N::Collate; + +use strict; +our $VERSION = '1.02'; + +=head1 NAME + +I18N::Collate - compare 8-bit scalar data according to the current locale + +=head1 SYNOPSIS + + use I18N::Collate; + setlocale(LC_COLLATE, 'locale-of-your-choice'); + $s1 = I18N::Collate->new("scalar_data_1"); + $s2 = I18N::Collate->new("scalar_data_2"); + +=head1 DESCRIPTION + + *** + + WARNING: starting from the Perl version 5.003_06 + the I18N::Collate interface for comparing 8-bit scalar data + according to the current locale + + HAS BEEN DEPRECATED + + That is, please do not use it anymore for any new applications + and please migrate the old applications away from it because its + functionality was integrated into the Perl core language in the + release 5.003_06. + + See the perllocale manual page for further information. + + *** + +This module provides you with objects that will collate +according to your national character set, provided that the +POSIX setlocale() function is supported on your system. + +You can compare $s1 and $s2 above with + + $s1 le $s2 + +to extract the data itself, you'll need a dereference: $$s1 + +This module uses POSIX::setlocale(). The basic collation conversion is +done by strxfrm() which terminates at NUL characters being a decent C +routine. collate_xfrm() handles embedded NUL characters gracefully. + +The available locales depend on your operating system; try whether +C shows them or man pages for "locale" or "nlsinfo" or the +direct approach C or C or +C. Not all the locales that your vendor supports +are necessarily installed: please consult your operating system's +documentation and possibly your local system administration. The +locale names are probably something like C or +C, for example C is the Swiss (CH) +variant of French (fr), ISO Latin (8859) 1 (-1) which is the Western +European character set. + +=cut + +# I18N::Collate.pm +# +# Author: Jarkko Hietaniemi > +# Helsinki University of Technology, Finland +# +# Acks: Guy Decoux > understood +# overloading magic much deeper than I and told +# how to cut the size of this code by more than half. +# (my first version did overload all of lt gt eq le ge cmp) +# +# Purpose: compare 8-bit scalar data according to the current locale +# +# Requirements: Perl5 POSIX::setlocale() and POSIX::strxfrm() +# +# Exports: setlocale 1) +# collate_xfrm 2) +# +# Overloads: cmp # 3) +# +# Usage: use I18N::Collate; +# setlocale(LC_COLLATE, 'locale-of-your-choice'); # 4) +# $s1 = I18N::Collate->("scalar_data_1"); +# $s2 = I18N::Collate->("scalar_data_2"); +# +# now you can compare $s1 and $s2: $s1 le $s2 +# to extract the data itself, you need to deref: $$s1 +# +# Notes: +# 1) this uses POSIX::setlocale +# 2) the basic collation conversion is done by strxfrm() which +# terminates at NUL characters being a decent C routine. +# collate_xfrm handles embedded NUL characters gracefully. +# 3) due to cmp and overload magic, lt le eq ge gt work also +# 4) the available locales depend on your operating system; +# try whether "locale -a" shows them or man pages for +# "locale" or "nlsinfo" work or the more direct +# approach "ls /usr/lib/nls/loc" or "ls /usr/lib/nls". +# Not all the locales that your vendor supports +# are necessarily installed: please consult your +# operating system's documentation. +# The locale names are probably something like +# 'xx_XX.(ISO)?8859-N' or 'xx_XX.(ISO)?8859N', +# for example 'fr_CH.ISO8859-1' is the Swiss (CH) +# variant of French (fr), ISO Latin (8859) 1 (-1) +# which is the Western European character set. +# +# Updated: 19961005 +# +# --- + +use POSIX qw(strxfrm LC_COLLATE); +use warnings::register; + +require Exporter; + +our @ISA = qw(Exporter); +our @EXPORT = qw(collate_xfrm setlocale LC_COLLATE); +our @EXPORT_OK = qw(); + +use overload qw( +fallback 1 +cmp collate_cmp +); + +our($LOCALE, $C); + +our $please_use_I18N_Collate_even_if_deprecated = 0; +sub new { + my $new = $_[1]; + + if (warnings::enabled() && $] >= 5.003_06) { + unless ($please_use_I18N_Collate_even_if_deprecated) { + warnings::warn <<___EOD___; +*** + + WARNING: starting from the Perl version 5.003_06 + the I18N::Collate interface for comparing 8-bit scalar data + according to the current locale + + HAS BEEN DEPRECATED + + That is, please do not use it anymore for any new applications + and please migrate the old applications away from it because its + functionality was integrated into the Perl core language in the + release 5.003_06. + + See the perllocale manual page for further information. + +*** +___EOD___ + $please_use_I18N_Collate_even_if_deprecated++; + } + } + + bless \$new; +} + +sub setlocale { + my ($category, $locale) = @_[0,1]; + + POSIX::setlocale($category, $locale) if (defined $category); + # the current $LOCALE + $LOCALE = $locale || $ENV{'LC_COLLATE'} || $ENV{'LC_ALL'} || ''; +} + +sub C { + my $s = ${$_[0]}; + + $C->{$LOCALE}->{$s} = collate_xfrm($s) + unless (defined $C->{$LOCALE}->{$s}); # cache when met + + $C->{$LOCALE}->{$s}; +} + +sub collate_xfrm { + my $s = $_[0]; + my $x = ''; + + for (split(/(\000+)/, $s)) { + $x .= (/^\000/) ? $_ : strxfrm("$_\000"); + } + + $x; +} + +sub collate_cmp { + &C($_[0]) cmp &C($_[1]); +} + +# init $LOCALE + +&I18N::Collate::setlocale(); + +1; # keep require happy diff --git a/git/usr/share/perl5/core_perl/autodie/Util.pm b/git/usr/share/perl5/core_perl/autodie/Util.pm new file mode 100644 index 0000000000000000000000000000000000000000..9917ead71ef71d417060266348de1dc0f9bbd4ee --- /dev/null +++ b/git/usr/share/perl5/core_perl/autodie/Util.pm @@ -0,0 +1,250 @@ +package autodie::Util; + +use strict; +use warnings; + +use Exporter 5.57 qw(import); + +use autodie::Scope::GuardStack; + +our @EXPORT_OK = qw( + fill_protos + install_subs + make_core_trampoline + on_end_of_compile_scope +); + +our $VERSION = '2.37'; # VERSION: Generated by DZP::OurPkg:Version + +# ABSTRACT: Internal Utility subroutines for autodie and Fatal + +# docs says we should pick __PACKAGE__ / +my $H_STACK_KEY = __PACKAGE__ . '/stack'; + +sub on_end_of_compile_scope { + my ($hook) = @_; + + # Dark magic to have autodie work under 5.8 + # Copied from namespace::clean, that copied it from + # autobox, that found it on an ancient scroll written + # in blood. + + # This magic bit causes %^H to be lexically scoped. + $^H |= 0x020000; + + my $stack = $^H{$H_STACK_KEY}; + if (not defined($stack)) { + $stack = autodie::Scope::GuardStack->new; + $^H{$H_STACK_KEY} = $stack; + } + + $stack->push_hook($hook); + return; +} + +# This code is based on code from the original Fatal. The "XXXX" +# remark is from the original code and its meaning is (sadly) unknown. +sub fill_protos { + my ($proto) = @_; + my ($n, $isref, @out, @out1, $seen_semi) = -1; + if ($proto =~ m{^\s* (?: [;] \s*)? \@}x) { + # prototype is entirely slurply - special case that does not + # require any handling. + return ([0, '@_']); + } + + while ($proto =~ /\S/) { + $n++; + push(@out1,[$n,@out]) if $seen_semi; + push(@out, $1 . "{\$_[$n]}"), next if $proto =~ s/^\s*\\([\@%\$\&])//; + push(@out, "\$_[$n]"), next if $proto =~ s/^\s*([_*\$&])//; + push(@out, "\@_[$n..\$#_]"), last if $proto =~ s/^\s*(;\s*)?\@//; + $seen_semi = 1, $n--, next if $proto =~ s/^\s*;//; # XXXX ???? + die "Internal error: Unknown prototype letters: \"$proto\""; + } + push(@out1,[$n+1,@out]); + return @out1; +} + + +sub make_core_trampoline { + my ($call, $pkg, $proto_str) = @_; + my $trampoline_code = 'sub {'; + my $trampoline_sub; + my @protos = fill_protos($proto_str); + + foreach my $proto (@protos) { + local $" = ", "; # So @args is formatted correctly. + my ($count, @args) = @$proto; + if (@args && $args[-1] =~ m/[@#]_/) { + $trampoline_code .= qq/ + if (\@_ >= $count) { + return $call(@args); + } + /; + } else { + $trampoline_code .= qq< + if (\@_ == $count) { + return $call(@args); + } + >; + } + } + + $trampoline_code .= qq< require Carp; Carp::croak("Internal error in Fatal/autodie. Leak-guard failure"); } >; + my $E; + + { + local $@; + $trampoline_sub = eval "package $pkg;\n $trampoline_code"; ## no critic + $E = $@; + } + die "Internal error in Fatal/autodie: Leak-guard installation failure: $E" + if $E; + + return $trampoline_sub; +} + +# The code here is originally lifted from namespace::clean, +# by Robert "phaylon" Sedlacek. +# +# It's been redesigned after feedback from ikegami on perlmonks. +# See http://perlmonks.org/?node_id=693338 . Ikegami rocks. +# +# Given a package, and hash of (subname => subref) pairs, +# we install the given subroutines into the package. If +# a subref is undef, the subroutine is removed. Otherwise +# it replaces any existing subs which were already there. + +sub install_subs { + my ($target_pkg, $subs_to_reinstate) = @_; + + my $pkg_sym = "${target_pkg}::"; + + # It does not hurt to do this in a predictable order, and might help debugging. + foreach my $sub_name (sort keys(%{$subs_to_reinstate})) { + + # We will repeatedly mess with stuff that strict "refs" does + # not like. So lets just disable it once for this entire + # scope. + no strict qw(refs); ## no critic + + my $sub_ref = $subs_to_reinstate->{$sub_name}; + + my $full_path = ${pkg_sym}.${sub_name}; + my $oldglob = *$full_path; + + # Nuke the old glob. + delete($pkg_sym->{$sub_name}); + + # For some reason this local *alias = *$full_path triggers an + # "only used once" warning. Not entirely sure why, but at + # least it is easy to silence. + no warnings qw(once); + local *alias = *$full_path; + use warnings qw(once); + + # Copy innocent bystanders back. Note that we lose + # formats; it seems that Perl versions up to 5.10.0 + # have a bug which causes copying formats to end up in + # the scalar slot. Thanks to Ben Morrow for spotting this. + + foreach my $slot (qw( SCALAR ARRAY HASH IO ) ) { + next unless defined(*$oldglob{$slot}); + *alias = *$oldglob{$slot}; + } + + if ($sub_ref) { + *$full_path = $sub_ref; + } + } + + return; +} + +1; + +__END__ + +=head1 NAME + +autodie::Util - Internal Utility subroutines for autodie and Fatal + +=head1 SYNOPSIS + + # INTERNAL API for autodie and Fatal only! + + use autodie::Util qw(on_end_of_compile_scope); + on_end_of_compile_scope(sub { print "Hallo world\n"; }); + +=head1 DESCRIPTION + +Internal Utilities for autodie and Fatal! This module is not a part of +autodie's public API. + +This module contains utility subroutines for abstracting away the +underlying magic of autodie and (ab)uses of C<%^H> to call subs at the +end of a (compile-time) scopes. + +Note that due to how C<%^H> works, some of these utilities are only +useful during the compilation phase of a perl module and relies on the +internals of how perl handles references in C<%^H>. + +=head2 Methods + +=head3 on_end_of_compile_scope + + on_end_of_compile_scope(sub { print "Hallo world\n"; }); + +Will invoke a sub at the end of a (compile-time) scope. The sub is +called once with no arguments. Can be called multiple times (even in +the same "compile-time" scope) to install multiple subs. Subs are +called in a "first-in-last-out"-order (FILO or "stack"-order). + +=head3 fill_protos + + fill_protos('*$$;$@') + +Given a Perl subroutine prototype, return a list of invocation +specifications. Each specification is a listref, where the first +member is the (minimum) number of arguments for this invocation +specification. The remaining arguments are a string representation of +how to pass the arguments correctly to a sub with the given prototype, +when called with the given number of arguments. + +The specifications are returned in increasing order of arguments +starting at 0 (e.g. ';$') or 1 (e.g. '$@'). Note that if the +prototype is "slurpy" (e.g. ends with a "@"), the number of arguments +for the last specification is a "minimum" number rather than an exact +number. This can be detected by the last member of the last +specification matching m/[@#]_/. + +=head3 make_core_trampoline + + make_core_trampoline('CORE::open', 'main', prototype('CORE::open')) + +Creates a trampoline for calling a core sub. Essentially, a tiny sub +that figures out how we should be calling our core sub, puts in the +arguments in the right way, and bounces our control over to it. + +If we could reliably use `goto &` on core builtins, we wouldn't need +this subroutine. + +=head3 install_subs + + install_subs('My::Module', { 'read' => sub { die("Hallo\n"), ... }}) + +Given a package name and a hashref mapping names to a subroutine +reference (or C), this subroutine will install said subroutines +on their given name in that module. If a name mapes to C, any +subroutine with that name in the target module will be removed +(possibly "unshadowing" a CORE sub of same name). + +=head1 AUTHOR + +Copyright 2013-2014, Niels Thykier Eniels@thykier.netE + +=head1 LICENSE + +This module is free software. You may distribute it under the +same terms as Perl itself. diff --git a/git/usr/share/perl5/core_perl/autodie/exception.pm b/git/usr/share/perl5/core_perl/autodie/exception.pm new file mode 100644 index 0000000000000000000000000000000000000000..46d75d81519afc8edc9829692f1a4a74760d00aa --- /dev/null +++ b/git/usr/share/perl5/core_perl/autodie/exception.pm @@ -0,0 +1,879 @@ +package autodie::exception; +use 5.008; +use strict; +use warnings; +use Carp qw(croak); + +use Scalar::Util qw(blessed); + +our $VERSION = '2.37'; # VERSION: Generated by DZP::OurPkg:Version +# ABSTRACT: Exceptions from autodying functions. + +our $DEBUG = 0; + +use overload + q{""} => "stringify", + # Overload smart-match only if we're using 5.10 or up + (( $] >= 5.010 && $] < 5.041 ) ? ('~~' => "matches") : ()), + fallback => 1, +; + +my $PACKAGE = __PACKAGE__; # Useful to have a scalar for hash keys. + +=head1 NAME + +autodie::exception - Exceptions from autodying functions. + +=head1 SYNOPSIS + + eval { + use autodie; + + open(my $fh, '<', 'some_file.txt'); + + ... + }; + + if (my $E = $@) { + say "Ooops! ",$E->caller," had problems: $@"; + } + + +=head1 DESCRIPTION + +When an L enabled function fails, it generates an +C object. This can be interrogated to +determine further information about the error that occurred. + +This document is broken into two sections; those methods that +are most useful to the end-developer, and those methods for +anyone wishing to subclass or get very familiar with +C. + +=head2 Common Methods + +These methods are intended to be used in the everyday dealing +of exceptions. + +The following assume that the error has been copied into +a separate scalar: + + if ($E = $@) { + ... + } + +This is not required, but is recommended in case any code +is called which may reset or alter C<$@>. + +=cut + +=head3 args + + my $array_ref = $E->args; + +Provides a reference to the arguments passed to the subroutine +that died. + +=cut + +sub args { return $_[0]->{$PACKAGE}{args}; } + +=head3 function + + my $sub = $E->function; + +The subroutine (including package) that threw the exception. + +=cut + +sub function { return $_[0]->{$PACKAGE}{function}; } + +=head3 file + + my $file = $E->file; + +The file in which the error occurred (eg, C or +C). + +=cut + +sub file { return $_[0]->{$PACKAGE}{file}; } + +=head3 package + + my $package = $E->package; + +The package from which the exceptional subroutine was called. + +=cut + +sub package { return $_[0]->{$PACKAGE}{package}; } + +=head3 caller + + my $caller = $E->caller; + +The subroutine that I the exceptional code. + +=cut + +sub caller { return $_[0]->{$PACKAGE}{caller}; } + +=head3 line + + my $line = $E->line; + +The line in C<< $E->file >> where the exceptional code was called. + +=cut + +sub line { return $_[0]->{$PACKAGE}{line}; } + +=head3 context + + my $context = $E->context; + +The context in which the subroutine was called by autodie; usually +the same as the context in which you called the autodying subroutine. +This can be 'list', 'scalar', or undefined (unknown). It will never +be 'void', as C always captures the return value in one way +or another. + +For some core functions that always return a scalar value regardless +of their context (eg, C), this may be 'scalar', even if you +used a list context. + +=cut + +# TODO: The comments above say this can be undefined. Is that actually +# the case? (With 'system', perhaps?) + +sub context { return $_[0]->{$PACKAGE}{context} } + +=head3 return + + my $return_value = $E->return; + +The value(s) returned by the failed subroutine. When the subroutine +was called in a list context, this will always be a reference to an +array containing the results. When the subroutine was called in +a scalar context, this will be the actual scalar returned. + +=cut + +sub return { return $_[0]->{$PACKAGE}{return} } + +=head3 errno + + my $errno = $E->errno; + +The value of C<$!> at the time when the exception occurred. + +B: This method will leave the main C class +and become part of a role in the future. You should only call +C for exceptions where C<$!> would reasonably have been +set on failure. + +=cut + +# TODO: Make errno part of a role. It doesn't make sense for +# everything. + +sub errno { return $_[0]->{$PACKAGE}{errno}; } + +=head3 eval_error + + my $old_eval_error = $E->eval_error; + +The contents of C<$@> immediately after autodie triggered an +exception. This may be useful when dealing with modules such +as L that set (but do not throw) C<$@> on error. + +=cut + +sub eval_error { return $_[0]->{$PACKAGE}{eval_error}; } + +=head3 matches + + if ( $e->matches('open') ) { ... } + + if ( 'open' ~~ $e ) { ... } + +C is used to determine whether a +given exception matches a particular role. + +An exception is considered to match a string if: + +=over 4 + +=item * + +For a string not starting with a colon, the string exactly matches the +package and subroutine that threw the exception. For example, +C. If the string does not contain a package name, +C is assumed. + +=item * + +For a string that does start with a colon, if the subroutine +throwing the exception I that behaviour. For example, the +C subroutine does C<:file>, C<:io> and C<:all>. + +See L for further information. + +On Perl 5.10 and above, using smart-match (C<~~>) with an +C object will use C underneath. This module +used to recommend using smart-match with the exception object on the left +hand side, but in future Perls that is likely to stop working. +The smart-match facility of this class should only be used with the +exception object on the right hand side. Having the exception object on +the right is both future-proof and portable to older Perls, back to 5.10. +Beware that this facility can only +be relied upon when it is certain that the exception object actually is +an C object; it is no more capable than an explicit +call to the C method. + +=back + +=cut + +{ + my (%cache); + + sub matches { + my ($this, $that) = @_; + + # TODO - Handle references + croak "UNIMPLEMENTED" if ref $that; + + my $sub = $this->function; + + if ($DEBUG) { + my $sub2 = $this->function; + warn "Smart-matching $that against $sub / $sub2\n"; + } + + # Direct subname match. + return 1 if $that eq $sub; + return 1 if $that !~ /:/ and "CORE::$that" eq $sub; + return 0 if $that !~ /^:/; + + # Cached match / check tags. + require Fatal; + + if (exists $cache{$sub}{$that}) { + return $cache{$sub}{$that}; + } + + # This rather awful looking line checks to see if our sub is in the + # list of expanded tags, caches it, and returns the result. + + return $cache{$sub}{$that} = grep { $_ eq $sub } @{ $this->_expand_tag($that) }; + } +} + +# This exists primarily so that child classes can override or +# augment it if they wish. + +sub _expand_tag { + my ($this, @args) = @_; + + return Fatal->_expand_tag(@args); +} + +=head2 Advanced methods + +The following methods, while usable from anywhere, are primarily +intended for developers wishing to subclass C, +write code that registers custom error messages, or otherwise +work closely with the C model. + +=cut + +# The table below records customer formatters. +# TODO - Should this be a package var instead? +# TODO - Should these be in a completely different file, or +# perhaps loaded on demand? Most formatters will never +# get used in most programs. + +my %formatter_of = ( + 'CORE::close' => \&_format_close, + 'CORE::open' => \&_format_open, + 'CORE::dbmopen' => \&_format_dbmopen, + 'CORE::flock' => \&_format_flock, + 'CORE::read' => \&_format_readwrite, + 'CORE::sysread' => \&_format_readwrite, + 'CORE::syswrite' => \&_format_readwrite, + 'CORE::chmod' => \&_format_chmod, + 'CORE::mkdir' => \&_format_mkdir, +); + +sub _beautify_arguments { + shift @_; + + # Walk through all our arguments, and... + # + # * Replace undef with the word 'undef' + # * Replace globs with the string '$fh' + # * Quote all other args. + foreach my $arg (@_) { + if (not defined($arg)) { $arg = 'undef' } + elsif (ref($arg) eq "GLOB") { $arg = '$fh' } + else { $arg = qq{'$arg'} } + } + + return @_; +} + +sub _trim_package_name { + # Info: The following is done since 05/2008 (which is before v1.10) + + # TODO: This is probably a good idea for CORE, is it + # a good idea for other subs? + + # Trim package name off dying sub for error messages + (my $name = $_[1]) =~ s/.*:://; + return $name; +} + +# Returns the parameter formatted as octal number +sub _octalize_number { + my $number = $_[1]; + + # Only reformat if it looks like a whole number + if ($number =~ /^\d+$/) { + $number = sprintf("%#04lo", $number); + } + + return $number; +} + +# TODO: Our tests only check LOCK_EX | LOCK_NB is properly +# formatted. Try other combinations and ensure they work +# correctly. + +sub _format_flock { + my ($this) = @_; + + require Fcntl; + + my $filehandle = $this->args->[0]; + my $raw_mode = $this->args->[1]; + + my $mode_type; + my $lock_unlock; + + if ($raw_mode & Fcntl::LOCK_EX() ) { + $lock_unlock = "lock"; + $mode_type = "for exclusive access"; + } + elsif ($raw_mode & Fcntl::LOCK_SH() ) { + $lock_unlock = "lock"; + $mode_type = "for shared access"; + } + elsif ($raw_mode & Fcntl::LOCK_UN() ) { + $lock_unlock = "unlock"; + $mode_type = ""; + } + else { + # I've got no idea what they're trying to do. + $lock_unlock = "lock"; + $mode_type = "with mode $raw_mode"; + } + + my $cooked_filehandle; + + if ($filehandle and not ref $filehandle) { + + # A package filehandle with a name! + + $cooked_filehandle = " $filehandle"; + } + else { + # Otherwise we have a scalar filehandle. + + $cooked_filehandle = ''; + + } + + local $! = $this->errno; + + return "Can't $lock_unlock filehandle$cooked_filehandle $mode_type: $!"; + +} + +# Default formatter for CORE::chmod +sub _format_chmod { + my ($this) = @_; + my @args = @{$this->args}; + + my $mode = shift @args; + local $! = $this->errno; + + $mode = $this->_octalize_number($mode); + + @args = $this->_beautify_arguments(@args); + + return "Can't chmod($mode, ". join(q{, }, @args) ."): $!"; +} + +# Default formatter for CORE::mkdir +sub _format_mkdir { + my ($this) = @_; + my @args = @{$this->args}; + + # If no mask is specified use default formatter + if (@args < 2) { + return $this->format_default; + } + + my $file = $args[0]; + my $mask = $args[1]; + local $! = $this->errno; + + $mask = $this->_octalize_number($mask); + + return "Can't mkdir('$file', $mask): '$!'"; +} + +# Default formatter for CORE::dbmopen +sub _format_dbmopen { + my ($this) = @_; + my @args = @{$this->args}; + + # TODO: Presently, $args flattens out the (usually empty) hash + # which is passed as the first argument to dbmopen. This is + # a bug in our args handling code (taking a reference to it would + # be better), but for the moment we'll just examine the end of + # our arguments list for message formatting. + + my $mode = $args[-1]; + my $file = $args[-2]; + + $mode = $this->_octalize_number($mode); + + local $! = $this->errno; + + return "Can't dbmopen(%hash, '$file', $mode): '$!'"; +} + +# Default formatter for CORE::close + +sub _format_close { + my ($this) = @_; + my $close_arg = $this->args->[0]; + + local $! = $this->errno; + + # If we've got an old-style filehandle, mention it. + if ($close_arg and not ref $close_arg) { + return "Can't close filehandle '$close_arg': '$!'"; + } + + # TODO - This will probably produce an ugly error. Test and fix. + return "Can't close($close_arg) filehandle: '$!'"; + +} + +# Default formatter for CORE::read, CORE::sysread and CORE::syswrite +# +# Similar to default formatter with the buffer filtered out as it +# may contain binary data. +sub _format_readwrite { + my ($this) = @_; + my $call = $this->_trim_package_name($this->function); + local $! = $this->errno; + + # These subs receive the following arguments (in order): + # + # * FILEHANDLE + # * SCALAR (buffer, we do not want to write this) + # * LENGTH (optional for syswrite) + # * OFFSET (optional for all) + my (@args) = @{$this->args}; + my $arg_name = $args[1]; + if (defined($arg_name)) { + if (ref($arg_name)) { + my $name = blessed($arg_name) || ref($arg_name); + $arg_name = "<${name}>"; + } else { + $arg_name = ''; + } + } else { + $arg_name = ''; + } + $args[1] = $arg_name; + + return "Can't $call(" . join(q{, }, @args) . "): $!"; +} + +# Default formatter for CORE::open + +use constant _FORMAT_OPEN => "Can't open '%s' for %s: '%s'"; + +sub _format_open_with_mode { + my ($this, $mode, $file, $error) = @_; + + my $wordy_mode; + + if ($mode eq '<') { $wordy_mode = 'reading'; } + elsif ($mode eq '>') { $wordy_mode = 'writing'; } + elsif ($mode eq '>>') { $wordy_mode = 'appending'; } + + $file = '' if not defined $file; + + return sprintf _FORMAT_OPEN, $file, $wordy_mode, $error if $wordy_mode; + + Carp::confess("Internal autodie::exception error: Don't know how to format mode '$mode'."); + +} + +sub _format_open { + my ($this) = @_; + + my @open_args = @{$this->args}; + + # Use the default formatter for single-arg and many-arg open + if (@open_args <= 1 or @open_args >= 4) { + return $this->format_default; + } + + # For two arg open, we have to extract the mode + if (@open_args == 2) { + my ($fh, $file) = @open_args; + + if (ref($fh) eq "GLOB") { + $fh = '$fh'; + } + + my ($mode) = $file =~ m{ + ^\s* # Spaces before mode + ( + (?> # Non-backtracking subexp. + < # Reading + |>>? # Writing/appending + ) + ) + [^&] # Not an ampersand (which means a dup) + }x; + + if (not $mode) { + # Maybe it's a 2-arg open without any mode at all? + # Detect the most simple case for this, where our + # file consists only of word characters. + + if ( $file =~ m{^\s*\w+\s*$} ) { + $mode = '<' + } + else { + # Otherwise, we've got no idea what's going on. + # Use the default. + return $this->format_default; + } + } + + # Localising $! means perl makes it a pretty error for us. + local $! = $this->errno; + + return $this->_format_open_with_mode($mode, $file, $!); + } + + # Here we must be using three arg open. + + my $file = $open_args[2]; + + local $! = $this->errno; + + my $mode = $open_args[1]; + + local $@; + + my $msg = eval { $this->_format_open_with_mode($mode, $file, $!); }; + + return $msg if $msg; + + # Default message (for pipes and odd things) + + return "Can't open '$file' with mode '$open_args[1]': '$!'"; +} + +=head3 register + + autodie::exception->register( 'CORE::open' => \&mysub ); + +The C method allows for the registration of a message +handler for a given subroutine. The full subroutine name including +the package should be used. + +Registered message handlers will receive the C +object as the first parameter. + +=cut + +sub register { + my ($class, $symbol, $handler) = @_; + + croak "Incorrect call to autodie::register" if @_ != 3; + + $formatter_of{$symbol} = $handler; + +} + +=head3 add_file_and_line + + say "Problem occurred",$@->add_file_and_line; + +Returns the string C< at %s line %d>, where C<%s> is replaced with +the filename, and C<%d> is replaced with the line number. + +Primarily intended for use by format handlers. + +=cut + +# Simply produces the file and line number; intended to be added +# to the end of error messages. + +sub add_file_and_line { + my ($this) = @_; + + return sprintf(" at %s line %d\n", $this->file, $this->line); +} + +=head3 stringify + + say "The error was: ",$@->stringify; + +Formats the error as a human readable string. Usually there's no +reason to call this directly, as it is used automatically if an +C object is ever used as a string. + +Child classes can override this method to change how they're +stringified. + +=cut + +sub stringify { + my ($this) = @_; + + my $call = $this->function; + my $msg; + + if ($DEBUG) { + my $dying_pkg = $this->package; + my $sub = $this->function; + my $caller = $this->caller; + warn "Stringifing exception for $dying_pkg :: $sub / $caller / $call\n"; + } + + # TODO - This isn't using inheritance. Should it? + if ( my $sub = $formatter_of{$call} ) { + $msg = $sub->($this) . $this->add_file_and_line; + } else { + $msg = $this->format_default . $this->add_file_and_line; + } + $msg .= $this->{$PACKAGE}{_stack_trace} + if $Carp::Verbose; + + return $msg; +} + +=head3 format_default + + my $error_string = $E->format_default; + +This produces the default error string for the given exception, +I. It is primarily +intended to be called from a message handler when they have +been passed an exception they don't want to format. + +Child classes can override this method to change how default +messages are formatted. + +=cut + +# TODO: This produces ugly errors. Is there any way we can +# dig around to find the actual variable names? I know perl 5.10 +# does some dark and terrible magicks to find them for undef warnings. + +sub format_default { + my ($this) = @_; + + my $call = $this->_trim_package_name($this->function); + + local $! = $this->errno; + + my @args = @{ $this->args() }; + @args = $this->_beautify_arguments(@args); + + # Format our beautiful error. + + return "Can't $call(". join(q{, }, @args) . "): $!" ; + + # TODO - Handle user-defined errors from hash. + + # TODO - Handle default error messages. + +} + +=head3 new + + my $error = autodie::exception->new( + args => \@_, + function => "CORE::open", + errno => $!, + context => 'scalar', + return => undef, + ); + + +Creates a new C object. Normally called +directly from an autodying function. The C argument +is required, its the function we were trying to call that +generated the exception. The C parameter is optional. + +The C value is optional. In versions of C +1.99 and earlier the code would try to automatically use the +current value of C<$!>, but this was unreliable and is no longer +supported. + +Atrributes such as package, file, and caller are determined +automatically, and cannot be specified. + +=cut + +sub new { + my ($class, @args) = @_; + + my $this = {}; + + bless($this,$class); + + # I'd love to use EVERY here, but it causes our code to die + # because it wants to stringify our objects before they're + # initialised, causing everything to explode. + + $this->_init(@args); + + return $this; +} + +sub _init { + + my ($this, %args) = @_; + + # Capturing errno here is not necessarily reliable. + my $original_errno = $!; + + our $init_called = 1; + + my $class = ref $this; + + # We're going to walk up our call stack, looking for the + # first thing that doesn't look like our exception + # code, autodie/Fatal, or some whacky eval. + + my ($package, $file, $line, $sub); + + my $depth = 0; + + while (1) { + $depth++; + + ($package, $file, $line, $sub) = CORE::caller($depth); + + # Skip up the call stack until we find something outside + # of the Fatal/autodie/eval space. + + next if $package->isa('Fatal'); + next if $package->isa($class); + next if $package->isa(__PACKAGE__); + + # Anything with the 'autodie::skip' role wants us to skip it. + # https://github.com/pjf/autodie/issues/15 + + next if ($package->can('DOES') and $package->DOES('autodie::skip')); + + next if $file =~ /^\(eval\s\d+\)$/; + + last; + + } + + # We now have everything correct, *except* for our subroutine + # name. If it's __ANON__ or (eval), then we need to keep on + # digging deeper into our stack to find the real name. However we + # don't update our other information, since that will be correct + # for our current exception. + + my $first_guess_subroutine = $sub; + + while (defined $sub and $sub =~ /^\(eval\)$|::__ANON__$/) { + $depth++; + + $sub = (CORE::caller($depth))[3]; + } + + # If we end up falling out the bottom of our stack, then our + # __ANON__ guess is the best we can get. This includes situations + # where we were called from the top level of a program. + + if (not defined $sub) { + $sub = $first_guess_subroutine; + } + + $this->{$PACKAGE}{package} = $package; + $this->{$PACKAGE}{file} = $file; + $this->{$PACKAGE}{line} = $line; + $this->{$PACKAGE}{caller} = $sub; + + # Tranks to %Carp::CarpInternal all Fatal, autodie and + # autodie::exception stack frames are filtered already, but our + # nameless wrapper is still present, so strip that. + + my $trace = Carp::longmess(); + $trace =~ s/^\s*at \(eval[^\n]+\n//; + + # And if we see an __ANON__, then we'll replace that with the actual + # name of our autodying function. + + my $short_func = $args{function}; + $short_func =~ s/^CORE:://; + $trace =~ s/(\s*[\w:]+)__ANON__/$1$short_func/; + + # And now we just fill in all our attributes. + + $this->{$PACKAGE}{_stack_trace} = $trace; + + $this->{$PACKAGE}{errno} = $args{errno} || 0; + + $this->{$PACKAGE}{context} = $args{context}; + $this->{$PACKAGE}{return} = $args{return}; + $this->{$PACKAGE}{eval_error} = $args{eval_error}; + + $this->{$PACKAGE}{args} = $args{args} || []; + $this->{$PACKAGE}{function}= $args{function} or + croak("$class->new() called without function arg"); + + return $this; + +} + +1; + +__END__ + +=head1 SEE ALSO + +L, L + +=head1 LICENSE + +Copyright (C)2008 Paul Fenwick + +This is free software. You may modify and/or redistribute this +code under the same terms as Perl 5.10 itself, or, at your option, +any later version of Perl 5. + +=head1 AUTHOR + +Paul Fenwick Epjf@perltraining.com.auE diff --git a/git/usr/share/perl5/core_perl/autodie/hints.pm b/git/usr/share/perl5/core_perl/autodie/hints.pm new file mode 100644 index 0000000000000000000000000000000000000000..8ac1f07c75ca937fbce378d74e3b2a1e5caa05d7 --- /dev/null +++ b/git/usr/share/perl5/core_perl/autodie/hints.pm @@ -0,0 +1,602 @@ +package autodie::hints; + +use strict; +use warnings; + +use constant PERL58 => ( $] < 5.009 ); + +our $VERSION = '2.37'; # VERSION: Generated by DZP::OurPkg:Version + +# ABSTRACT: Provide hints about user subroutines to autodie + +=head1 NAME + +autodie::hints - Provide hints about user subroutines to autodie + +=head1 SYNOPSIS + + package Your::Module; + + our %DOES = ( 'autodie::hints::provider' => 1 ); + + sub AUTODIE_HINTS { + return { + foo => { scalar => HINTS, list => SOME_HINTS }, + bar => { scalar => HINTS, list => MORE_HINTS }, + } + } + + # Later, in your main program... + + use Your::Module qw(foo bar); + use autodie qw(:default foo bar); + + foo(); # succeeds or dies based on scalar hints + + # Alternatively, hints can be set on subroutines we've + # imported. + + use autodie::hints; + use Some::Module qw(think_positive); + + BEGIN { + autodie::hints->set_hints_for( + \&think_positive, + { + fail => sub { $_[0] <= 0 } + } + ) + } + use autodie qw(think_positive); + + think_positive(...); # Returns positive or dies. + + +=head1 DESCRIPTION + +=head2 Introduction + +The L pragma is very smart when it comes to working with +Perl's built-in functions. The behaviour for these functions are +fixed, and C knows exactly how they try to signal failure. + +But what about user-defined subroutines from modules? If you use +C on a user-defined subroutine then it assumes the following +behaviour to demonstrate failure: + +=over + +=item * + +A false value, in scalar context + +=item * + +An empty list, in list context + +=item * + +A list containing a single undef, in list context + +=back + +All other return values (including the list of the single zero, and the +list containing a single empty string) are considered successful. However, +real-world code isn't always that easy. Perhaps the code you're working +with returns a string containing the word "FAIL" upon failure, or a +two element list containing C<(undef, "human error message")>. To make +autodie work with these sorts of subroutines, we have +the I. + +The hinting interface allows I to be provided to C +on how it should detect failure from user-defined subroutines. While +these I be provided by the end-user of C, they are ideally +written into the module itself, or into a helper module or sub-class +of C itself. + +=head2 What are hints? + +A I is a subroutine or value that is checked against the +return value of an autodying subroutine. If the match returns true, +C considers the subroutine to have failed. + +If the hint provided is a subroutine, then C will pass +the complete return value to that subroutine. If the hint is a regexp object, +then C will match it against the return value. If the hint is undef, +the return value must be undef. On Perl versions 5.10 and newer, any other +value can be provided and it will be smart matched against the value provided. +However, smart matched values like this are deprecated. + +Hints can be provided for both scalar and list contexts. Note +that an autodying subroutine will never see a void context, as +C always needs to capture the return value for examination. +Autodying subroutines called in void context act as if they're called +in a scalar context, but their return value is discarded after it +has been checked. + +=head2 Example hints + +Hints may consist of subroutine references, objects overloading +smart-match, regular expressions, and depending on Perl version possibly +other things. You can specify different hints for how +failure should be identified in scalar and list contexts. + +These examples apply for use in the C subroutine and when +calling C<< autodie::hints->set_hints_for() >>. + +The most common context-specific hints are: + + # Scalar failures always return undef: + { scalar => sub { !defined($_[0]) } } + + # Scalar failures return any false value [default expectation]: + { scalar => sub { ! $_[0] } } + + # Scalar failures always return zero explicitly: + { scalar => sub { defined($_[0]) && $_[0] eq '0' } } + + # List failures always return an empty list: + { list => sub { !@_ } } + + # List failures return () or (undef) [default expectation]: + { list => sub { ! @_ || @_ == 1 && !defined $_[0] } } + + # List failures return () or a single false value: + { list => sub { ! @_ || @_ == 1 && !$_[0] } } + + # List failures return (undef, "some string") + { list => sub { @_ == 2 && !defined $_[0] } } + + # Unsuccessful foo() returns 'FAIL' or '_FAIL' in scalar context, + # returns (-1) in list context... + autodie::hints->set_hints_for( + \&foo, + { + scalar => qr/^ _? FAIL $/xms, + list => sub { @_ == 1 && $_[0] eq -1 }, + } + ); + + # Unsuccessful foo() returns 0 in all contexts... + autodie::hints->set_hints_for( + \&foo, + { + scalar => sub { defined($_[0]) && $_[0] == 0 }, + list => sub { @_ == 1 && defined($_[0]) && $_[0] == 0 }, + } + ); + +This "in all contexts" construction is very common, and can be +abbreviated, using the 'fail' key. This sets both the C +and C hints to the same value: + + # Unsuccessful foo() returns 0 in all contexts... + autodie::hints->set_hints_for( + \&foo, + { + fail => sub { @_ == 1 and defined $_[0] and $_[0] == 0 } + } + ); + + # Unsuccessful think_positive() returns negative number on failure... + autodie::hints->set_hints_for( + \&think_positive, + { + fail => sub { $_[0] < 0 } + } + ); + + # Unsuccessful my_system() returns non-zero on failure... + autodie::hints->set_hints_for( + \&my_system, + { + fail => sub { $_[0] != 0 } + } + ); + +=head1 Manually setting hints from within your program + +If you are using a module which returns something special on failure, then +you can manually create hints for each of the desired subroutines. Once +the hints are specified, they are available for all files and modules loaded +thereafter, thus you can move this work into a module and it will still +work. + + use Some::Module qw(foo bar); + use autodie::hints; + + autodie::hints->set_hints_for( + \&foo, + { + scalar => SCALAR_HINT, + list => LIST_HINT, + } + ); + autodie::hints->set_hints_for( + \&bar, + { fail => SOME_HINT, } + ); + +It is possible to pass either a subroutine reference (recommended) or a fully +qualified subroutine name as the first argument. This means you can set hints +on modules that I get loaded: + + use autodie::hints; + autodie::hints->set_hints_for( + 'Some::Module:bar', { fail => SCALAR_HINT, } + ); + +This technique is most useful when you have a project that uses a +lot of third-party modules. You can define all your possible hints +in one-place. This can even be in a sub-class of autodie. For +example: + + package my::autodie; + + use parent qw(autodie); + use autodie::hints; + + autodie::hints->set_hints_for(...); + + 1; + +You can now C, which will work just like the standard +C, but is now aware of any hints that you've set. + +=head1 Adding hints to your module + +C provides a passive interface to allow you to declare hints for +your module. These hints will be found and used by C if it +is loaded, but otherwise have no effect (or dependencies) without autodie. +To set these, your module needs to declare that it I the +C role. This can be done by writing your +own C method, using a system such as C to handle +the heavy-lifting for you, or declaring a C<%DOES> package variable +with a C key and a corresponding true value. + +Note that checking for a C<%DOES> hash is an C-only +short-cut. Other modules do not use this mechanism for checking +roles, although you can use the C module from the +CPAN to allow it. + +In addition, you must define a C subroutine that returns +a hash-reference containing the hints for your subroutines: + + package Your::Module; + + # We can use the Class::DOES from the CPAN to declare adherence + # to a role. + + use Class::DOES 'autodie::hints::provider' => 1; + + # Alternatively, we can declare the role in %DOES. Note that + # this is an autodie specific optimisation, although Class::DOES + # can be used to promote this to a true role declaration. + + our %DOES = ( 'autodie::hints::provider' => 1 ); + + # Finally, we must define the hints themselves. + + sub AUTODIE_HINTS { + return { + foo => { scalar => HINTS, list => SOME_HINTS }, + bar => { scalar => HINTS, list => MORE_HINTS }, + baz => { fail => HINTS }, + } + } + +This allows your code to set hints without relying on C and +C being loaded, or even installed. In this way your +code can do the right thing when C is installed, but does not +need to depend upon it to function. + +=head1 Insisting on hints + +When a user-defined subroutine is wrapped by C, it will +use hints if they are available, and otherwise reverts to the +I described in the introduction of this document. +This can be problematic if we expect a hint to exist, but (for +whatever reason) it has not been loaded. + +We can ask autodie to I that a hint be used by prefixing +an exclamation mark to the start of the subroutine name. A lone +exclamation mark indicates that I subroutines after it must +have hints declared. + + # foo() and bar() must have their hints defined + use autodie qw( !foo !bar baz ); + + # Everything must have hints (recommended). + use autodie qw( ! foo bar baz ); + + # bar() and baz() must have their hints defined + use autodie qw( foo ! bar baz ); + + # Enable autodie for all of Perl's supported built-ins, + # as well as for foo(), bar() and baz(). Everything must + # have hints. + use autodie qw( ! :all foo bar baz ); + +If hints are not available for the specified subroutines, this will cause a +compile-time error. Insisting on hints for Perl's built-in functions +(eg, C and C) is always successful. + +Insisting on hints is I recommended. + +=cut + +# TODO: implement regular expression hints + +use constant UNDEF_ONLY => sub { not defined $_[0] }; +use constant EMPTY_OR_UNDEF => sub { + ! @_ or + @_==1 && !defined $_[0] +}; + +use constant EMPTY_ONLY => sub { @_ == 0 }; +use constant EMPTY_OR_FALSE => sub { + ! @_ or + @_==1 && !$_[0] +}; + +use constant SINGLE_TRUE => sub { @_ == 1 and not $_[0] }; + +use constant DEFAULT_HINTS => { + scalar => UNDEF_ONLY, + list => EMPTY_OR_UNDEF, +}; + + +use constant HINTS_PROVIDER => 'autodie::hints::provider'; + +our $DEBUG = 0; + +# Only ( undef ) is a strange but possible situation for very +# badly written code. It's not supported yet. + +my %Hints = ( + 'File::Copy::copy' => { scalar => SINGLE_TRUE, list => SINGLE_TRUE }, + 'File::Copy::move' => { scalar => SINGLE_TRUE, list => SINGLE_TRUE }, + 'File::Copy::cp' => { scalar => SINGLE_TRUE, list => SINGLE_TRUE }, + 'File::Copy::mv' => { scalar => SINGLE_TRUE, list => SINGLE_TRUE }, +); + +# Start by using Sub::Identify if it exists on this system. + +eval { require Sub::Identify; Sub::Identify->import('get_code_info'); }; + +# If it doesn't exist, we'll define our own. This code is directly +# taken from Rafael Garcia's Sub::Identify 0.04, used under the same +# license as Perl itself. + +if ($@) { + require B; + + no warnings 'once'; + + *get_code_info = sub ($) { + + my ($coderef) = @_; + ref $coderef or return; + my $cv = B::svref_2object($coderef); + $cv->isa('B::CV') or return; + # bail out if GV is undefined + $cv->GV->isa('B::SPECIAL') and return; + + return ($cv->GV->STASH->NAME, $cv->GV->NAME); + }; + +} + +sub sub_fullname { + return join( '::', get_code_info( $_[1] ) ); +} + +my %Hints_loaded = (); + +sub load_hints { + my ($class, $sub) = @_; + + my ($package) = ( $sub =~ /(.*)::/ ); + + if (not defined $package) { + require Carp; + Carp::croak( + "Internal error in autodie::hints::load_hints - no package found. + "); + } + + # Do nothing if we've already tried to load hints for + # this package. + return if $Hints_loaded{$package}++; + + my $hints_available = 0; + + { + no strict 'refs'; ## no critic + + if ($package->can('DOES') and $package->DOES(HINTS_PROVIDER) ) { + $hints_available = 1; + } + elsif ( PERL58 and $package->isa(HINTS_PROVIDER) ) { + $hints_available = 1; + } + elsif ( ${"${package}::DOES"}{HINTS_PROVIDER.""} ) { + $hints_available = 1; + } + } + + return if not $hints_available; + + my %package_hints = %{ $package->AUTODIE_HINTS }; + + foreach my $sub (keys %package_hints) { + + my $hint = $package_hints{$sub}; + + # Ensure we have a package name. + $sub = "${package}::$sub" if $sub !~ /::/; + + # TODO - Currently we don't check for conflicts, should we? + $Hints{$sub} = $hint; + + $class->normalise_hints(\%Hints, $sub); + } + + return; + +} + +sub normalise_hints { + my ($class, $hints, $sub) = @_; + + if ( exists $hints->{$sub}->{fail} ) { + + if ( exists $hints->{$sub}->{scalar} or + exists $hints->{$sub}->{list} + ) { + # TODO: Turn into a proper diagnostic. + require Carp; + local $Carp::CarpLevel = 1; + Carp::croak("fail hints cannot be provided with either scalar or list hints for $sub"); + } + + # Set our scalar and list hints. + + $hints->{$sub}->{scalar} = + $hints->{$sub}->{list} = delete $hints->{$sub}->{fail}; + + return; + + } + + # Check to make sure all our hints exist. + + foreach my $hint (qw(scalar list)) { + if ( not exists $hints->{$sub}->{$hint} ) { + # TODO: Turn into a proper diagnostic. + require Carp; + local $Carp::CarpLevel = 1; + Carp::croak("$hint hint missing for $sub"); + } + } + + return; +} + +sub get_hints_for { + my ($class, $sub) = @_; + + my $subname = $class->sub_fullname( $sub ); + + # If we have hints loaded for a sub, then return them. + + if ( exists $Hints{ $subname } ) { + return $Hints{ $subname }; + } + + # If not, we try to load them... + + $class->load_hints( $subname ); + + # ...and try again! + + if ( exists $Hints{ $subname } ) { + return $Hints{ $subname }; + } + + # It's the caller's responsibility to use defaults if desired. + # This allows on autodie to insist on hints if needed. + + return; + +} + +sub set_hints_for { + my ($class, $sub, $hints) = @_; + + if (ref $sub) { + $sub = $class->sub_fullname( $sub ); + + require Carp; + + $sub or Carp::croak("Attempts to set_hints_for unidentifiable subroutine"); + } + + if ($DEBUG) { + warn "autodie::hints: Setting $sub to hints: $hints\n"; + } + + $Hints{ $sub } = $hints; + + $class->normalise_hints(\%Hints, $sub); + + return; +} + +1; + +__END__ + + +=head1 Diagnostics + +=over 4 + +=item Attempts to set_hints_for unidentifiable subroutine + +You've called C<< autodie::hints->set_hints_for() >> using a subroutine +reference, but that reference could not be resolved back to a +subroutine name. It may be an anonymous subroutine (which can't +be made autodying), or may lack a name for other reasons. + +If you receive this error with a subroutine that has a real name, +then you may have found a bug in autodie. See L +for how to report this. + +=item fail hints cannot be provided with either scalar or list hints for %s + +When defining hints, you can either supply both C and +C keywords, I you can provide a single C keyword. +You can't mix and match them. + +=item %s hint missing for %s + +You've provided either a C hint without supplying +a C hint, or vice-versa. You I supply both C +and C hints, I a single C hint. + +=back + +=head1 ACKNOWLEDGEMENTS + +=over + +=item * + +Dr Damian Conway for suggesting the hinting interface and providing the +example usage. + +=item * + +Jacinta Richardson for translating much of my ideas into this +documentation. + +=back + +=head1 AUTHOR + +Copyright 2009, Paul Fenwick Epjf@perltraining.com.auE + +=head1 LICENSE + +This module is free software. You may distribute it under the +same terms as Perl itself. + +=head1 SEE ALSO + +L, L + +=for Pod::Coverage get_hints_for load_hints normalise_hints sub_fullname get_code_info + +=cut diff --git a/git/usr/share/perl5/core_perl/autodie/skip.pm b/git/usr/share/perl5/core_perl/autodie/skip.pm new file mode 100644 index 0000000000000000000000000000000000000000..aff4e6d8844f259c193a138e2ac884f9ef3d6831 --- /dev/null +++ b/git/usr/share/perl5/core_perl/autodie/skip.pm @@ -0,0 +1,56 @@ +package autodie::skip; +use strict; +use warnings; + +our $VERSION = '2.37'; # VERSION + +# This package exists purely so people can inherit from it, +# which isn't at all how roles are supposed to work, but it's +# how people will use them anyway. + +if ($] < 5.010) { + # Older Perls don't have a native ->DOES. Let's provide a cheap + # imitation here. + + *DOES = sub { return shift->isa(@_); }; +} + +1; + +__END__ + +=head1 NAME + +autodie::skip - Skip a package when throwing autodie exceptions + +=head1 SYNPOSIS + + use parent qw(autodie::skip); + +=head1 DESCRIPTION + +This dummy class exists to signal that the class inheriting it should +be skipped when reporting exceptions from autodie. This is useful +for utility classes like L that wish to report the location +of where they were called on failure. + +If your class has a better way of doing roles, then you should not +load this class and instead simply say that your class I +C instead. + +=head1 AUTHOR + +Copyright 2013, Paul Fenwick + +=head1 LICENSE + +This module is free software. You may distribute it under the same +terms as Perl itself. + +=head1 SEE ALSO + +L, L + +=for Pod::Coverage DOES + +=cut diff --git a/git/usr/share/perl5/core_perl/encoding/warnings.pm b/git/usr/share/perl5/core_perl/encoding/warnings.pm new file mode 100644 index 0000000000000000000000000000000000000000..e09836d845e762e15f649108d90485712a044a22 --- /dev/null +++ b/git/usr/share/perl5/core_perl/encoding/warnings.pm @@ -0,0 +1,263 @@ +package encoding::warnings; +$encoding::warnings::VERSION = '0.14'; + +use strict; +use 5.007; + +=head1 NAME + +encoding::warnings - Warn on implicit encoding conversions + +=head1 VERSION + +This document describes version 0.13 of encoding::warnings, released +June 20, 2016. + +=head1 NOTICE + +As of Perl 5.26.0, this module has no effect. The internal Perl feature +that was used to implement this module has been removed. In recent years, +much work has been done on the Perl core to eliminate discrepancies in the +treatment of upgraded versus downgraded strings. In addition, the +L pragma, which caused many of the problems, is no longer +supported. Thus, the warnings this module produced are no longer +necessary. + +Hence, if you load this module on Perl 5.26.0, you will get one warning +that the module is no longer supported; and the module will do nothing +thereafter. + +=head1 SYNOPSIS + + use encoding::warnings; # or 'FATAL' to raise fatal exceptions + + utf8::encode($a = chr(20000)); # a byte-string (raw bytes) + $b = chr(20000); # a unicode-string (wide characters) + + # "Bytes implicitly upgraded into wide characters as iso-8859-1" + $c = $a . $b; + +=head1 DESCRIPTION + +=head2 Overview of the problem + +By default, there is a fundamental asymmetry in Perl's unicode model: +implicit upgrading from byte-strings to unicode-strings assumes that +they were encoded in I, but unicode-strings are +downgraded with UTF-8 encoding. This happens because the first 256 +codepoints in Unicode happens to agree with Latin-1. + +However, this silent upgrading can easily cause problems, if you happen +to mix unicode strings with non-Latin1 data -- i.e. byte-strings encoded +in UTF-8 or other encodings. The error will not manifest until the +combined string is written to output, at which time it would be impossible +to see where did the silent upgrading occur. + +=head2 Detecting the problem + +This module simplifies the process of diagnosing such problems. Just put +this line on top of your main program: + + use encoding::warnings; + +Afterwards, implicit upgrading of high-bit bytes will raise a warning. +Ex.: C. + +However, strings composed purely of ASCII code points (C<0x00>..C<0x7F>) +will I trigger this warning. + +You can also make the warnings fatal by importing this module as: + + use encoding::warnings 'FATAL'; + +=head2 Solving the problem + +Most of the time, this warning occurs when a byte-string is concatenated +with a unicode-string. There are a number of ways to solve it: + +=over 4 + +=item * Upgrade both sides to unicode-strings + +If your program does not need compatibility for Perl 5.6 and earlier, +the recommended approach is to apply appropriate IO disciplines, so all +data in your program become unicode-strings. See L, L and +L for how. + +=item * Downgrade both sides to byte-strings + +The other way works too, especially if you are sure that all your data +are under the same encoding, or if compatibility with older versions +of Perl is desired. + +You may downgrade strings with C and C. +See L and L for details. + +=item * Specify the encoding for implicit byte-string upgrading + +If you are confident that all byte-strings will be in a specific +encoding like UTF-8, I need not support older versions of Perl, +use the C pragma: + + use encoding 'utf8'; + +Similarly, this will silence warnings from this module, and preserve the +default behaviour: + + use encoding 'iso-8859-1'; + +However, note that C actually had three distinct effects: + +=over 4 + +=item * PerlIO layers for B and B + +This is similar to what L pragma does. + +=item * Literal conversions + +This turns I literal string in your program into unicode-strings +(equivalent to a C), by decoding them using the specified +encoding. + +=item * Implicit upgrading for byte-strings + +This will silence warnings from this module, as shown above. + +=back + +Because literal conversions also work on empty strings, it may surprise +some people: + + use encoding 'big5'; + + my $byte_string = pack("C*", 0xA4, 0x40); + print length $a; # 2 here. + $a .= ""; # concatenating with a unicode string... + print length $a; # 1 here! + +In other words, do not C unless you are certain that the +program will not deal with any raw, 8-bit binary data at all. + +However, the C 1> flavor of C will I +affect implicit upgrading for byte-strings, and is thus incapable of +silencing warnings from this module. See L for more details. + +=back + +=head1 CAVEATS + +For Perl 5.9.4 or later, this module's effect is lexical. + +For Perl versions prior to 5.9.4, this module affects the whole script, +instead of inside its lexical block. + +=cut + +# Constants. +sub ASCII () { 0 } +sub LATIN1 () { 1 } +sub FATAL () { 2 } + +sub import { + if ($] >= 5.025003) { + require Carp; + Carp::cluck( + "encoding::warnings is not supported on Perl 5.26.0 and later" + ); + return; + } + + # Install a ${^ENCODING} handler if no other one are already in place. + my $class = shift; + my $fatal = shift || ''; + + local $@; + return if ${^ENCODING} and ref(${^ENCODING}) ne $class; + return unless eval { require Encode; 1 }; + + my $ascii = Encode::find_encoding('us-ascii') or return; + my $latin1 = Encode::find_encoding('iso-8859-1') or return; + + # Have to undef explicitly here + undef ${^ENCODING}; + + # Install a warning handler for decode() + my $decoder = bless( + [ + $ascii, + $latin1, + (($fatal eq 'FATAL') ? 'Carp::croak' : 'Carp::carp'), + ], $class, + ); + + no warnings 'deprecated'; + ${^ENCODING} = $decoder; + use warnings 'deprecated'; + $^H{$class} = 1; +} + +sub unimport { + my $class = shift; + $^H{$class} = undef; + undef ${^ENCODING}; +} + +# Don't worry about source code literals. +sub cat_decode { + my $self = shift; + return $self->[LATIN1]->cat_decode(@_); +} + +# Warn if the data is not purely US-ASCII. +sub decode { + my $self = shift; + + DO_WARN: { + if ($] >= 5.009004) { + my $hints = (caller(0))[10]; + $hints->{ref($self)} or last DO_WARN; + } + + local $@; + my $rv = eval { $self->[ASCII]->decode($_[0], Encode::FB_CROAK()) }; + return $rv unless $@; + + require Carp; + no strict 'refs'; + $self->[FATAL]->( + "Bytes implicitly upgraded into wide characters as iso-8859-1" + ); + + } + + return $self->[LATIN1]->decode(@_); +} + +sub name { 'iso-8859-1' } + +1; + +__END__ + +=head1 SEE ALSO + +L, L + +L, L, L, L + +=head1 AUTHORS + +Audrey Tang + +=head1 COPYRIGHT + +Copyright 2004, 2005, 2006, 2007 by Audrey Tang Ecpan@audreyt.orgE. + +This program is free software; you can redistribute it and/or modify it +under the same terms as Perl itself. + +See L + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Authen/SASL/CRAM_MD5.pm b/git/usr/share/perl5/vendor_perl/Authen/SASL/CRAM_MD5.pm new file mode 100644 index 0000000000000000000000000000000000000000..efe2f11cb490d4645029707dbb37d7d95206fd2a --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Authen/SASL/CRAM_MD5.pm @@ -0,0 +1,21 @@ +# Copyright (c) 2002 Graham Barr . All rights reserved. +# This program is free software; you can redistribute it and/or +# modify it under the same terms as Perl itself. + +package Authen::SASL::CRAM_MD5 2.2000; + +use strict; +use warnings; + +warnings::warnif( + 'deprecated', + 'The CRAM-MD5 SASL mechanism is effectively deprecated by RFC8314 and should no longer be used' + ); + +sub new { + shift; + Authen::SASL->new(@_, mechanism => 'CRAM-MD5'); +} + +1; + diff --git a/git/usr/share/perl5/vendor_perl/Authen/SASL/EXTERNAL.pm b/git/usr/share/perl5/vendor_perl/Authen/SASL/EXTERNAL.pm new file mode 100644 index 0000000000000000000000000000000000000000..4b32fa5d7ef1228974256813726445aeccb62eb5 --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Authen/SASL/EXTERNAL.pm @@ -0,0 +1,17 @@ +# Copyright (c) 2002 Graham Barr . All rights reserved. +# This program is free software; you can redistribute it and/or +# modify it under the same terms as Perl itself. + +package Authen::SASL::EXTERNAL 2.2000; + +use strict; +use warnings; + + +sub new { + shift; + Authen::SASL->new(@_, mechanism => 'EXTERNAL'); +} + +1; + diff --git a/git/usr/share/perl5/vendor_perl/Authen/SASL/Perl.pm b/git/usr/share/perl5/vendor_perl/Authen/SASL/Perl.pm new file mode 100644 index 0000000000000000000000000000000000000000..54571bd2c4aa277f61d21e1aff453962f0b7746c --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Authen/SASL/Perl.pm @@ -0,0 +1,347 @@ +# Copyright (c) 2002 Graham Barr . All rights reserved. +# This program is free software; you can redistribute it and/or +# modify it under the same terms as Perl itself. + +package Authen::SASL::Perl 2.2000; + +use strict; +use warnings; +use Carp; + + +my %secflags = ( + noplaintext => 1, + noanonymous => 1, + nodictionary => 1, +); +my %have; + +sub server_new { + my ($pkg, $parent, $service, $host, $options) = @_; + + my $self = { + callback => { %{$parent->callback} }, + service => $service || '', + host => $host || '', + debug => $parent->{debug} || 0, + need_step => 1, + }; + + my $mechanism = $parent->mechanism + or croak "No server mechanism specified"; + $mechanism =~ s/^\s*\b(.*)\b\s*$/$1/g; + $mechanism =~ s/-/_/g; + $mechanism = uc $mechanism; + my $mpkg = __PACKAGE__ . "::$mechanism"; + eval "require $mpkg;" + or croak "Cannot use $mpkg for " . $parent->mechanism; + my $server = $mpkg->_init($self); + $server->_init_server($options); + return $server; +} + +sub client_new { + my ($pkg, $parent, $service, $host, $secflags) = @_; + + my @sec = grep { $secflags{$_} } split /\W+/, lc($secflags || ''); + + my $self = { + callback => { %{$parent->callback} }, + service => $service || '', + host => $host || '', + debug => $parent->{debug} || 0, + need_step => 1, + }; + + my @mpkg = sort { + $b->_order <=> $a->_order + } grep { + my $have = $have{$_} ||= (eval "require $_;" and $_->can('_secflags')) ? 1 : -1; + $have > 0 and $_->_secflags(@sec) == @sec + and $_->_acceptable( %{$parent->callback} ) + } map { + (my $mpkg = __PACKAGE__ . "::$_") =~ s/-/_/g; + $mpkg; + } split /[^-\w]+/, $parent->mechanism + or croak "No SASL mechanism found: ", $parent->mechanism, "\n"; + + $mpkg[0]->_init($self); +} + +sub _init_server {} + +sub _acceptable { 1 } +sub _order { 0 } +sub code { defined(shift->{error}) || 0 } +sub error { shift->{error} } +sub service { shift->{service} } +sub host { shift->{host} } + +sub need_step { + my $self = shift; + return 0 if $self->{error}; + return $self->{need_step}; +} + +## I think I need to rename that to end()? +## It doesn't mean that SASL is successful, but that +## that the negotiation is over, no more step necessary +## at least for the client +sub set_success { + my $self = shift; + $self->{need_step} = 0; +} + +sub is_success { + my $self = shift; + return !$self->code && !$self->need_step; +} + +sub set_error { + my $self = shift; + $self->{error} = shift; + return; +} + +# set/get property +sub property { + my $self = shift; + my $prop = $self->{property} ||= {}; + return $prop->{ $_[0] } if @_ == 1; + my %new = @_; + @{$prop}{keys %new} = values %new; + 1; +} + +sub callback { + my $self = shift; + + return $self->{callback}{$_[0]} if @_ == 1; + + my %new = @_; + @{$self->{callback}}{keys %new} = values %new; + + $self->{callback}; +} + +# Should be defined in the mechanism sub-class +sub mechanism { undef } +sub client_step { undef } +sub client_start { undef } +sub server_step { undef } +sub server_start { undef } + +# Private methods used by Authen::SASL::Perl that +# may be overridden in mechanism sub-classes + +sub _init { + my ($pkg, $href) = @_; + + bless $href, $pkg; +} + +sub _call { + my ($self, $name) = splice(@_,0,2); + + my $cb = $self->{callback}{$name}; + + return undef unless defined $cb; + + my $value; + + if (ref($cb) eq 'ARRAY') { + my @args = @$cb; + $cb = shift @args; + $value = $cb->($self, @args); + } + elsif (ref($cb) eq 'CODE') { + $value = $cb->($self, @_); + } + else { + $value = $cb; + } + + $self->{answer}{$name} = $value + unless $name eq 'pass'; # Do not store password + + return $value; +} + +# TODO: Need a better name than this +sub answer { + my ($self, $name) = @_; + $self->{answer}{$name}; +} + +sub _secflags { 0 } + +sub securesocket { + my $self = shift; + return $_[0] unless (defined($self->property('ssf')) && $self->property('ssf') > 0); + + local *GLOB; # avoid used only once warning + my $glob = \do { local *GLOB; }; + tie(*$glob, 'Authen::SASL::Perl::Layer', $_[0], $self); + $glob; +} + +{ + +# +# Add SASL encoding/decoding to a filehandle +# + + package # private package; prevent detection by MetaCPAN + Authen::SASL::Perl::Layer; + + use bytes; + + require Tie::Handle; + our @ISA = qw(Tie::Handle); + + sub TIEHANDLE { + my ($class, $fh, $conn) = @_; + my $self; + + warn __PACKAGE__ . ': non-blocking handle may not work' + if ($fh->can('blocking') and not $fh->blocking()); + + $self->{fh} = $fh; + $self->{conn} = $conn; + $self->{readbuflen} = 0; + $self->{sndbufsz} = $conn->property('maxout'); + $self->{rcvbufsz} = $conn->property('maxbuf'); + + return bless($self, $class); + } + + sub CLOSE { + my ($self) = @_; + + # forward close to the inner handle + close($self->{fh}); + delete $self->{fh}; + } + + sub DESTROY { + my ($self) = @_; + delete $self->{fh}; + undef $self; + } + + sub FETCH { + my ($self) = @_; + return $self->{fh}; + } + + sub FILENO { + my ($self) = @_; + return fileno($self->{fh}); + } + + + sub READ { + my ($self, $buf, $len, $offset) = @_; + my $debug = $self->{conn}->{debug}; + + $buf = \$_[1]; + + my $avail = $self->{readbuflen}; + + print STDERR " [READ(len=$len,offset=$offset)] avail=$avail;\n" + if ($debug & 4); + + # Check if there's leftovers from a previous READ + if ($avail <= 0) { + $avail = $self->_getbuf(); + return undef unless ($avail > 0); + } + + # if there's more than we need right now, leave the rest for later + if ($avail >= $len) { + print STDERR " GOT ALL: avail=$avail; need=$len\n" + if ($debug & 4); + substr($$buf, $offset, $len) = substr($self->{readbuf}, 0, $len, ''); + $self->{readbuflen} -= $len; + return ($len); + } + + # there's not enough; take all we have, read more on next call + print STDERR " GOT PARTIAL: avail=$avail; need=$len\n" + if ($debug & 4); + substr($$buf, $offset || 0, $avail) = $self->{readbuf}; + $self->{readbuf} = ''; + $self->{readbuflen} = 0; + + return ($avail); + } + + # retrieve and decode a buffer of cipher text in SASL format + sub _getbuf { + my ($self) = @_; + my $debug = $self->{conn}->{debug}; + my $fh = $self->{fh}; + my $buf = ''; + + # first, read 4-octet buffer size + my $n = 0; + while ($n < 4) { + my $rv = sysread($fh, $buf, 4 - $n, $n); + print STDERR " [getbuf: sysread($fh,$buf,4-$n,$n)=$rv: $!\n" + if ($debug & 4); + return $rv unless $rv > 0; + $n += $rv; + } + + # size is encoded in network byte order + my ($bsz) = unpack('N', $buf); + print STDERR " [getbuf: cipher buffer sz=$bsz]\n" if ($debug & 4); + return undef unless ($bsz <= $self->{rcvbufsz}); + + # next, read actual cipher text + $buf = ''; + $n = 0; + while ($n < $bsz) { + my $rv = sysread($fh, $buf, $bsz - $n, $n); + print STDERR " [getbuf: got o=$n,n=", $bsz - $n, ",rv=$rv,bl=" . length($buf) . "]\n" + if ($debug & 4); + return $rv unless $rv > 0; + $n += $rv; + } + + # call mechanism specific decoding routine + $self->{readbuf} = $self->{conn}->decode($buf, $bsz); + $n = length($self->{readbuf}); + print STDERR " [getbuf: clear text buffer sz=$n]\n" if ($debug & 4); + $self->{readbuflen} = $n; + } + + + # Encrypting a write() to a filehandle is much easier than reading, because + # all the data to be encrypted is immediately available + sub WRITE { + my ($self, $data, $len, $offset) = @_; + my $debug = $self->{conn}->{debug}; + + my $fh = $self->{fh}; + $len = length($data) if $len > length($data); # RT 85294 + + # put on wire in peer-sized chunks + my $bsz = $self->{sndbufsz}; + while ($len > 0) { + print STDERR " [WRITE: chunk $bsz/$len]\n" + if ($debug & 8); + + # call mechanism specific encoding routine + my $x = $self->{conn}->encode(substr($data, $offset || 0, $bsz)); + print $fh pack('N', length($x)), $x; + $len -= $bsz; + $offset += $bsz; + } + + return $_[2]; + } + +} + +1; diff --git a/git/usr/share/perl5/vendor_perl/Authen/SASL/Perl/ANONYMOUS.pm b/git/usr/share/perl5/vendor_perl/Authen/SASL/Perl/ANONYMOUS.pm new file mode 100644 index 0000000000000000000000000000000000000000..faf559b5a8f5fb31e85728dd6fc8af89b7f5ec2e --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Authen/SASL/Perl/ANONYMOUS.pm @@ -0,0 +1,97 @@ +# Copyright (c) 2002 Graham Barr . All rights reserved. +# This program is free software; you can redistribute it and/or +# modify it under the same terms as Perl itself. + +package Authen::SASL::Perl::ANONYMOUS 2.2000; + +use strict; +use warnings; +use vars qw(@ISA); + +@ISA = qw(Authen::SASL::Perl); + +my %secflags = ( + noplaintext => 1, +); + +sub _order { 0 } +sub _secflags { + shift; + grep { $secflags{$_} } @_; +} + +sub mechanism { 'ANONYMOUS' } + +sub client_start { + shift->_call('authname') +} + +sub client_step { + shift->_call('authname') +} + +1; + +__END__ + +=head1 NAME + +Authen::SASL::Perl::ANONYMOUS - Anonymous Authentication class + +=head1 VERSION + +version 2.2000 + +=head1 SYNOPSIS + + use Authen::SASL qw(Perl); + + $sasl = Authen::SASL->new( + mechanism => 'ANONYMOUS', + callback => { + authname => $mailaddress + }, + ); + +=head1 DESCRIPTION + +This method implements the client part of the ANONYMOUS SASL algorithm, +as described in RFC 2245 resp. in IETF Draft draft-ietf-sasl-anon-XX.txt. + +=head2 CALLBACK + +The callbacks used are: + +=over 4 + +=item authname + +email address or UTF-8 encoded string to be used as +trace information for the server + +=back + +=head1 SEE ALSO + +L, +L + +=head1 AUTHORS + +Software written by Graham Barr , +documentation written by Peter Marschall . + +Please report any bugs, or post any suggestions, to the perl-ldap mailing list + + +=head1 COPYRIGHT + +Copyright (c) 2002-2004 Graham Barr. +All rights reserved. This program is free software; you can redistribute +it and/or modify it under the same terms as Perl itself. + +Documentation Copyright (c) 2004 Peter Marschall. +All rights reserved. This documentation is distributed, +and may be redistributed, under the same terms as Perl itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Authen/SASL/Perl/CRAM_MD5.pm b/git/usr/share/perl5/vendor_perl/Authen/SASL/Perl/CRAM_MD5.pm new file mode 100644 index 0000000000000000000000000000000000000000..c8614e786e0a9716cf03b9bedfe35bfca7cd5c3e --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Authen/SASL/Perl/CRAM_MD5.pm @@ -0,0 +1,119 @@ +# Copyright (c) 2002 Graham Barr . All rights reserved. +# This program is free software; you can redistribute it and/or +# modify it under the same terms as Perl itself. + +package Authen::SASL::Perl::CRAM_MD5 2.2000; + +use strict; +use warnings; +use vars qw(@ISA); +use Digest::HMAC_MD5 qw(hmac_md5_hex); + +warnings::warnif( + 'deprecated', + 'The CRAM-MD5 SASL mechanism is effectively deprecated by RFC8314 and should no longer be used' + ); + +@ISA = qw(Authen::SASL::Perl); + +my %secflags = ( + noplaintext => 1, + noanonymous => 1, +); + +sub _order { 2 } +sub _secflags { + shift; + scalar grep { $secflags{$_} } @_; +} + +sub mechanism { 'CRAM-MD5' } + +sub client_start { + ''; +} + +sub client_step { + my ($self, $string) = @_; + my ($user, $pass) = map { + my $v = $self->_call($_); + defined($v) ? $v : '' + } qw(user pass); + + $user . " " . hmac_md5_hex($string,$pass); +} + +1; + +__END__ + +=head1 NAME + +Authen::SASL::Perl::CRAM_MD5 - (DEPRECATED) CRAM MD5 Authentication class + +=head1 VERSION + +version 2.2000 + +=head1 SYNOPSIS + + use Authen::SASL qw(Perl); + + $sasl = Authen::SASL->new( + mechanism => 'CRAM-MD5', + callback => { + user => $user, + pass => $pass + }, + ); + +=head1 DESCRIPTION + +This method implements the client part of the CRAM-MD5 SASL algorithm, +as described in RFC 2195 resp. in IETF Draft draft-ietf-sasl-crammd5-XX.txt. + +Please note that this mechanism has been moved to the "LIMITED" use section of +the L +and is effectively deprecated per L (see +section 5; security considerations). + +=head2 CALLBACK + +The callbacks used are: + +=over 4 + +=item user + +The username to be used for authentication + +=item pass + +The user's password to be used for authentication + +=back + +=head1 SEE ALSO + +L, +L + +=head1 AUTHORS + +Software written by Graham Barr , +documentation written by Peter Marschall . + +Please report any bugs, or post any suggestions, to the perl-ldap mailing list + + +=head1 COPYRIGHT + +Copyright (c) 2002-2004 Graham Barr. +All rights reserved. This program is free software; you can redistribute +it and/or modify it under the same terms as Perl itself. + +Documentation Copyright (c) 2004 Peter Marschall. +All rights reserved. This documentation is distributed, +and may be redistributed, under the same terms as Perl itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Authen/SASL/Perl/DIGEST_MD5.pm b/git/usr/share/perl5/vendor_perl/Authen/SASL/Perl/DIGEST_MD5.pm new file mode 100644 index 0000000000000000000000000000000000000000..b7fe653f905ba0b344ee19d0715e205578ec2f1d --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Authen/SASL/Perl/DIGEST_MD5.pm @@ -0,0 +1,891 @@ +# Copyright (c) 2003-2009 Graham Barr, Djamel Boudjerda, Paul Connolly, Julian +# Onions, Nexor and Yann Kerherve. +# All rights reserved. This program is free software; you can redistribute +# it and/or modify it under the same terms as Perl itself. + +# See http://www.ietf.org/rfc/rfc2831.txt for details + +package Authen::SASL::Perl::DIGEST_MD5 2.2000; + +use strict; +use warnings; +use vars qw(@ISA $CNONCE $NONCE); +use Crypt::URandom qw(urandom); +use Digest::MD5 qw(md5_hex md5); +use Digest::HMAC_MD5 qw(hmac_md5); + +warnings::warnif( + 'deprecated', + 'The DIGEST-MD5 SASL mechanism is deprecated by RFC6331 and should no longer be used' + ); + +# TODO: complete qop support in server, should be configurable + +@ISA = qw(Authen::SASL::Perl); + +my %secflags = ( + noplaintext => 1, + noanonymous => 1, +); + +# some have to be quoted - some don't - sigh! +my (%cqdval, %sqdval); +@cqdval{qw( + username authzid realm nonce cnonce digest-uri +)} = (); + +## ...and server behaves different than client - double sigh! +@sqdval{keys %cqdval, qw(qop cipher)} = (); +# username authzid realm nonce cnonce digest-uri qop cipher +#)} = (); + +my %multi; +@{$multi{server}}{qw(realm auth-param)} = (); +@{$multi{client}}{qw()} = (); + +my @server_required = qw(algorithm nonce); +my @client_required = qw(username nonce cnonce nc qop response); + +# available ciphers +my @ourciphers = ( + { + name => 'rc4', + ssf => 128, + bs => 1, + ks => 16, + pkg => 'Crypt::RC4', + key => sub { $_[0] }, + iv => sub {}, + fixup => sub { + # retrofit the Crypt::RC4 module with standard subs + *Crypt::RC4::encrypt = *Crypt::RC4::decrypt = + sub { goto &Crypt::RC4::RC4; }; + *Crypt::RC4::keysize = sub {128}; + *Crypt::RC4::blocksize = sub {1}; + } + }, + { + name => '3des', + ssf => 112, + bs => 8, + ks => 16, + pkg => 'Crypt::DES3', + key => sub { + pack('B8' x 16, + map { $_ . '0' } + map { unpack('a7' x 16, $_); } + unpack('B*', substr($_[0], 0, 14)) ); + }, + iv => sub { substr($_[0], -8, 8) }, + }, + { + name => 'des', + ssf => 56, + bs => 8, + ks => 16, + pkg => 'Crypt::DES', + key => sub { + pack('B8' x 8, + map { $_ . '0' } + map { unpack('a7' x 8, $_); } + unpack('B*',substr($_[0], 0, 7)) ); + }, + iv => sub { substr($_[0], -8, 8) }, + }, + { + name => 'rc4-56', + ssf => 56, + bs => 1, + ks => 7, + pkg => 'Crypt::RC4', + key => sub { $_[0] }, + iv => sub {}, + fixup => sub { + *Crypt::RC4::encrypt = *Crypt::RC4::decrypt = + sub { goto &Crypt::RC4::RC4; }; + *Crypt::RC4::keysize = sub {56}; + *Crypt::RC4::blocksize = sub {1}; + } + }, + { + name => 'rc4-40', + ssf => 40, + bs => 1, + ks => 5, + pkg => 'Crypt::RC4', + key => sub { $_[0] }, + iv => sub {}, + fixup => sub { + *Crypt::RC4::encrypt = *Crypt::RC4::decrypt = + sub { goto &Crypt::RC4::RC4; }; + *Crypt::RC4::keysize = sub {40}; + *Crypt::RC4::blocksize = sub {1}; + } + }, +); + +## The system we are on, might not be able to crypt the stream +our $NO_CRYPT_AVAILABLE = 1; +for (@ourciphers) { + eval "require $_->{pkg}"; + unless ($@) { + $NO_CRYPT_AVAILABLE = 0; + last; + } +} + +sub _order { 3 } +sub _secflags { + shift; + scalar grep { $secflags{$_} } @_; +} + +sub mechanism { 'DIGEST-MD5' } + +sub _init { + my ($pkg, $self) = @_; + bless $self, $pkg; + + # set default security properties + $self->property('minssf', 0); + $self->property('maxssf', int 2**31 - 1); # XXX - arbitrary "high" value + $self->property('maxbuf', 0xFFFFFF); # maximum supported by GSSAPI mech + $self->property('externalssf', 0); + + $self; +} + +sub _init_server { + my $server = shift; + my $options = shift || {}; + if (!ref $options or ref $options ne 'HASH') { + warn "options for DIGEST_MD5 should be a hashref"; + $options = {}; + } + + ## new server, means new nonce_counts + $server->{nonce_counts} = {}; + + ## determine supported qop + my @qop = ('auth'); + push @qop, 'auth-int' unless $options->{no_integrity}; + push @qop, 'auth-conf' unless $options->{no_integrity} + or $options->{no_confidentiality} + or $NO_CRYPT_AVAILABLE; + + $server->{supported_qop} = { map { $_ => 1 } @qop }; +} + +sub init_sec_layer { + my $self = shift; + $self->{cipher} = undef; + $self->{khc} = undef; + $self->{khs} = undef; + $self->{sndseqnum} = 0; + $self->{rcvseqnum} = 0; + + # reset properties for new session + $self->property(maxout => undef); + $self->property(ssf => undef); +} + +# no initial value passed to the server +sub client_start { + my $self = shift; + + $self->{need_step} = 1; + $self->{error} = undef; + $self->{state} = 0; + $self->init_sec_layer; + ''; +} + +sub server_start { + my $self = shift; + my $challenge = shift; + my $cb = shift || sub {}; + + $self->{need_step} = 1; + $self->{error} = undef; + $self->{nonce} = $NONCE ? md5_hex($NONCE) : unpack('H32',urandom(16)); + + $self->init_sec_layer; + + my $qop = [ sort keys %{$self->{supported_qop}} ]; + + ## get the realm using callbacks but default to the host specified + ## during the instantiation of the SASL object + my $realm = $self->_call('realm'); + $realm ||= $self->host; + + my %response = ( + nonce => $self->{nonce}, + charset => 'utf-8', + algorithm => 'md5-sess', + realm => $realm, + maxbuf => $self->property('maxbuf'), + +## IN DRAFT ONLY: +# If this directive is present multiple times the client MUST treat +# it as if it received a single qop directive containing a comma +# separated value from all instances. I.e., +# 'qop="auth",qop="auth-int"' is the same as 'qop="auth,auth-int" + + 'qop' => $qop, + 'cipher' => [ map { $_->{name} } @ourciphers ], + ); + my $final_response = _response(\%response); + $cb->($final_response); + return; +} + +sub client_step { # $self, $server_sasl_credentials + my ($self, $challenge) = @_; + $self->{server_params} = \my %sparams; + + # Parse response parameters + $self->_parse_challenge(\$challenge, server => $self->{server_params}) + or return $self->set_error("Bad challenge: '$challenge'"); + + if ($self->{state} == 1) { + # check server's `rspauth' response + return $self->set_error("Server did not send rspauth in step 2") + unless ($sparams{rspauth}); + return $self->set_error("Invalid rspauth in step 2") + unless ($self->{rspauth} eq $sparams{rspauth}); + + # all is well + $self->set_success; + return ''; + } + + # check required fields in server challenge + if (my @missing = grep { !exists $sparams{$_} } @server_required) { + return $self->set_error("Server did not provide required field(s): @missing") + } + + my %response = ( + nonce => $sparams{'nonce'}, + cnonce => $CNONCE ? md5_hex($CNONCE) : unpack('H32',urandom(16)), + 'digest-uri' => $self->service . '/' . $self->host, + # calc how often the server nonce has been seen; server expects "00000001" + nc => sprintf("%08d", ++$self->{nonce_counts}{$sparams{'nonce'}}), + charset => $sparams{'charset'}, + ); + + return $self->set_error("Server qop too weak (qop = $sparams{'qop'})") + unless ($self->_client_layer(\%sparams,\%response)); + + # let caller-provided fields override defaults: authorization ID, service name, realm + + my $s_realm = $sparams{realm} || []; + my $realm = $self->_call('realm', @$s_realm); + unless (defined $realm) { + # If the user does not pick a realm, use the first from the server + $realm = $s_realm->[0]; + } + if (defined $realm) { + $response{realm} = $realm; + } + + my $authzid = $self->_call('authname'); + if (defined $authzid) { + $response{authzid} = $authzid; + } + + my $serv_name = $self->_call('serv'); + if (defined $serv_name) { + $response{'digest-uri'} .= '/' . $serv_name; + } + + my $user = $self->_call('user'); + return $self->set_error("Username is required") + unless defined $user; + $response{username} = $user; + + my $password = $self->_call('pass'); + return $self->set_error("Password is required") + unless defined $password; + + $self->property('maxout', $sparams{maxbuf} || 65536); + + # Generate the response value + $self->{state} = 1; + + my ($response, $rspauth) + = $self->_compute_digests_and_set_keys($password, \%response); + + $response{response} = $response; + $self->{rspauth} = $rspauth; + + # finally, return our response token + return _response(\%response, "is_client"); +} + +sub _compute_digests_and_set_keys { + my $self = shift; + my $password = shift; + my $params = shift; + + if (defined $params->{realm} and ref $params->{realm} eq 'ARRAY') { + $params->{realm} = $params->{realm}[0]; + } + + my $realm = $params->{realm}; + $realm = "" unless defined $realm; + + my $A1 = join (":", + md5(join (":", $params->{username}, $realm, $password)), + @$params{defined($params->{authzid}) + ? qw(nonce cnonce authzid) + : qw(nonce cnonce) + } + ); + + # pre-compute MD5(A1) and HEX(MD5(A1)); these are used multiple times below + my $hdA1 = unpack("H*", (my $dA1 = md5($A1)) ); + + # derive keys for layer encryption / integrity + $self->{kic} = md5($dA1, + 'Digest session key to client-to-server signing key magic constant'); + + $self->{kis} = md5($dA1, + 'Digest session key to server-to-client signing key magic constant'); + + if (my $cipher = $self->{cipher}) { + &{ $cipher->{fixup} || sub{} }; + + # compute keys for encryption + my $ks = $cipher->{ks}; + $self->{kcc} = md5(substr($dA1,0,$ks), + 'Digest H(A1) to client-to-server sealing key magic constant'); + $self->{kcs} = md5(substr($dA1,0,$ks), + 'Digest H(A1) to server-to-client sealing key magic constant'); + + # get an encryption and decryption handle for the chosen cipher + $self->{khc} = $cipher->{pkg}->new($cipher->{key}->($self->{kcc})); + $self->{khs} = $cipher->{pkg}->new($cipher->{key}->($self->{kcs})); + + # initialize IVs + $self->{ivc} = $cipher->{iv}->($self->{kcc}); + $self->{ivs} = $cipher->{iv}->($self->{kcs}); + } + + my $A2 = "AUTHENTICATE:" . $params->{'digest-uri'}; + $A2 .= ":00000000000000000000000000000000" if ($params->{qop} ne 'auth'); + + my $response = md5_hex( + join (":", $hdA1, @$params{qw(nonce nc cnonce qop)}, md5_hex($A2)) + ); + + # calculate server `rspauth' response, so we can check in step 2 + # the only difference here is in the A2 string which from which + # `AUTHENTICATE' is omitted in the calculation of `rspauth' + $A2 = ":" . $params->{'digest-uri'}; + $A2 .= ":00000000000000000000000000000000" if ($params->{qop} ne 'auth'); + + my $rspauth = md5_hex( + join (":", $hdA1, @$params{qw(nonce nc cnonce qop)}, md5_hex($A2)) + ); + + return ($response, $rspauth); +} + +sub server_step { + my $self = shift; + my $challenge = shift; + my $cb = shift || sub {}; + + $self->{client_params} = \my %cparams; + unless ( $self->_parse_challenge(\$challenge, client => $self->{client_params}) ) { + $self->set_error("Bad challenge: '$challenge'"); + return $cb->(); + } + + # check required fields in server challenge + if (my @missing = grep { !exists $cparams{$_} } @client_required) { + $self->set_error("Client did not provide required field(s): @missing"); + return $cb->(); + } + + my $count = hex ($cparams{'nc'} || 0); + unless ($count == ++$self->{nonce_counts}{$cparams{nonce}}) { + $self->set_error("nonce-count doesn't match: $count"); + return $cb->(); + } + + my $qop = $cparams{'qop'} || "auth"; + unless ($self->is_qop_supported($qop)) { + $self->set_error("Client qop not supported (qop = '$qop')"); + return $cb->(); + } + + my $username = $cparams{'username'}; + unless ($username) { + $self->set_error("Client didn't provide a username"); + return $cb->(); + } + + # "The authzid MUST NOT be an empty string." + if (exists $cparams{authzid} && $cparams{authzid} eq '') { + $self->set_error("authzid cannot be empty"); + return $cb->(); + } + my $authzid = $cparams{authzid}; + + # digest-uri: "Servers SHOULD check that the supplied value is correct. + # This will detect accidental connection to the incorrect server, as well as + # some redirection attacks" + my $digest_uri = $cparams{'digest-uri'}; + my ($cservice, $chost, $cservname) = split '/', $digest_uri, 3; + if ($cservice ne $self->service or $chost ne $self->host) { + # XXX deal with serv_name + $self->set_error("Incorrect digest-uri"); + return $cb->(); + } + + unless (defined $self->callback('getsecret')) { + $self->set_error("a getsecret callback MUST be defined"); + $cb->(); + return; + } + + my $realm = $self->{client_params}->{'realm'}; + my $response_check = sub { + my $password = shift; + return $self->set_error("Cannot get the passord for $username") + unless defined $password; + + ## configure the security layer + $self->_server_layer($qop) + or return $self->set_error("Cannot negociate the security layer"); + + my ($expected, $rspauth) + = $self->_compute_digests_and_set_keys($password, $self->{client_params}); + + return $self->set_error("Incorrect response $self->{client_params}->{response} <> $expected") + unless $expected eq $self->{client_params}->{response}; + + my %response = ( + rspauth => $rspauth, + ); + + # I'm not entirely sure of what I am doing + $self->{answer}{$_} = $self->{client_params}->{$_} for qw/username authzid realm serv/; + + $self->set_success; + return _response(\%response); + }; + + $self->callback('getsecret')->( + $self, + { user => $username, realm => $realm, authzid => $authzid }, + sub { $cb->( $response_check->( shift ) ) }, + ); +} + +sub is_qop_supported { + my $self = shift; + my $qop = shift; + return $self->{supported_qop}{$qop}; +} + +sub _response { + my $response = shift; + my $is_client = shift; + + my @out; + for my $k (sort keys %$response) { + my $is_array = ref $response->{$k} && ref $response->{$k} eq 'ARRAY'; + my @values = $is_array ? @{$response->{$k}} : ($response->{$k}); + # Per spec, one way of doing it: multiple k=v + #push @out, [$k, $_] for @values; + # other way: comma separated list + push @out, [$k, join (',', @values)]; + } + return join (",", map { _qdval($_->[0], $_->[1], $is_client) } @out); +} + +sub _parse_challenge { + my $self = shift; + my $challenge_ref = shift; + my $type = shift; + my $params = shift; + + while($$challenge_ref =~ + s/^(?:\s*,)*\s* # remaining or crap + ([\w-]+) # key, eg: qop + = + ("([^\\"]+|\\.)*"|[^,]+) # value, eg: auth-conf or "NoNcE" + \s*(?:,\s*)* # remaining + //x) { + + my ($k, $v) = ($1,$2); + if ($v =~ /^"(.*)"$/s) { + ($v = $1) =~ s/\\(.)/$1/g; + } + if (exists $multi{$type}{$k}) { + my $aref = $params->{$k} ||= []; + push @$aref, $v; + } + elsif (defined $params->{$k}) { + return $self->set_error("Bad challenge: '$$challenge_ref'"); + } + else { + $params->{$k} = $v; + } + } + return length $$challenge_ref ? 0 : 1; +} + +sub _qdval { + my ($k, $v, $is_client) = @_; + + my $qdval = $is_client ? \%cqdval : \%sqdval; + + if (!defined $v) { + return; + } + elsif (exists $qdval->{$k}) { + $v =~ s/([\\"])/\\$1/g; + return qq{$k="$v"}; + } + + return "$k=$v"; +} + +sub _server_layer { + my ($self, $auth) = @_; + + # XXX dupe + # construct our qop mask + my $maxssf = $self->property('maxssf') - $self->property('externalssf'); + $maxssf = 0 if ($maxssf < 0); + my $minssf = $self->property('minssf') - $self->property('externalssf'); + $minssf = 0 if ($minssf < 0); + + return undef if ($maxssf < $minssf); # sanity check + + my $ciphers = [ map { $_->{name} } @ourciphers ]; + if (( $auth eq 'auth-conf') + and $self->_select_cipher($minssf, $maxssf, $ciphers )) { + $self->property('ssf', $self->{cipher}->{ssf}); + return 1; + } + if ($auth eq 'auth-int') { + $self->property('ssf', 1); + return 1; + } + if ($auth eq 'auth') { + $self->property('ssf', 0); + return 1; + } + + return undef; +} + +sub _client_layer { + my ($self, $sparams, $response) = @_; + + # construct server qop mask + # qop in server challenge is optional: if not there "auth" is assumed + my $smask = 0; + map { + m/^auth$/ and $smask |= 1; + m/^auth-int$/ and $smask |= 2; + m/^auth-conf$/ and $smask |= 4; + } split(/,/, $sparams->{qop}||'auth'); # XXX I think we might have a bug here bc. of LWS + + # construct our qop mask + my $cmask = 0; + my $maxssf = $self->property('maxssf') - $self->property('externalssf'); + $maxssf = 0 if ($maxssf < 0); + my $minssf = $self->property('minssf') - $self->property('externalssf'); + $minssf = 0 if ($minssf < 0); + + return undef if ($maxssf < $minssf); # sanity check + + # ssf values > 1 mean integrity and confidentiality + # ssf == 1 means integrity but no confidentiality + # ssf < 1 means neither integrity nor confidentiality + # no security layer can be had if buffer size is 0 + $cmask |= 1 if ($minssf < 1); + $cmask |= 2 if ($minssf <= 1 and $maxssf >= 1); + $cmask |= 4 if ($maxssf > 1); + + # find common bits + $cmask &= $smask; + + # parse server cipher options + my @sciphers = split(/,/, $sparams->{'cipher-opts'}||$sparams->{cipher}||''); + + if (($cmask & 4) and $self->_select_cipher($minssf,$maxssf,\@sciphers)) { + $response->{qop} = 'auth-conf'; + $response->{cipher} = $self->{cipher}->{name}; + $self->property('ssf', $self->{cipher}->{ssf}); + return 1; + } + if ($cmask & 2) { + $response->{qop} = 'auth-int'; + $self->property('ssf', 1); + return 1; + } + if ($cmask & 1) { + $response->{qop} = 'auth'; + $self->property('ssf', 0); + return 1; + } + + return undef; +} + +sub _select_cipher { + my ($self, $minssf, $maxssf, $ciphers) = @_; + + # compose a subset of candidate ciphers based on ssf and peer list + my @a = map { + my $c = $_; + (grep { $c->{name} eq $_ } @$ciphers and + $c->{ssf} >= $minssf and $c->{ssf} <= $maxssf) ? $_ : () + } @ourciphers; + + # from these, select the first one we can create an instance of + for (@a) { + next unless eval "require $_->{pkg}"; + $self->{cipher} = $_; + return 1; + } + + return 0; +} + +use Digest::HMAC_MD5 qw(hmac_md5); + +sub encode { # input: self, plaintext buffer,length (length not used here) + my $self = shift; + my $seqnum = pack('N', $self->{sndseqnum}++); + my $mac = substr(hmac_md5($seqnum . $_[0], $self->{kic}), 0, 10); + + # if integrity only, return concatenation of buffer, MAC, TYPE and SEQNUM + return $_[0] . $mac.pack('n',1) . $seqnum unless ($self->{khc}); + + # must encrypt, block ciphers need padding bytes + my $pad = ''; + my $bs = $self->{cipher}->{bs}; + if ($bs > 1) { + # padding is added in between BUF and MAC + my $n = $bs - ((length($_[0]) + 10) & ($bs - 1)); + $pad = chr($n) x $n; + } + + # XXX - for future AES cipher support, the currently used common _crypt() + # function probably wont do; we might to switch to per-cipher routines + # like so: + # return $self->{khc}->encrypt($_[0] . $pad . $mac) . pack('n', 1) . $seqnum; + return $self->_crypt(0, $_[0] . $pad . $mac) . pack('n', 1) . $seqnum; +} + +sub decode { # input: self, cipher buffer,length + my ($self, $buf, $len) = @_; + + return if ($len <= 16); + + # extract TYPE/SEQNUM from end of buffer + my ($type,$seqnum) = unpack('na[4]', substr($buf, -6, 6, '')); + + # decrypt remaining buffer, if necessary + if ($self->{khs}) { + # XXX - see remark above in encode() #$buf = $self->{khs}->decrypt($buf); + $buf = $self->_crypt(1, $buf); + } + return unless ($buf); + + # extract 10-byte MAC from the end of (decrypted) buffer + my ($mac) = unpack('a[10]', substr($buf, -10, 10, '')); + + if ($self->{khs} and $self->{cipher}->{bs} > 1) { + # remove padding + my $n = ord(substr($buf, -1, 1)); + substr($buf, -$n, $n, ''); + } + + # check the MAC + my $check = substr(hmac_md5($seqnum . $buf, $self->{kis}), 0, 10); + return if ($mac ne $check); + return if (unpack('N', $seqnum) != $self->{rcvseqnum}); + $self->{rcvseqnum}++; + + return $buf; +} + +sub _crypt { # input: op(decrypting=1/encrypting=0)), buffer + my ($self,$d) = (shift,shift); + my $bs = $self->{cipher}->{bs}; + + if ($bs <= 1) { + # stream cipher + return $d ? $self->{khs}->decrypt($_[0]) : $self->{khc}->encrypt($_[0]) + } + + # the remainder of this sub is for block ciphers + + # get current IV + my $piv = \$self->{$d ? 'ivs' : 'ivc'}; + my $iv = $$piv; + + my $result = join '', map { + my $x = $d + ? $iv ^ $self->{khs}->decrypt($_) + : $self->{khc}->encrypt($iv ^ $_); + $iv = $d ? $_ : $x; + $x; + } unpack("a$bs "x(int(length($_[0])/$bs)), $_[0]); + + # store current IV + $$piv = $iv; + return $result; +} + +1; + +__END__ + +=head1 NAME + +Authen::SASL::Perl::DIGEST_MD5 - (DEPRECATED) Digest MD5 Authentication class + +=head1 VERSION + +version 2.2000 + +=head1 SYNOPSIS + + use Authen::SASL qw(Perl); + + $sasl = Authen::SASL->new( + mechanism => 'DIGEST-MD5', + callback => { + user => $user, + pass => $pass, + serv => $serv + }, + ); + +=head1 DESCRIPTION + +This method implements the client and server parts of the DIGEST-MD5 SASL +algorithm, as described in RFC 2831. + +Please note that this mechanism has been moved to the "OBSOLETE" section of +the L +as per L. + +=head2 CALLBACK + +The callbacks used are: + +=head3 client + +=over 4 + +=item authname + +The authorization id to use after successful authentication + +=item user + +The username to be used in the response + +=item pass + +The password to be used to compute the response. + +=item serv + +The service name when authenticating to a replicated service + +=item realm + +The authentication realm when overriding the server-provided default. +If not given the server-provided value is used. + +The callback will be passed the list of realms that the server provided +in the initial response. + +=back + +=head3 server + +=over 4 + +=item realm + +The default realm to provide to the client + +=item getsecret(username, realm, authzid) + +returns the password associated with C and C + +=back + +=head2 PROPERTIES + +The properties used are: + +=over 4 + +=item maxbuf + +The maximum buffer size for receiving cipher text + +=item minssf + +The minimum SSF value that should be provided by the SASL security layer. +The default is 0 + +=item maxssf + +The maximum SSF value that should be provided by the SASL security layer. +The default is 2**31 + +=item externalssf + +The SSF value provided by an underlying external security layer. +The default is 0 + +=item ssf + +The actual SSF value provided by the SASL security layer after the SASL +authentication phase has been completed. This value is read-only and set +by the implementation after the SASL authentication phase has been completed. + +=item maxout + +The maximum plaintext buffer size for sending data to the peer. +This value is set by the implementation after the SASL authentication +phase has been completed and a SASL security layer is in effect. + +=back + + +=head1 SEE ALSO + +L, +L + +=head1 AUTHORS + +Graham Barr, Djamel Boudjerda (NEXOR), Paul Connolly, Julian Onions (NEXOR), +Yann Kerherve. + +Please report any bugs, or post any suggestions, to the perl-ldap mailing list + + +=head1 COPYRIGHT + +Copyright (c) 2003-2009 Graham Barr, Djamel Boudjerda, Paul Connolly, +Julian Onions, Nexor, Peter Marschall and Yann Kerherve. +All rights reserved. This program is free software; you can redistribute +it and/or modify it under the same terms as Perl itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Authen/SASL/Perl/EXTERNAL.pm b/git/usr/share/perl5/vendor_perl/Authen/SASL/Perl/EXTERNAL.pm new file mode 100644 index 0000000000000000000000000000000000000000..62f3ec8801d854e7f542928a2c2e1370f18e3ca0 --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Authen/SASL/Perl/EXTERNAL.pm @@ -0,0 +1,101 @@ +# Copyright (c) 1998-2002 Graham Barr and 2001 Chris Ridd +# . All rights reserved. This program +# is free software; you can redistribute it and/or modify it under the +# same terms as Perl itself. + +package Authen::SASL::Perl::EXTERNAL 2.2000; + +use strict; +use warnings; +use vars qw(@ISA); + +@ISA = qw(Authen::SASL::Perl); + +my %secflags = ( + noplaintext => 1, + nodictionary => 1, + noanonymous => 1, +); + +sub _order { 2 } +sub _secflags { + shift; + grep { $secflags{$_} } @_; +} + +sub mechanism { 'EXTERNAL' } + +sub client_start { + my $self = shift; + my $v = $self->_call('user'); + defined($v) ? $v : '' +} + +#sub client_step { +# shift->_call('user'); +#} + +1; + +__END__ + +=head1 NAME + +Authen::SASL::Perl::EXTERNAL - External Authentication class + +=head1 VERSION + +version 2.2000 + +=head1 SYNOPSIS + + use Authen::SASL qw(Perl); + + $sasl = Authen::SASL->new( + mechanism => 'EXTERNAL', + callback => { + user => $user + }, + ); + +=head1 DESCRIPTION + +This method implements the client part of the EXTERNAL SASL algorithm, +as described in RFC 2222. + +=head2 CALLBACK + +The callbacks used are: + +=over 4 + +=item user + +The username to be used for authentication + +=back + +=head1 SEE ALSO + +L, +L + +=head1 AUTHORS + +Software written by Graham Barr , +documentation written by Peter Marschall . + +Please report any bugs, or post any suggestions, to the perl-ldap mailing list + + +=head1 COPYRIGHT + +Copyright (c) 1998-2004 Graham Barr. +All rights reserved. This program is free software; you can redistribute +it and/or modify it under the same terms as Perl itself. + +Documentation Copyright (c) 2004 Peter Marschall. +All rights reserved. This documentation is distributed, +and may be redistributed, under the same terms as Perl itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Authen/SASL/Perl/GSSAPI.pm b/git/usr/share/perl5/vendor_perl/Authen/SASL/Perl/GSSAPI.pm new file mode 100644 index 0000000000000000000000000000000000000000..114b5e9cbf99d484c927bffeee0dc0566cb611ef --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Authen/SASL/Perl/GSSAPI.pm @@ -0,0 +1,380 @@ +# Copyright (c) 2006 Simon Wilkinson +# All rights reserved. This program is free software; you can redistribute +# it and/or modify it under the same terms as Perl itself. + +package Authen::SASL::Perl::GSSAPI 2.2000; + +use strict; +use warnings; + +use vars qw(@ISA); +use GSSAPI; + +@ISA = qw(Authen::SASL::Perl); + +my %secflags = ( + noplaintext => 1, + noanonymous => 1, +); + +sub _order { 4 } +sub _secflags { + shift; + scalar grep { $secflags{$_} } @_; +} + +sub mechanism { 'GSSAPI' } + +sub _init { + my ($pkg, $self) = @_; + bless $self, $pkg; + + # set default security properties + $self->property('minssf', 0); + $self->property('maxssf', int 2**31 - 1); # XXX - arbitrary "high" value + $self->property('maxbuf', 0xFFFFFF); # maximum supported by GSSAPI mech + $self->property('externalssf', 0); + # the cyrus sasl library allows only one bit to be set in the + # layer selection mask in the client reply, we default to + # compatibility with that bug + $self->property('COMPAT_CYRUSLIB_REPLY_MASK_BUG', 1); + $self; +} + +sub client_start { + my $self = shift; + my $status; + my $principal = $self->service.'@'.$self->host; + + # GSSAPI::Name->import is the *constructor*, + # storing the new GSSAPI::Name into $target. + # GSSAPI::Name->import is not the standard + # import() method as used in Perl normally + my $target; + $status = GSSAPI::Name->import($target, $principal, gss_nt_service_name) + or return $self->set_error("GSSAPI Error : ".$status); + $self->{gss_name} = $target; + $self->{gss_ctx} = new GSSAPI::Context; + $self->{gss_state} = 0; + $self->{gss_layer} = undef; + my $cred = $self->_call('pass'); + $self->{gss_cred} = (ref($cred) && $cred->isa('GSSAPI::Cred')) ? $cred : GSS_C_NO_CREDENTIAL; + $self->{gss_mech} = $self->_call('gssmech') || gss_mech_krb5; + + # reset properties for new session + $self->property(maxout => undef); + $self->property(ssf => undef); + + return $self->client_step(''); +} + +sub client_step { + my ($self, $challenge) = @_; + my $debug = $self->{debug}; + + my $status; + + if ($self->{gss_state} == 0) { + my $outtok; + my $inflags = GSS_C_INTEG_FLAG | GSS_C_MUTUAL_FLAG;#todo:set according to ssf props + my $outflags; + $status = $self->{gss_ctx}->init($self->{gss_cred}, $self->{gss_name}, + $self->{gss_mech}, + $inflags, + 0, GSS_C_NO_CHANNEL_BINDINGS, $challenge, undef, + $outtok, $outflags, undef); + + print STDERR "state(0): ". + $status->generic_message.';'.$status->specific_message. + "; output token sz: ".length($outtok)."\n" + if ($debug & 1); + + if (GSSAPI::Status::GSS_ERROR($status->major)) { + return $self->set_error("GSSAPI Error (init): ".$status); + } + if ($status->major == GSS_S_COMPLETE) { + $self->{gss_state} = 1; + } + return $outtok; + } + elsif ($self->{gss_state} == 1) { + # If the server has an empty output token when it COMPLETEs, Cyrus SASL + # kindly sends us that empty token. We need to ignore it, which introduces + # another round into the process. + print STDERR " state(1): challenge is EMPTY\n" + if ($debug and $challenge eq ''); + return '' if ($challenge eq ''); + + my $unwrapped; + $status = $self->{gss_ctx}->unwrap($challenge, $unwrapped, undef, undef) + or return $self->set_error("GSSAPI Error (unwrap challenge): ".$status); + + return $self->set_error("GSSAPI Error : invalid security layer token") + if (length($unwrapped) != 4); + + # the security layers the server supports: bitmask of + # 1 = no security layer, + # 2 = integrity protection, + # 4 = confidentiality protection + # which is encoded in the first octet of the response; + # the remote maximum buffer size is encoded in the next three octets + # + my $layer = ord(substr($unwrapped, 0, 1, chr(0))); + my ($rsz) = unpack('N',$unwrapped); + + # get local receive buffer size + my $lsz = $self->property('maxbuf'); + + # choose security layer + my $choice = $self->_layer($layer,$rsz,$lsz); + return $self->set_error("GSSAPI Error: security too weak") unless $choice; + + $self->{gss_layer} = $choice; + + if ($choice > 1) { + # determine maximum plain text message size for peer's cipher buffer + my $psz; + $status = $self->{gss_ctx}->wrap_size_limit($choice & 4, 0, $rsz, $psz) + or return $self->set_error("GSSAPI Error (wrap size): ".$status); + return $self->set_error("GSSAPI wrap size = 0") unless ($psz); + $self->property(maxout => $psz); + # set SSF property; if we have just integrity protection SSF is set + # to 1. If we have confidentiality, SSF would be an estimate of the + # strength of the actual encryption ciphers in use which is not + # available through the GSSAPI interface; for now just set it to + # the lowest value that signifies confidentiality. + $self->property(ssf => (($choice & 4) ? 2 : 1)); + } else { + # our advertised buffer size should be 0 if no layer selected + $lsz = 0; + $self->property(ssf => 0); + } + + print STDERR "state(1): layermask $layer,rsz $rsz,lsz $lsz,choice $choice\n" + if ($debug & 1); + + my $message = pack('CCCC', $choice, + ($lsz >> 16)&0xff, ($lsz >> 8)&0xff, $lsz&0xff); + + # append authorization identity if we have one + my $authz = $self->_call('authname'); + $message .= $authz if ($authz); + + my $outtok; + $status = $self->{gss_ctx}->wrap(0, 0, $message, undef, $outtok) + or return $self->set_error("GSSAPI Error (wrap token): ".$status); + + $self->{gss_state} = 0; + return $outtok; + } +} + +# default layer selection +sub _layer { + my ($self, $theirmask, $rsz, $lsz) = @_; + my $maxssf = $self->property('maxssf') - $self->property('externalssf'); + $maxssf = 0 if ($maxssf < 0); + + my $minssf = $self->property('minssf') - $self->property('externalssf'); + $minssf = 0 if ($minssf < 0); + + return undef if ($maxssf < $minssf); # sanity check + + # ssf values > 1 mean integrity and confidentiality + # ssf == 1 means integrity but no confidentiality + # ssf < 1 means neither integrity nor confidentiality + # no security layer can be had if buffer size is 0 + my $ourmask = 0; + $ourmask |= 1 if ($minssf < 1); + $ourmask |= 2 if ($minssf <= 1 and $maxssf >= 1); + $ourmask |= 4 if ($maxssf > 1); + $ourmask &= 1 unless ($rsz and $lsz); + + # mask the bits they don't have + $ourmask &= $theirmask; + + return $ourmask unless $self->property('COMPAT_CYRUSLIB_REPLY_MASK_BUG'); + + # in cyrus sasl bug compat mode, select the highest bit set + return 4 if ($ourmask & 4); + return 2 if ($ourmask & 2); + return 1 if ($ourmask & 1); + return undef; +} + +sub encode { # input: self, plaintext buffer,length (length not used here) + my $self = shift; + my $wrapped; + my $status = $self->{gss_ctx}->wrap($self->{gss_layer} & 4, 0, $_[0], undef, $wrapped); + $self->set_error("GSSAPI Error (encode): " . $status), return + unless ($status); + return $wrapped; +} + +sub decode { # input: self, cipher buffer,length (length not used here) + my $self = shift; + my $unwrapped; + my $status = $self->{gss_ctx}->unwrap($_[0], $unwrapped, undef, undef); + $self->set_error("GSSAPI Error (decode): " . $status), return + unless ($status); + return $unwrapped; +} + +__END__ + +=head1 NAME + +Authen::SASL::Perl::GSSAPI - GSSAPI (Kerberosv5) Authentication class + +=head1 VERSION + +version 2.2000 + +=head1 SYNOPSIS + + use Authen::SASL qw(Perl); + + $sasl = Authen::SASL->new( mechanism => 'GSSAPI' ); + + $sasl = Authen::SASL->new( mechanism => 'GSSAPI', + callback => { pass => $mycred }); + + $sasl->client_start( $service, $host ); + +=head1 DESCRIPTION + +This method implements the client part of the GSSAPI SASL algorithm, +as described in RFC 2222 section 7.2.1 resp. draft-ietf-sasl-gssapi-XX.txt. + +With a valid Kerberos 5 credentials cache (aka TGT) it allows +to connect to I@I given as the first two parameters +to Authen::SASL's client_start() method. Alternatively, a GSSAPI::Cred +object can be passed in via the Authen::SASL callback hash using +the `pass' key. + +Please note that this module does not currently implement a SASL +security layer following authentication. Unless the connection is +protected by other means, such as TLS, it will be vulnerable to +man-in-the-middle attacks. If security layers are required, then the +L GSSAPI module should be used instead. + +=head2 CALLBACK + +The callbacks used are: + +=over 4 + +=item authname + +The authorization identity to be used in SASL exchange + +=item gssmech + +The GSS mechanism to be used in the connection + +=item pass + +The GSS credentials to be used in the connection (optional) + +=back + + +=head1 EXAMPLE + + #! /usr/bin/perl -w + + use strict; +use warnings; + + use Net::LDAP 0.33; + use Authen::SASL 2.10; + + # -------- Adjust to your environment -------- + my $adhost = 'theserver.bla.net'; + my $ldap_base = 'dc=bla,dc=net'; + my $ldap_filter = '(&(sAMAccountName=BLAAGROL))'; + + my $sasl = Authen::SASL->new(mechanism => 'GSSAPI'); + my $ldap; + + eval { + $ldap = Net::LDAP->new($adhost, + onerror => 'die') + or die "Cannot connect to LDAP host '$adhost': '$@'"; + $ldap->bind(sasl => $sasl); + }; + + if ($@) { + chomp $@; + die "\nBind error : $@", + "\nDetailed SASL error: ", $sasl->error, + "\nTerminated"; + } + + print "\nLDAP bind() succeeded, working in authenticated state"; + + my $mesg = $ldap->search(base => $ldap_base, + filter => $ldap_filter); + + # -------- evaluate $mesg + +=head2 PROPERTIES + +The properties used are: + +=over 4 + +=item maxbuf + +The maximum buffer size for receiving cipher text + +=item minssf + +The minimum SSF value that should be provided by the SASL security layer. +The default is 0 + +=item maxssf + +The maximum SSF value that should be provided by the SASL security layer. +The default is 2**31 + +=item externalssf + +The SSF value provided by an underlying external security layer. +The default is 0 + +=item ssf + +The actual SSF value provided by the SASL security layer after the SASL +authentication phase has been completed. This value is read-only and set +by the implementation after the SASL authentication phase has been completed. + +=item maxout + +The maximum plaintext buffer size for sending data to the peer. +This value is set by the implementation after the SASL authentication +phase has been completed and a SASL security layer is in effect. + +=back + + +=head1 SEE ALSO + +L, +L + +=head1 AUTHORS + +Written by Simon Wilkinson, with patches and extensions by Achim Grolms +and Peter Marschall. + +Please report any bugs, or post any suggestions, to the perl-ldap mailing list + + +=head1 COPYRIGHT + +Copyright (c) 2006 Simon Wilkinson, Achim Grolms and Peter Marschall. +All rights reserved. This program is free software; you can redistribute +it and/or modify it under the same terms as Perl itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Authen/SASL/Perl/LOGIN.pm b/git/usr/share/perl5/vendor_perl/Authen/SASL/Perl/LOGIN.pm new file mode 100644 index 0000000000000000000000000000000000000000..a54b8987e2453efe4cb4f4f5b6472d52a3cd72a6 --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Authen/SASL/Perl/LOGIN.pm @@ -0,0 +1,220 @@ +# Copyright (c) 2002 Graham Barr . All rights reserved. +# This program is free software; you can redistribute it and/or +# modify it under the same terms as Perl itself. + +package Authen::SASL::Perl::LOGIN 2.2000; + +use strict; +use warnings; +use vars qw(@ISA); + +@ISA = qw(Authen::SASL::Perl); + +my %secflags = ( + noanonymous => 1, +); + +sub _order { 1 } +sub _secflags { + shift; + scalar grep { $secflags{$_} } @_; +} + +sub mechanism { 'LOGIN' } + +sub client_start { + my $self = shift; + $self->{stage} = 0; + ''; +} + +sub client_step { + my ($self, $string) = @_; + + # XXX technically this is wrong. I might want to change that. + # spec say it's "staged" and that the content of the challenge doesn't + # matter + # actually, let's try + my $stage = ++$self->{stage}; + if ($stage == 1) { + return $self->_call('user'); + } + elsif ($stage == 2) { + return $self->_call('pass'); + } + elsif ($stage == 3) { + $self->set_success; + return; + } + else { + return $self->set_error("Invalid sequence"); + } +} + +sub server_start { + my $self = shift; + my $response = shift; + my $user_cb = shift || sub {}; + + $self->{answer} = {}; + $self->{stage} = 0; + $self->{need_step} = 1; + $self->{error} = undef; + $user_cb->('Username:'); + return; +} + +sub server_step { + my $self = shift; + my $response = shift; + my $user_cb = shift || sub {}; + + my $stage = ++$self->{stage}; + + if ($stage == 1) { + unless (defined $response) { + $self->set_error("Invalid sequence (empty username)"); + return $user_cb->(); + } + $self->{answer}{user} = $response; + return $user_cb->("Password:"); + } + elsif ($stage == 2) { + unless (defined $response) { + $self->set_error("Invalid sequence (empty pass)"); + return $user_cb->(); + } + $self->{answer}{pass} = $response; + } + else { + $self->set_error("Invalid sequence (end)"); + return $user_cb->(); + } + my $error = "Credentials don't match"; + my $answers = { user => $self->{answer}{user}, pass => $self->{answer}{pass} }; + if (my $checkpass = $self->{callback}{checkpass}) { + my $cb = sub { + my $result = shift; + unless ($result) { + $self->set_error($error); + } + else { + $self->set_success; + } + $user_cb->(); + }; + $checkpass->($self => $answers => $cb ); + return; + } + elsif (my $getsecret = $self->{callback}{getsecret}) { + my $cb = sub { + my $good_pass = shift; + if ($good_pass && $good_pass eq ($self->{answer}{pass} || "")) { + $self->set_success; + } + else { + $self->set_error($error); + } + $user_cb->(); + }; + $getsecret->($self => $answers => $cb ); + return; + } + else { + $self->set_error($error); + $user_cb->(); + } + return; +} + +1; + +__END__ + +=head1 NAME + +Authen::SASL::Perl::LOGIN - Login Authentication class + +=head1 VERSION + +version 2.2000 + +=head1 SYNOPSIS + + use Authen::SASL qw(Perl); + + $sasl = Authen::SASL->new( + mechanism => 'LOGIN', + callback => { + user => $user, + pass => $pass + }, + ); + +=head1 DESCRIPTION + +This method implements the client and server part of the LOGIN SASL algorithm, +as described in IETF Draft draft-murchison-sasl-login-XX.txt. + +=head2 CALLBACK + +The callbacks used are: + +=head3 Client + +=over 4 + +=item user + +The username to be used for authentication + +=item pass + +The user's password to be used for authentication + +=back + +=head3 Server + +=over 4 + +=item getsecret(username) + +returns the password associated with C + +=item checkpass(username, password) + +returns true and false depending on the validity of the credentials passed +in arguments. + +=back + +=head1 SEE ALSO + +L, +L + +=head1 AUTHORS + +Software written by Graham Barr , +documentation written by Peter Marschall . +Server support by Yann Kerherve + +Please report any bugs, or post any suggestions, to the perl-ldap mailing list + + +=head1 COPYRIGHT + +Copyright (c) 2002-2004 Graham Barr. +All rights reserved. This program is free software; you can redistribute +it and/or modify it under the same terms as Perl itself. + +Documentation Copyright (c) 2004 Peter Marschall. +All rights reserved. This documentation is distributed, +and may be redistributed, under the same terms as Perl itself. + +Server support Copyright (c) 2009 Yann Kerherve. +All rights reserved. This program is free software; you can redistribute +it and/or modify it under the same terms as Perl itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Authen/SASL/Perl/OAUTHBEARER.pm b/git/usr/share/perl5/vendor_perl/Authen/SASL/Perl/OAUTHBEARER.pm new file mode 100644 index 0000000000000000000000000000000000000000..db8ae085d0b747ff8d8639b64e76885f45173ab6 --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Authen/SASL/Perl/OAUTHBEARER.pm @@ -0,0 +1,148 @@ +# Copyright (c) 2025 Aditya Garg +# Copyright (c) 2025 Julian Swagemakers +# All rights reserved. +# This program is free software; you can redistribute it and/or +# modify it under the same terms as Perl itself. + +package Authen::SASL::Perl::OAUTHBEARER 2.2000; + +use strict; +use warnings; +use vars qw(@ISA); +use JSON::PP; + +@ISA = qw(Authen::SASL::Perl); + +my %secflags = ( + noanonymous => 1, +); + +sub _order { 1 } + +sub _secflags { + shift; + scalar grep { $secflags{$_} } @_; +} + +sub mechanism { 'OAUTHBEARER' } + +sub client_start { + my $self = shift; + $self->{stage} = 0; + + # This will generate the oauthbearer string used for authentication. + # + # "n,a=" {User} ",^Ahost=" {Host} "^Aport=" {Port} "^Aauth=Bearer " {Access Token} "^A^A + # + # The first part `n,a=" {User} ",` is the gs2 header described in RFC5801. + # * gs2-cb-flag `n` -> client does not support CB + # * gs2-authzid `a=" {User} "` + # + # The second part are key value pairs containing host, port and auth as + # described in RFC7628. Host and port are optional and can be omitted. + # + # https://datatracker.ietf.org/doc/html/rfc5801 + # https://datatracker.ietf.org/doc/html/rfc7628 + my $username = $self->_call('user'); + my $host = $self->_call('host'); + my $port = $self->_call('port'); + my $token = $self->_call('pass'); # OAuth 2.0 access token + my $auth_string; + if (defined $host && defined $port) { + $auth_string = "n,a=$username,\001host=$host\001port=$port\001auth=Bearer $token\001\001"; + } elsif (defined $host) { + $auth_string = "n,a=$username,\001host=$host\001auth=Bearer $token\001\001"; + } elsif (defined $port) { + $auth_string = "n,a=$username,\001port=$port\001auth=Bearer $token\001\001"; + } else { + $auth_string = "n,a=$username,\001auth=Bearer $token\001\001"; + } + + return $auth_string; +} + +sub client_step { + my ($self, $challenge) = @_; + my $json = JSON::PP->new; + my $payload = $json->decode( $challenge ); + $self->set_error( $payload ); + # Send dummy request on authentication failure according to rfc7628. + # https://datatracker.ietf.org/doc/html/rfc7628#section-3.2.3 + return "\001"; +} + +1; + +__END__ + +=head1 NAME + +Authen::SASL::Perl::OAUTHBEARER - OAUTHBEARER Authentication class + +=head1 VERSION + +version 2.2000 + +=head1 SYNOPSIS + + use Authen::SASL qw(Perl); + + $sasl = Authen::SASL->new( + mechanism => 'OAUTHBEARER', + callback => { + user => $user, + host => $hostname, #optional + port => $port, #optional + pass => $access_token + }, + ); + +=head1 DESCRIPTION + +This module implements the client side of the OAUTHBEARER SASL mechanism, +which is used for OAuth 2.0-based authentication. + +=head2 CALLBACK + +The callbacks used are: + +=head3 Client + +=over 4 + +=item user + +The username to be used for authentication. + +=item host + +The hostname to which the client will connect to. It is optional and can be omitted. + +=item port + +The destination port that the client will connect to. It should be a decimal positive integer string without leading zeros. It is optional and can be omitted. + +=item pass + +The OAuth 2.0 access token to be used for authentication. + +=back + +=head1 SEE ALSO + +L, +L + +=head1 AUTHORS + +Written by Aditya Garg and Julian Swagemakers. + +=head1 COPYRIGHT + +Copyright (c) 2025 Aditya Garg. + +Copyright (c) 2025 Julian Swagemakers. + +All rights reserved. This program is free software; you can redistribute +it and/or modify it under the same terms as Perl itself. +=cut diff --git a/git/usr/share/perl5/vendor_perl/Authen/SASL/Perl/PLAIN.pm b/git/usr/share/perl5/vendor_perl/Authen/SASL/Perl/PLAIN.pm new file mode 100644 index 0000000000000000000000000000000000000000..f703774e8a26498a9908bc17b068ed46af14f08d --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Authen/SASL/Perl/PLAIN.pm @@ -0,0 +1,186 @@ +# Copyright (c) 2002 Graham Barr . All rights reserved. +# This program is free software; you can redistribute it and/or +# modify it under the same terms as Perl itself. + +package Authen::SASL::Perl::PLAIN 2.2000; + +use strict; +use warnings; +use vars qw(@ISA); + +@ISA = qw(Authen::SASL::Perl); + +my %secflags = ( + noanonymous => 1, +); + +my @tokens = qw(authname user pass); + +sub _order { 1 } +sub _secflags { + shift; + grep { $secflags{$_} } @_; +} + +sub mechanism { 'PLAIN' } + +sub client_start { + my $self = shift; + + $self->{error} = undef; + $self->{need_step} = 0; + + my @parts = map { + my $v = $self->_call($_); + defined($v) ? $v : '' + } @tokens; + + join("\0", @parts); +} + +sub server_start { + my $self = shift; + my $response = shift; + my $user_cb = shift || sub {}; + + $self->{error} = undef; + return $self->set_error("No response: Credentials don't match") + unless defined $response; + + my %parts; + @parts{@tokens} = split "\0", $response, scalar @tokens; + + + # I'm not entirely sure of what I am doing + $self->{answer}{$_} = $parts{$_} for qw/authname user/; + my $error = "Credentials don't match"; + + ## checkpass + if (my $checkpass = $self->callback('checkpass')) { + my $cb = sub { + my $result = shift; + unless ($result) { + $self->set_error($error); + } + else { + $self->set_success; + } + $user_cb->(); + }; + $checkpass->($self => { %parts } => $cb ); + return; + } + + ## getsecret + elsif (my $getsecret = $self->callback('getsecret')) { + my $cb = sub { + my $good_pass = shift; + if ($good_pass && $good_pass eq ($parts{pass} || "")) { + $self->set_success; + } + else { + $self->set_error($error); + } + $user_cb->(); + }; + $getsecret->( $self, { map { $_ => $parts{$_ } } qw/user authname/ }, $cb ); + return; + } + + ## error by default + else { + $self->set_error($error); + $user_cb->(); + } +} + +1; + +__END__ + +=head1 NAME + +Authen::SASL::Perl::PLAIN - Plain Login Authentication class + +=head1 VERSION + +version 2.2000 + +=head1 SYNOPSIS + + use Authen::SASL qw(Perl); + + $sasl = Authen::SASL->new( + mechanism => 'PLAIN', + callback => { + user => $user, + pass => $pass + }, + ); + +=head1 DESCRIPTION + +This method implements the client and server part of the PLAIN SASL algorithm, +as described in RFC 2595 resp. IETF Draft draft-ietf-sasl-plain-XX.txt + +=head2 CALLBACK + +The callbacks used are: + +=head3 Client + +=over 4 + +=item authname + +The authorization id to use after successful authentication (client) + +=item user + +The username to be used for authentication (client) + +=item pass + +The user's password to be used for authentication. + +=back + +=head3 Server + +=over 4 + +=item checkpass(username, password, realm) + +returns true and false depending on the validity of the credentials passed +in arguments. + +=back + +=head1 SEE ALSO + +L, +L + +=head1 AUTHORS + +Software written by Graham Barr , +documentation written by Peter Marschall . + +Please report any bugs, or post any suggestions, to the perl-ldap mailing list + + +=head1 COPYRIGHT + +Copyright (c) 2002-2004 Graham Barr. +All rights reserved. This program is free software; you can redistribute +it and/or modify it under the same terms as Perl itself. + +Documentation Copyright (c) 2004 Peter Marschall. +All rights reserved. This documentation is distributed, +and may be redistributed, under the same terms as Perl itself. + +Server support Copyright (c) 2009 Yann Kerherve. +All rights reserved. This program is free software; you can redistribute +it and/or modify it under the same terms as Perl itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Authen/SASL/Perl/XOAUTH2.pm b/git/usr/share/perl5/vendor_perl/Authen/SASL/Perl/XOAUTH2.pm new file mode 100644 index 0000000000000000000000000000000000000000..74cc01a0dfe45bef9cbed03430d8e92d18bb44d1 --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Authen/SASL/Perl/XOAUTH2.pm @@ -0,0 +1,115 @@ +# Copyright (c) 2025 Aditya Garg +# Copyright (c) 2025 Julian Swagemakers +# All rights reserved. +# This program is free software; you can redistribute it and/or +# modify it under the same terms as Perl itself. + +package Authen::SASL::Perl::XOAUTH2 2.2000; + +use strict; +use warnings; +use vars qw(@ISA); +use JSON::PP; + +@ISA = qw(Authen::SASL::Perl); + +my %secflags = ( + noanonymous => 1, +); + +sub _order { 1 } + +sub _secflags { + shift; + scalar grep { $secflags{$_} } @_; +} + +sub mechanism { 'XOAUTH2' } + +sub client_start { + my $self = shift; + $self->{stage} = 0; + + # "user=" {User} "^Aauth=Bearer " {Access Token} "^A^A" + # https://developers.google.com/gmail/imap/xoauth2-protocol#initial_client_response + my $username = $self->_call('user'); + my $token = $self->_call('pass'); # OAuth 2.0 access token + my $auth_string = "user=$username\001auth=Bearer $token\001\001"; + return $auth_string +} + +sub client_step { + my ($self, $challenge) = @_; + my $json = JSON::PP->new; + my $payload = $json->decode( $challenge ); + $self->set_error( $payload ); + # Send dummy request on authentication failure according to rfc7628. + # https://datatracker.ietf.org/doc/html/rfc7628#section-3.2.3 + return "\001"; +} + +1; + +__END__ + +=head1 NAME + +Authen::SASL::Perl::XOAUTH2 - XOAUTH2 Authentication class + +=head1 VERSION + +version 2.2000 + +=head1 SYNOPSIS + + use Authen::SASL qw(Perl); + + $sasl = Authen::SASL->new( + mechanism => 'XOAUTH2', + callback => { + user => $user, + pass => $access_token + }, + ); + +=head1 DESCRIPTION + +This module implements the client side of the XOAUTH2 SASL mechanism, +which is used for OAuth 2.0-based authentication. + +=head2 CALLBACK + +The callbacks used are: + +=head3 Client + +=over 4 + +=item user + +The username to be used for authentication. + +=item pass + +The OAuth 2.0 access token to be used for authentication. + +=back + +=head1 SEE ALSO + +L, +L + +=head1 AUTHORS + +Written by Aditya Garg and Julian Swagemakers. + +=head1 COPYRIGHT + +Copyright (c) 2025 Aditya Garg. + +Copyright (c) 2025 Julian Swagemakers. + +All rights reserved. This program is free software; you can redistribute +it and/or modify it under the same terms as Perl itself. +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Format/Generic.pm b/git/usr/share/perl5/vendor_perl/Date/Format/Generic.pm new file mode 100644 index 0000000000000000000000000000000000000000..5fa5eea9ffdd49b4aed07376ee5dd3a80fcef4b2 --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Format/Generic.pm @@ -0,0 +1,264 @@ +## +## +## + +package Date::Format::Generic; + +use strict; +use warnings; + +our ($epoch, $tzname); +use Time::Zone; +use Time::Local; + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: Date formatting subroutines + +sub ctime +{ + my($me,$t,$tz) = @_; + $me->time2str("%a %b %e %T %Y\n", $t, $tz); +} + +sub asctime +{ + my($me,$t,$tz) = @_; + $me->strftime("%a %b %e %T %Y\n", $t, $tz); +} + +sub _subs +{ + my $fn; + $_[1] =~ s/ + %(O?[%a-zA-Z]) + / + ($_[0]->can("format_$1") || sub { $1 })->($_[0]); + /sgeox; + + $_[1]; +} + +sub strftime +{ + my($pkg,$fmt,$time); + + ($pkg,$fmt,$time,$tzname) = @_; + + my $me = ref($pkg) ? $pkg : bless []; + + if(defined $tzname) + { + $tzname = uc $tzname; + + $tzname = sprintf("%+05d",$tzname) + unless($tzname =~ /\D/); + + $epoch = timelocal(@{$time}[0..5]); + + @$me = gmtime($epoch + tz_offset($tzname)); + } + else + { + @$me = @$time; + undef $epoch; + } + + _subs($me,$fmt); +} + +sub time2str +{ + my($pkg,$fmt,$time); + + ($pkg,$fmt,$time,$tzname) = @_; + + my $me = ref($pkg) ? $pkg : bless [], $pkg; + + $epoch = $time; + + if(defined $tzname) + { + $tzname = uc $tzname; + + $tzname = sprintf("%+05d",$tzname) + unless($tzname =~ /\D/); + + $time += tz_offset($tzname); + @$me = gmtime($time); + } + else + { + @$me = localtime($time); + } + $me->[9] = $time; + _subs($me,$fmt); +} + +my(@DoW,@MoY,@DoWs,@MoYs,@AMPM,%format,@Dsuf); + +@DoW = qw(Sunday Monday Tuesday Wednesday Thursday Friday Saturday); + +@MoY = qw(January February March April May June + July August September October November December); + +@DoWs = map { substr($_,0,3) } @DoW; +@MoYs = map { substr($_,0,3) } @MoY; + +@AMPM = qw(AM PM); + +@Dsuf = (qw(th st nd rd th th th th th th)) x 3; +@Dsuf[11,12,13] = qw(th th th); +@Dsuf[30,31] = qw(th st); + +%format = ('x' => "%m/%d/%y", + 'C' => "%a %b %e %T %Z %Y", + 'X' => "%H:%M:%S", + ); + +my @locale; +my $locale = "/usr/share/lib/locale/LC_TIME/default"; +local *LOCALE; + +if(open(LOCALE,"$locale")) + { + chop(@locale = ); + close(LOCALE); + + @MoYs = @locale[0 .. 11]; + @MoY = @locale[12 .. 23]; + @DoWs = @locale[24 .. 30]; + @DoW = @locale[31 .. 37]; + @format{"X","x","C"} = @locale[38 .. 40]; + @AMPM = @locale[41 .. 42]; + } + +sub wkyr { + my($wstart, $wday, $yday) = @_; + $wday = ($wday + 7 - $wstart) % 7; + return int(($yday - $wday + 13) / 7 - 1); +} + +## +## these 6 formatting routines need to be *copied* into the language +## specific packages +## + +my @roman = ('',qw(I II III IV V VI VII VIII IX)); +sub roman { + my $n = shift; + + $n =~ s/(\d)$//; + my $r = $roman[ $1 ]; + + if($n =~ s/(\d)$//) { + (my $t = $roman[$1]) =~ tr/IVX/XLC/; + $r = $t . $r; + } + if($n =~ s/(\d)$//) { + (my $t = $roman[$1]) =~ tr/IVX/CDM/; + $r = $t . $r; + } + if($n =~ s/(\d)$//) { + (my $t = $roman[$1]) =~ tr/IVX/M../; + $r = $t . $r; + } + $r; +} + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } +sub format_P { lc($_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0]) } + +sub format_d { sprintf("%02d",$_[0]->[3]) } +sub format_e { sprintf("%2d",$_[0]->[3]) } +sub format_H { sprintf("%02d",$_[0]->[2]) } +sub format_I { sprintf("%02d",$_[0]->[2] % 12 || 12)} +sub format_j { sprintf("%03d",$_[0]->[7] + 1) } +sub format_k { sprintf("%2d",$_[0]->[2]) } +sub format_l { sprintf("%2d",$_[0]->[2] % 12 || 12)} +sub format_L { $_[0]->[4] + 1 } +sub format_m { sprintf("%02d",$_[0]->[4] + 1) } +sub format_M { sprintf("%02d",$_[0]->[1]) } +sub format_q { sprintf("%01d",int($_[0]->[4] / 3) + 1) } +sub format_s { + $epoch = timelocal(@{$_[0]}[0..5]) + unless defined $epoch; + sprintf("%d",$epoch) +} +sub format_S { sprintf("%02d",$_[0]->[0]) } +sub format_U { wkyr(0, $_[0]->[6], $_[0]->[7]) } +sub format_w { $_[0]->[6] } +sub format_W { wkyr(1, $_[0]->[6], $_[0]->[7]) } +sub format_y { sprintf("%02d",$_[0]->[5] % 100) } +sub format_Y { sprintf("%04d",$_[0]->[5] + 1900) } + +sub format_Z { + my $o = tz_local_offset($_[0]->[9]); + defined $tzname ? $tzname : uc tz_name($o, $_[0]->[8]); +} + +sub format_z { + my $t = $_[0]->[9]; + my $o = defined $tzname ? tz_offset($tzname, $t) : tz_offset(undef,$t); + sprintf("%+03d%02d", int($o / 3600), int(abs($o) % 3600) / 60); +} + +sub format_c { &format_x . " " . &format_X } +sub format_D { &format_m . "/" . &format_d . "/" . &format_y } +sub format_r { &format_I . ":" . &format_M . ":" . &format_S . " " . &format_p } +sub format_R { &format_H . ":" . &format_M } +sub format_T { &format_H . ":" . &format_M . ":" . &format_S } +sub format_t { "\t" } +sub format_n { "\n" } +sub format_o { sprintf("%2d%s",$_[0]->[3],$Dsuf[$_[0]->[3]]) } +sub format_x { my $f = $format{'x'}; _subs($_[0],$f); } +sub format_X { my $f = $format{'X'}; _subs($_[0],$f); } +sub format_C { my $f = $format{'C'}; _subs($_[0],$f); } + +sub format_Od { roman(format_d(@_)) } +sub format_Oe { roman(format_e(@_)) } +sub format_OH { roman(format_H(@_)) } +sub format_OI { roman(format_I(@_)) } +sub format_Oj { roman(format_j(@_)) } +sub format_Ok { roman(format_k(@_)) } +sub format_Ol { roman(format_l(@_)) } +sub format_Om { roman(format_m(@_)) } +sub format_OM { roman(format_M(@_)) } +sub format_Oq { roman(format_q(@_)) } +sub format_Oy { roman(format_y(@_)) } +sub format_OY { roman(format_Y(@_)) } + +sub format_G { int(($_[0]->[9] - 315993600) / 604800) } + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Format::Generic - Date formatting subroutines + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/Afar.pm b/git/usr/share/perl5/vendor_perl/Date/Language/Afar.pm new file mode 100644 index 0000000000000000000000000000000000000000..f53dfc3973cdf879233d8d0a3266f244fb2a9b96 --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/Afar.pm @@ -0,0 +1,79 @@ +## +## Afar tables +## + +package Date::Language::Afar; + +use strict; +use warnings; + +use Date::Language (); +use base 'Date::Language'; + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: Afar localization for Date::Format + +our (@DoW, @DoWs, @MoY, @MoYs, @AMPM, @Dsuf, %MoY, %DoW); + +@DoW = qw(Acaada Etleeni Talaata Arbaqa Kamiisi Gumqata Sabti); +@MoY = ( +"Qunxa Garablu", +"Kudo", +"Ciggilta Kudo", +"Agda Baxis", +"Caxah Alsa", +"Qasa Dirri", +"Qado Dirri", +"Liiqen", +"Waysu", +"Diteli", +"Ximoli", +"Kaxxa Garablu" +); +@DoWs = map { substr($_,0,3) } @DoW; +@MoYs = map { substr($_,0,3) } @MoY; +@AMPM = qw(saaku carra); + +@Dsuf = (qw(th st nd rd th th th th th th)) x 3; +@Dsuf[11,12,13] = qw(th th th); +@Dsuf[30,31] = qw(th st); + +Date::Language::_build_lookups(); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::Afar - Afar localization for Date::Format + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/Amharic.pm b/git/usr/share/perl5/vendor_perl/Date/Language/Amharic.pm new file mode 100644 index 0000000000000000000000000000000000000000..18bf34c9eb12acbad27596748821e6a0fbd025a0 --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/Amharic.pm @@ -0,0 +1,117 @@ +## +## Amharic tables +## + +package Date::Language::Amharic; + +use strict; +use warnings; + +use Date::Language (); +use base 'Date::Language'; + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: Amharic localization for Date::Format + +our (@DoW, @DoWs, @MoY, @MoYs, @AMPM, @Dsuf, %MoY, %DoW); + +if ( $] >= 5.006 ) { +@DoW = ( +"\x{12a5}\x{1211}\x{12f5}", +"\x{1230}\x{129e}", +"\x{121b}\x{12ad}\x{1230}\x{129e}", +"\x{1228}\x{1261}\x{12d5}", +"\x{1210}\x{1219}\x{1235}", +"\x{12d3}\x{122d}\x{1265}", +"\x{1245}\x{12f3}\x{121c}" +); +@MoY = ( +"\x{1303}\x{1295}\x{12e9}\x{12c8}\x{122a}", +"\x{134c}\x{1265}\x{1229}\x{12c8}\x{122a}", +"\x{121b}\x{122d}\x{127d}", +"\x{12a4}\x{1355}\x{1228}\x{120d}", +"\x{121c}\x{12ed}", +"\x{1301}\x{1295}", +"\x{1301}\x{120b}\x{12ed}", +"\x{12a6}\x{1308}\x{1235}\x{1275}", +"\x{1234}\x{1355}\x{1274}\x{121d}\x{1260}\x{122d}", +"\x{12a6}\x{12ad}\x{1270}\x{12cd}\x{1260}\x{122d}", +"\x{1296}\x{126c}\x{121d}\x{1260}\x{122d}", +"\x{12f2}\x{1234}\x{121d}\x{1260}\x{122d}" +); +@DoWs = map { substr($_,0,3) } @DoW; +@MoYs = map { substr($_,0,3) } @MoY; +@AMPM = ( "\x{1320}\x{12cb}\x{1275}", "\x{12a8}\x{1230}\x{12d3}\x{1275}" ); + +@Dsuf = ("\x{129b}" x 31); +} +else { +@DoW = ( +"እሑድ", +"ሰኞ", +"ማክሰኞ", +"ረቡዕ", +"ሐሙስ", +"ዓርብ", +"ቅዳሜ" +); +@MoY = ( +"ጃንዩወሪ", +"ፌብሩወሪ", +"ማርች", +"ኤፕረል", +"ሜይ", +"ጁን", +"ጁላይ", +"ኦገስት", +"ሴፕቴምበር", +"ኦክተውበር", +"ኖቬምበር", +"ዲሴምበር" +); +@DoWs = map { substr($_,0,9) } @DoW; +@MoYs = map { substr($_,0,9) } @MoY; +@AMPM = ( "ጠዋት", "ከሰዓት" ); + +@Dsuf = ("ኛ" x 31); +} + +Date::Language::_build_lookups(); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::Amharic - Amharic localization for Date::Format + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/Arabic.pm b/git/usr/share/perl5/vendor_perl/Date/Language/Arabic.pm new file mode 100644 index 0000000000000000000000000000000000000000..96442843bc622e6a1685af83f609df93164260be --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/Arabic.pm @@ -0,0 +1,61 @@ +package Date::Language::Arabic; + +use strict; +use warnings; +use utf8; +use Date::Language (); +use base 'Date::Language'; + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: Arabic localization for Date::Format + +our (@DoW, @DoWs, @MoY, @MoYs, @AMPM, @Dsuf, %MoY, %DoW); + +@DoW = qw(الأحد الاثنين الثلاثاء الأربعاء الخميس الجمعة السبت); +@MoY = qw(يناير فبراير مسيرة أبريل مايو يونيو يوليو أغسطس سبتمبر أكتوبر نوفمبر ديسمبر); +@DoWs = map { substr($_,0,3) } @DoW; +@MoYs = map { substr($_,0,3) } @MoY; +$MoYs[6] = 'يوليو'; +@AMPM = qw(صباحا مساءا); + +@Dsuf = ((qw(er e e e e e e e e e)) x 3, 'er'); #To be amended + +Date::Language::_build_lookups(); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::Arabic - Arabic localization for Date::Format + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/Austrian.pm b/git/usr/share/perl5/vendor_perl/Date/Language/Austrian.pm new file mode 100644 index 0000000000000000000000000000000000000000..49b2d919c0e6c59a0da8c877e22f831c1a9c8eb3 --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/Austrian.pm @@ -0,0 +1,78 @@ +## +## Austrian tables +## + +package Date::Language::Austrian; + +use strict; +use warnings; +use utf8; + +use Date::Language (); +use Date::Language::English (); + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: Austrian localization for Date::Format + +use base 'Date::Language'; + +our @MoY = qw(Jänner Feber März April Mai Juni + Juli August September Oktober November Dezember); +our @MoYs = qw(Jän Feb Mär Apr Mai Jun Jul Aug Sep Oct Nov Dez); +our @DoW = qw(Sonntag Montag Dienstag Mittwoch Donnerstag Freitag Samstag); +our @DoWs = qw(So Mo Di Mi Do Fr Sa); + + +our @AMPM = @{Date::Language::English::AMPM}; +our @Dsuf = @{Date::Language::English::Dsuf}; + +our ( %MoY, %DoW ); +Date::Language::_build_lookups(); + +# Timezone abbreviation translations (English → German, same as German locale) +our %TZ = ( + 'CET' => 'MEZ', # Mitteleuropäische Zeit + 'CEST' => 'MESZ', # Mitteleuropäische Sommerzeit + 'WET' => 'WEZ', # Westeuropäische Zeit + 'WEST' => 'WESZ', # Westeuropäische Sommerzeit + 'EET' => 'OEZ', # Osteuropäische Zeit + 'EEST' => 'OESZ', # Osteuropäische Sommerzeit +); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::Austrian - Austrian localization for Date::Format + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/Brazilian.pm b/git/usr/share/perl5/vendor_perl/Date/Language/Brazilian.pm new file mode 100644 index 0000000000000000000000000000000000000000..e502dbc8760f823881011d7164289f0d0632cb56 --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/Brazilian.pm @@ -0,0 +1,66 @@ +## +## Brazilian tables, contributed by Christian Tosta (tosta@cce.ufmg.br) +## + +package Date::Language::Brazilian; + +use strict; +use warnings; +use utf8; + +use Date::Language (); + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: Brazilian localization for Date::Format + +use base 'Date::Language'; + +our @DoW = qw(Domingo Segunda Terça Quarta Quinta Sexta Sábado); +our @MoY = qw(Janeiro Fevereiro Março Abril Maio Junho + Julho Agosto Setembro Outubro Novembro Dezembro); +our @DoWs = map { substr($_,0,3) } @DoW; +our @MoYs = map { substr($_,0,3) } @MoY; +our @AMPM = qw(AM PM); + +our @Dsuf = (qw(mo ro do ro to to to mo vo no)) x 3; + +our ( %MoY, %DoW ); +Date::Language::_build_lookups(); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::Brazilian - Brazilian localization for Date::Format + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/Bulgarian.pm b/git/usr/share/perl5/vendor_perl/Date/Language/Bulgarian.pm new file mode 100644 index 0000000000000000000000000000000000000000..55a4864bb8a74ccd96aa68544cfc11802df33091 --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/Bulgarian.pm @@ -0,0 +1,113 @@ +## +## Bulgarian tables contributed by Krasimir Berov +## + +package Date::Language::Bulgarian; + +use strict; +use warnings; +use utf8; + +use base qw(Date::Language); + +our (@DoW, @DoWs, @MoY, @MoYs, @AMPM, @Dsuf, %MoY, %DoW); + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: Bulgarian localization for Date::Format + +@DoW = qw(неделя понеделник вторник сряда четвъртък петък събота); +@MoY = qw(януари февруари март април май юни + юли август септември октомври ноември декември); +@DoWs = qw(нд пн вт ср чт пт сб); +@MoYs = map { substr($_,0,3) } @MoY; +@AMPM = qw(AM PM); + +@Dsuf = (qw(ти ви ри ти ти ти ти ми ми ти)) x 3; +@Dsuf[11,12,13] = qw(ти ти ти); +@Dsuf[30,31] = qw(ти ви); + +Date::Language::_build_lookups(); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } +sub format_o { ($_[0]->[3]<10?' ':'').$_[0]->[3].$Dsuf[$_[0]->[3]] } + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::Bulgarian - Bulgarian localization for Date::Format + +=head1 VERSION + +version 2.35 + +=head1 SYNOPSIS + + use strict; + use warnings; + use Date::Language; + local $\=$/; + my $template ='%a %b %e %T %Y (%Y-%m-%d %H:%M:%S)'; + my $time=1290883821; #or just use time(); + my @lt = localtime($time); + my %languages = qw(English GMT German EEST Bulgarian EET); + binmode(select,':utf8'); + + foreach my $l(keys %languages){ + my $lang = Date::Language->new($l); + my $zone = $languages{$l}; + print $/. "$l $zone"; + print $lang->time2str($template, $time); + print $lang->time2str($template, $time, $zone); + + print $lang->strftime($template, \@lt); + } + +=head1 DESCRIPTION + +This is Bulgarian localization for Date::Format. +It is important to note that this module source code is in utf8. +All strings which it outputs are in utf8, so it is safe to use it +currently only with English. You are left alone to try and convert +the output when using different Date::Language::* in the same application. +This should be addresed in the future. + +=head1 NAME + +Date::Language::Bulgarian - localization for Date::Format + +=head1 AUTHOR + +Krasimir Berov (berov@cpan.org) + +=head1 COPYRIGHT + +Copyright (c) 2010 Krasimir Berov. This program is free +software; you can redistribute it and/or modify it under the same terms +as Perl itself. + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/Chinese.pm b/git/usr/share/perl5/vendor_perl/Date/Language/Chinese.pm new file mode 100644 index 0000000000000000000000000000000000000000..6917f003384de236827bc5be8bc2ded6c0a2e962 --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/Chinese.pm @@ -0,0 +1,67 @@ +## +## English tables +## + +package Date::Language::Chinese; + +use strict; +use warnings; +use utf8; +use Date::Language (); + +use base qw(Date::Language); + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: Chinese localization for Date::Format + +our @DoW = qw(星期日 星期一 星期二 星期三 星期四 星期五 星期六); +our @MoY = qw(一月 二月 三月 四月 五月 六月 + 七月 八月 九月 十月 十一月 十二月); +our @DoWs = map { $_ } @DoW; +our @MoYs = map { $_ } @MoY; +our @AMPM = qw(上午 下午); + +our @Dsuf = (qw(日 日 日 日 日 日 日 日 日 日)) x 3; + +our ( %MoY, %DoW ); +Date::Language::_build_lookups(); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } + +sub format_o { sprintf("%2d%s",$_[0]->[3],"日") } + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::Chinese - Chinese localization for Date::Format + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/Chinese_GB.pm b/git/usr/share/perl5/vendor_perl/Date/Language/Chinese_GB.pm new file mode 100644 index 0000000000000000000000000000000000000000..8639b41f0ceeae809e609e71b9ae77c7cdeb05e9 --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/Chinese_GB.pm @@ -0,0 +1,94 @@ +## +## Chinese GB2312 tables (GB2312 byte encoding) +## + +package Date::Language::Chinese_GB; + +use strict; +use warnings; + +use Date::Language (); + +use base 'Date::Language'; + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: Chinese localization for Date::Format (GB2312) + +our (@DoW, @DoWs, @MoY, @MoYs, @AMPM, @Dsuf, %MoY, %DoW); + +@DoW = ( + "\xd0\xc7\xc6\xda\xc8\xd5", # 星期日 + "\xd0\xc7\xc6\xda\xd2\xbb", # 星期一 + "\xd0\xc7\xc6\xda\xb6\xfe", # 星期二 + "\xd0\xc7\xc6\xda\xc8\xfd", # 星期三 + "\xd0\xc7\xc6\xda\xcb\xc4", # 星期四 + "\xd0\xc7\xc6\xda\xce\xe5", # 星期五 + "\xd0\xc7\xc6\xda\xc1\xf9", # 星期六 +); + +@MoY = ( + "\xd2\xbb\xd4\xc2", # 一月 + "\xb6\xfe\xd4\xc2", # 二月 + "\xc8\xfd\xd4\xc2", # 三月 + "\xcb\xc4\xd4\xc2", # 四月 + "\xce\xe5\xd4\xc2", # 五月 + "\xc1\xf9\xd4\xc2", # 六月 + "\xc6\xdf\xd4\xc2", # 七月 + "\xb0\xcb\xd4\xc2", # 八月 + "\xbe\xc5\xd4\xc2", # 九月 + "\xca\xae\xd4\xc2", # 十月 + "\xca\xae\xd2\xbb\xd4\xc2", # 十一月 + "\xca\xae\xb6\xfe\xd4\xc2", # 十二月 +); + +@DoWs = map { $_ } @DoW; +@MoYs = map { $_ } @MoY; + +@AMPM = ( + "\xc9\xcf\xce\xe7", # 上午 + "\xcf\xc2\xce\xe7", # 下午 +); + +@Dsuf = ("\xc8\xd5") x 31; # 日 + +Date::Language::_build_lookups(); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } + +sub format_o { sprintf("%2d%s",$_[0]->[3],"\xc8\xd5") } # 日 + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::Chinese_GB - Chinese localization for Date::Format (GB2312) + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/Czech.pm b/git/usr/share/perl5/vendor_perl/Date/Language/Czech.pm new file mode 100644 index 0000000000000000000000000000000000000000..15accb205c577e556f6f0a4fc12c3eb28b0281d7 --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/Czech.pm @@ -0,0 +1,89 @@ +## +## Czech tables +## +## Contributed by Honza Pazdziora + +package Date::Language::Czech; + +use strict; +use warnings; +use utf8; +use Date::Language (); + +use base 'Date::Language'; + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: Czech localization for Date::Format + +our @MoY = qw(leden únor bøezen duben kvìten èerven èervenec srpen záøí + øíjen listopad prosinec); +our @MoYs = qw(led únor bøe dub kvì èvn èec srp záøí øíj lis pro); +our @MoY2 = @MoY; +for (@MoY2) + { s!en$!na! or s!ec$!ce! or s!ad$!adu! or s!or$!ora!; } + +our @DoW = qw(nedìle pondìlí úterý støeda ètvrtek pátek sobota); +our @DoWs = qw(Ne Po Út St Èt Pá So); + +our @AMPM = qw(dop. odp.); + +our ( %MoY, %DoW ); +Date::Language::_build_lookups(); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } + +sub format_d { $_[0]->[3] } +sub format_m { $_[0]->[4] + 1 } +sub format_o { $_[0]->[3] . '.' } + +sub format_Q { $MoY2[$_[0]->[4]] } + +sub time2str { + my $ref = shift; + my @a = @_; + $a[0] =~ s/(%[do]\.?\s?)%B/$1%Q/; + $ref->SUPER::time2str(@a); + } + +sub strftime { + my $ref = shift; + my @a = @_; + $a[0] =~ s/(%[do]\.?\s?)%B/$1%Q/; + $ref->SUPER::time2str(@a); + } + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::Czech - Czech localization for Date::Format + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/Danish.pm b/git/usr/share/perl5/vendor_perl/Date/Language/Danish.pm new file mode 100644 index 0000000000000000000000000000000000000000..ea57b63841d7ddf4da422d559d1997ccf3915f35 --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/Danish.pm @@ -0,0 +1,67 @@ +## +## Danish tables +## + +package Date::Language::Danish; + +use strict; +use warnings; +use utf8; +use Date::Language (); + +use base 'Date::Language'; + +use Date::Language::English (); + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: Danish localization for Date::Format + +our @MoY = qw(Januar Februar Marts April Maj Juni + Juli August September Oktober November December); +our @MoYs = qw(Jan Feb Mar Apr Maj Jun Jul Aug Sep Okt Nov Dec); +our @DoW = qw(Søndag Mandag Tirsdag Onsdag Torsdag Fredag Lørdag); +our @DoWs = qw(Søn Man Tir Ons Tor Fre Lør); + +our @AMPM = @{Date::Language::English::AMPM}; +our @Dsuf = @{Date::Language::English::Dsuf}; + +our ( %MoY, %DoW ); +Date::Language::_build_lookups(); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::Danish - Danish localization for Date::Format + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/Dutch.pm b/git/usr/share/perl5/vendor_perl/Date/Language/Dutch.pm new file mode 100644 index 0000000000000000000000000000000000000000..d31fff1c72aa6912677464033006da3e46150b69 --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/Dutch.pm @@ -0,0 +1,69 @@ +## +## Dutch tables +## Contributed by Johannes la Poutre +## + +package Date::Language::Dutch; + +use strict; +use warnings; +use Date::Language (); +use base 'Date::Language'; + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: Dutch localization for Date::Format + +our (@DoW, @DoWs, @MoY, @MoYs, @AMPM, @Dsuf, %MoY, %DoW); + +@MoY = qw(januari februari maart april mei juni juli + augustus september oktober november december); +@MoYs = map(substr($_, 0, 3), @MoY); +$MoYs[2] = 'mrt'; # mrt is more common (Frank Maas) +@DoW = map($_ . "dag", qw(zon maan dins woens donder vrij zater)); +@DoWs = map(substr($_, 0, 2), @DoW); + +# these aren't normally used... +@AMPM = qw(VM NM); +@Dsuf = ('e') x 31; + + +Date::Language::_build_lookups(); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } +sub format_o { sprintf("%2de",$_[0]->[3]) } + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::Dutch - Dutch localization for Date::Format + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/English.pm b/git/usr/share/perl5/vendor_perl/Date/Language/English.pm new file mode 100644 index 0000000000000000000000000000000000000000..77e72442f95fa445ac4787844a34de9a10ad9c96 --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/English.pm @@ -0,0 +1,66 @@ +## +## English tables +## + +package Date::Language::English; + +use strict; +use warnings; +use Date::Language (); +use base 'Date::Language'; + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: English localization for Date::Format + +our (@DoW, @DoWs, @MoY, @MoYs, @AMPM, @Dsuf, %MoY, %DoW); + +@DoW = qw(Sunday Monday Tuesday Wednesday Thursday Friday Saturday); +@MoY = qw(January February March April May June + July August September October November December); +@DoWs = map { substr($_,0,3) } @DoW; +@MoYs = map { substr($_,0,3) } @MoY; +@AMPM = qw(AM PM); + +@Dsuf = (qw(th st nd rd th th th th th th)) x 3; +@Dsuf[11,12,13] = qw(th th th); +@Dsuf[30,31] = qw(th st); + +Date::Language::_build_lookups(); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::English - English localization for Date::Format + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/Finnish.pm b/git/usr/share/perl5/vendor_perl/Date/Language/Finnish.pm new file mode 100644 index 0000000000000000000000000000000000000000..ddfaa3391cff3c30c50184ce41bfc9a86070d5b2 --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/Finnish.pm @@ -0,0 +1,74 @@ +## +## Finnish tables +## Contributed by Matthew Musgrove +## Corrected by roke +## + +package Date::Language::Finnish; + +use strict; +use warnings; +use utf8; + +use base 'Date::Language'; + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: Finnish localization for Date::Format +use Date::Language (); + +# In Finnish, the names of the months and days are only capitalized at the beginning of sentences. +our @MoY = map($_ . "kuu", qw(tammi helmi maalis huhti touko kesä heinä elo syys loka marras joulu)); +our @DoW = qw(sunnuntai maanantai tiistai keskiviikko torstai perjantai lauantai); + +# it is not customary to use abbreviated names of months or days +# per Graham's suggestion: +our @MoYs = @MoY; +our @DoWs = @DoW; + +# the short form of ordinals +our @Dsuf = ('.') x 31; + +# doesn't look like this is normally used... +our @AMPM = qw(ap ip); + +our ( %MoY, %DoW ); +Date::Language::_build_lookups(); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } +sub format_o { sprintf("%2de",$_[0]->[3]) } + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::Finnish - Finnish localization for Date::Format + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/French.pm b/git/usr/share/perl5/vendor_perl/Date/Language/French.pm new file mode 100644 index 0000000000000000000000000000000000000000..2858cf900add8317a40f19da58b8f52222cc6885 --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/French.pm @@ -0,0 +1,67 @@ +## +## French tables, contributed by Emmanuel Bataille (bem@residents.frmug.org) +## + +package Date::Language::French; + +use strict; +use warnings; +use utf8; +use Date::Language (); + +use base 'Date::Language'; + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: French localization for Date::Format + +our @DoW = qw(dimanche lundi mardi mercredi jeudi vendredi samedi); +our @MoY = qw(janvier février mars avril mai juin + juillet août septembre octobre novembre décembre); +our @DoWs = map { substr($_,0,3) } @DoW; +our @MoYs = map { substr($_,0,3) } @MoY; +$MoYs[6] = 'jul'; + +our @AMPM = qw(AM PM); +our @Dsuf = ('e', 'er', ('e') x 30); + +our ( %MoY, %DoW ); +Date::Language::_build_lookups(); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } +sub format_o { sprintf("%2d%s",$_[0]->[3],$Dsuf[$_[0]->[3]]) } + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::French - French localization for Date::Format + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/Gedeo.pm b/git/usr/share/perl5/vendor_perl/Date/Language/Gedeo.pm new file mode 100644 index 0000000000000000000000000000000000000000..371f9bbb4a09e88d2a6b1a385e7fdacb49a5d7bf --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/Gedeo.pm @@ -0,0 +1,81 @@ +## +## Gedeo tables +## + +package Date::Language::Gedeo; + +use strict; +use warnings; + +use Date::Language (); +use base 'Date::Language'; + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: Gedeo localization for Date::Format + +our (@DoW, @DoWs, @MoY, @MoYs, @AMPM, @Dsuf, %MoY, %DoW); + +@DoW = qw( Sanbbattaa Sanno Masano Roobe Hamusse Arbe Qiddamme); +@MoY = ( +"Oritto", +"Birre'a", +"Onkkollessa", +"Saddasa", +"Arrasa", +"Qammo", +"Ella", +"Waacibajje", +"Canissa", +"Addolessa", +"Bittitotessa", +"Hegeya" +); +@DoWs = map { substr($_,0,3) } @DoW; +$DoWs[0] = "Snb"; +$DoWs[1] = "Sno"; +@MoYs = map { substr($_,0,3) } @MoY; +@AMPM = qw(gorsa warreti-udumma); + +@Dsuf = (qw(th st nd rd th th th th th th)) x 3; +@Dsuf[11,12,13] = qw(th th th); +@Dsuf[30,31] = qw(th st); + +Date::Language::_build_lookups(); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::Gedeo - Gedeo localization for Date::Format + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/German.pm b/git/usr/share/perl5/vendor_perl/Date/Language/German.pm new file mode 100644 index 0000000000000000000000000000000000000000..9dec08fb30f329dc77e25827669caf71024640ea --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/German.pm @@ -0,0 +1,77 @@ +## +## German tables +## + +package Date::Language::German; + +use strict; +use warnings; +use utf8; + +use Date::Language::English (); + +use base 'Date::Language'; + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: German localization for Date::Format + +our @MoY = qw(Januar Februar März April Mai Juni + Juli August September Oktober November Dezember); +our @MoYs = qw(Jan Feb Mär Apr Mai Jun Jul Aug Sep Okt Nov Dez); +our @DoW = qw(Sonntag Montag Dienstag Mittwoch Donnerstag Freitag Samstag); +our @DoWs = qw(So Mo Di Mi Do Fr Sa); + +our @AMPM = @{Date::Language::English::AMPM}; +our @Dsuf = @{Date::Language::English::Dsuf}; + +our ( %MoY, %DoW ); +Date::Language::_build_lookups(); + +# Timezone abbreviation translations (English → German) +our %TZ = ( + 'CET' => 'MEZ', # Mitteleuropäische Zeit + 'CEST' => 'MESZ', # Mitteleuropäische Sommerzeit + 'WET' => 'WEZ', # Westeuropäische Zeit + 'WEST' => 'WESZ', # Westeuropäische Sommerzeit + 'EET' => 'OEZ', # Osteuropäische Zeit + 'EEST' => 'OESZ', # Osteuropäische Sommerzeit +); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } +sub format_o { sprintf("%2d.",$_[0]->[3]) } + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::German - German localization for Date::Format + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/Greek.pm b/git/usr/share/perl5/vendor_perl/Date/Language/Greek.pm new file mode 100644 index 0000000000000000000000000000000000000000..e04f872abb5c71c493f28859eefbe335728751ae --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/Greek.pm @@ -0,0 +1,119 @@ +## +## Greek tables +## +## Traditional date format is: DoW DD{eta} MoY Year (%A %o %B %Y) +## +## Matthew Musgrove +## Translations graciously provided by Menelaos Stamatelos +## This module returns unicode (utf8) encoded characters. You will need to +## take the necessary steps for this to display correctly. +## + +package Date::Language::Greek; + +use strict; +use warnings; +use utf8; + +use Date::Language (); + +use base 'Date::Language'; + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: Greek localization for Date::Format + +our (@DoW, @DoWs, @MoY, @MoYs, @AMPM, @Dsuf, %MoY, %DoW); + +@DoW = ( +"Κυριακή", +"Δευτέρα", +"Τρίτη", +"Τετάρτη", +"Πέμπτη", +"Παρασκευή", +"Σάββατο", +); + +@MoY = ( +"Ιανουαρίου", +"Φεβρουαρίου", +"Μαρτίου", +"Απριλίου", +"Μαΐου", +"Ιουνίου", +"Ιουλίου", +"Αυγούστου", +"Σεπτεμτου", +"Οκτωβρίου", +"Νοεμβρίου", +"Δεκεμβρίου", +); + +@DoWs = ( +"Κυ", +"Δε", +"Τρ", +"Τε", +"Πε", +"Πα", +"Σα", +); +@MoYs = ( +"Ιαν", +"Φε", +"Μαρ", +"Απρ", +"Μα", +"Ιουν", +"Ιουλ", +"Αυγ", +"Σεπ", +"Οκ", +"Νο", +"Δε", +); + +@AMPM = ("πμ", "μμ"); + +@Dsuf = ("η" x 31); + +Date::Language::_build_lookups(); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_o { sprintf("%2d%s",$_[0]->[3],"η") } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::Greek - Greek localization for Date::Format + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/Hungarian.pm b/git/usr/share/perl5/vendor_perl/Date/Language/Hungarian.pm new file mode 100644 index 0000000000000000000000000000000000000000..8771fde375fc66e492cb18f6029f822834f4924a --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/Hungarian.pm @@ -0,0 +1,116 @@ +## +## Hungarian tables based on English +## +# +# This is a just-because-I-stumbled-across-it +# -and-my-wife-is-Hungarian release: if Graham or +# someone adds to docs to Date::Format, I'd be +# glad to correct bugs and extend as needed. +# + +package Date::Language::Hungarian; + + +use strict; +use warnings; +use utf8; +use Date::Language (); + +use base 'Date::Language'; + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: Hungarian localization for Date::Format + +our @DoW = qw(Vasárnap Hétfő Kedd Szerda Csütörtök Péntek Szombat); +our @MoY = qw(Január Február Március Április Május Június + Július Augusztus Szeptember Október November December); +our @DoWs = map { substr($_,0,3) } @DoW; +our @MoYs = map { substr($_,0,3) } @MoY; +our @AMPM = qw(DE. DU.); + +# There is no 'th or 'nd in Hungarian, just a dot +our @Dsuf = (".") x 31; + +our ( %MoY, %DoW ); +Date::Language::_build_lookups(); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } +sub format_P { lc($_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0]) } +sub format_o { $_[0]->[3].'.' } + +sub format_D { &format_y . "." . &format_m . "." . &format_d } + +sub format_y { sprintf("%02d",$_[0]->[5] % 100) } +sub format_d { sprintf("%02d",$_[0]->[3]) } +sub format_m { sprintf("%02d",$_[0]->[4] + 1) } + + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::Hungarian - Hungarian localization for Date::Format + +=head1 VERSION + +version 2.35 + +=head1 SYNOPSIS + + my $lang = Date::Language->new('Hungarian'); + print $lang->time2str("%a %b %e %T %Y", time); + + my @lt = localtime(time); + my $template = "%a %b %e %T %Y"; + print $lang->time2str($template, time); + print $lang->strftime($template, @lt); + + my $zone = "EST"; + print $lang->time2str($template, time, $zone); + print $lang->strftime($template, @lt, $zone); + + print $lang->ctime(time); + print $lang->asctime(@lt); + + print $lang->ctime(time, $zone); + print $lang->asctime(@lt, $zone); + +See L. + +=head1 NAME + +Date::Language::Hungarian - Magyar format for Date::Format + +=head1 AUTHOR + +Paula Goddard (paula -at- paulacska -dot- com) + +=head1 LICENCE + +Made available under the same terms as Perl itself. + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/Icelandic.pm b/git/usr/share/perl5/vendor_perl/Date/Language/Icelandic.pm new file mode 100644 index 0000000000000000000000000000000000000000..a78ef26f149e38fe82dc2702003d82a956004e13 --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/Icelandic.pm @@ -0,0 +1,67 @@ +## +## Icelandic tables +## + +package Date::Language::Icelandic; + +use strict; +use warnings; +use utf8; +use Date::Language (); + +use base 'Date::Language'; + +use Date::Language::English (); + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: Icelandic localization for Date::Format + +our @MoY = qw(Janúar Febrúar Mars Apríl Maí Júni + Júli Ágúst September Október Nóvember Desember); +our @MoYs = qw(Jan Feb Mar Apr Maí Jún Júl Ágú Sep Okt Nóv Des); +our @DoW = qw(Sunnudagur Mánudagur Þriðjudagur Miðvikudagur Fimmtudagur Föstudagur Laugardagur); +our @DoWs = qw(Sun Mán Þri Mið Fim Fös Lau); + +our @AMPM = @{Date::Language::English::AMPM}; +our @Dsuf = @{Date::Language::English::Dsuf}; + +our ( %MoY, %DoW ); +Date::Language::_build_lookups(); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::Icelandic - Icelandic localization for Date::Format + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/Italian.pm b/git/usr/share/perl5/vendor_perl/Date/Language/Italian.pm new file mode 100644 index 0000000000000000000000000000000000000000..1058e52cd7e02639dc7e5f70a43965f6194e221b --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/Italian.pm @@ -0,0 +1,65 @@ +## +## Italian tables +## + +package Date::Language::Italian; + +use strict; +use warnings; +use Date::Language (); +use base 'Date::Language'; + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: Italian localization for Date::Format + +our (@DoW, @DoWs, @MoY, @MoYs, @AMPM, @Dsuf, %MoY, %DoW); + +@MoY = qw(Gennaio Febbraio Marzo Aprile Maggio Giugno + Luglio Agosto Settembre Ottobre Novembre Dicembre); +@MoYs = qw(Gen Feb Mar Apr Mag Giu Lug Ago Set Ott Nov Dic); +@DoW = qw(Domenica Lunedi Martedi Mercoledi Giovedi Venerdi Sabato); +@DoWs = qw(Dom Lun Mar Mer Gio Ven Sab); + +use Date::Language::English (); +@AMPM = @{Date::Language::English::AMPM}; +@Dsuf = @{Date::Language::English::Dsuf}; + +Date::Language::_build_lookups(); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::Italian - Italian localization for Date::Format + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/Norwegian.pm b/git/usr/share/perl5/vendor_perl/Date/Language/Norwegian.pm new file mode 100644 index 0000000000000000000000000000000000000000..21488a63c9e98933cca2bb55770050bb7be5aa7f --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/Norwegian.pm @@ -0,0 +1,66 @@ +## +## Norwegian tables +## + +package Date::Language::Norwegian; + +use strict; +use warnings; +use utf8; +use Date::Language (); + +use base 'Date::Language'; +use Date::Language::English (); + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: Norwegian localization for Date::Format + +our @MoY = qw(Januar Februar Mars April Mai Juni + Juli August September Oktober November Desember); +our @MoYs = qw(Jan Feb Mar Apr Mai Jun Jul Aug Sep Okt Nov Des); +our @DoW = qw(Søndag Mandag Tirsdag Onsdag Torsdag Fredag Lørdag); +our @DoWs = qw(Søn Man Tir Ons Tor Fre Lør); + +our @AMPM = @{Date::Language::English::AMPM}; +our @Dsuf = @{Date::Language::English::Dsuf}; + +our ( %MoY, %DoW ); +Date::Language::_build_lookups(); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::Norwegian - Norwegian localization for Date::Format + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/Occitan.pm b/git/usr/share/perl5/vendor_perl/Date/Language/Occitan.pm new file mode 100644 index 0000000000000000000000000000000000000000..19f59387050a3dcca92297c71bbca463d6d0e217 --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/Occitan.pm @@ -0,0 +1,65 @@ +## +## Occitan tables, contributed by Quentn PAGÈS +## + +package Date::Language::Occitan; + +use strict; +use warnings; +use Date::Language (); +use base 'Date::Language'; + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: Occitan localization for Date::Format + +our (@DoW, @DoWs, @MoY, @MoYs, @AMPM, @Dsuf, %MoY, %DoW); + +@DoW = qw(dimenge diluns dimars dimècres dijòus divendres dissabte); +@MoY = qw(genièr febrièr març abrial mai junh + julhet agost setembre octòbre novembre decembre); +@DoWs = map { substr($_,0,3) } @DoW; +@MoYs = map { substr($_,0,3) } @MoY; +$MoYs[6] = 'jul'; +@AMPM = qw(AM PM); + +@Dsuf = ((qw(er e e e e e e e e e)) x 3, 'er'); + +Date::Language::_build_lookups(); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::Occitan - Occitan localization for Date::Format + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/Oromo.pm b/git/usr/share/perl5/vendor_perl/Date/Language/Oromo.pm new file mode 100644 index 0000000000000000000000000000000000000000..562c6c33b9e6cd9eead58a4145aaf55c7878d1e6 --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/Oromo.pm @@ -0,0 +1,67 @@ +## +## Oromo tables +## + +package Date::Language::Oromo; + +use strict; +use warnings; + +use Date::Language (); +use base 'Date::Language'; + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: Oromo localization for Date::Format + +our (@DoW, @DoWs, @MoY, @MoYs, @AMPM, @Dsuf, %MoY, %DoW); + +@DoW = qw(Dilbata Wiixata Qibxata Roobii Kamiisa Jimaata Sanbata); +@MoY = qw(Amajjii Guraandhala Bitooteessa Elba Caamsa Waxabajjii + Adooleessa Hagayya Fuulbana Onkololeessa Sadaasa Muddee); +@DoWs = map { substr($_,0,3) } @DoW; +@MoYs = map { substr($_,0,3) } @MoY; +@AMPM = qw(WD WB); + +@Dsuf = (qw(th st nd rd th th th th th th)) x 3; +@Dsuf[11,12,13] = qw(th th th); +@Dsuf[30,31] = qw(th st); + +Date::Language::_build_lookups(); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::Oromo - Oromo localization for Date::Format + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/Portuguese.pm b/git/usr/share/perl5/vendor_perl/Date/Language/Portuguese.pm new file mode 100644 index 0000000000000000000000000000000000000000..40a3c56bad0d5ff1ac77a8e3c2f3ad6ff7325acc --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/Portuguese.pm @@ -0,0 +1,67 @@ +## +## Portuguese tables +## + +package Date::Language::Portuguese; + +use strict; +use warnings; +use utf8; + +use Date::Language (); + +use base 'Date::Language'; + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: Portuguese localization for Date::Format + +our @DoW = qw(domingo segunda-feira terça-feira quarta-feira quinta-feira sexta-feira sábado); +our @MoY = qw(janeiro fevereiro março abril maio junho + julho agosto setembro outubro novembro dezembro); +our @DoWs = map { substr($_,0,3) } @DoW; +our @MoYs = map { substr($_,0,3) } @MoY; +our @AMPM = qw(AM PM); + +our @Dsuf = ('º') x 32; + +our ( %MoY, %DoW ); +Date::Language::_build_lookups(); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_o { sprintf("%2d%s",$_[0]->[3],$Dsuf[$_[0]->[3]]) } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::Portuguese - Portuguese localization for Date::Format + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/Romanian.pm b/git/usr/share/perl5/vendor_perl/Date/Language/Romanian.pm new file mode 100644 index 0000000000000000000000000000000000000000..bbdef470dbee8ac33cf1836e3243543f213d57ae --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/Romanian.pm @@ -0,0 +1,67 @@ +## +## Italian tables +## + +package Date::Language::Romanian; + +use strict; +use warnings; + +use Date::Language (); +use base 'Date::Language'; + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: Romanian localization for Date::Format + +our (@DoW, @DoWs, @MoY, @MoYs, @AMPM, @Dsuf, %MoY, %DoW); + +@MoY = qw(ianuarie februarie martie aprilie mai iunie + iulie august septembrie octombrie noembrie decembrie); +@DoW = qw(duminica luni marti miercuri joi vineri sambata); +@DoWs = map { substr($_,0,3) } @DoW; +@MoYs = map { substr($_,0,3) } @MoY; + +@AMPM = qw(AM PM); + +@Dsuf = ('') x 31; + + +Date::Language::_build_lookups(); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::Romanian - Romanian localization for Date::Format + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/Russian.pm b/git/usr/share/perl5/vendor_perl/Date/Language/Russian.pm new file mode 100644 index 0000000000000000000000000000000000000000..54a16de15be98314b3768ca013724094c5f41e23 --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/Russian.pm @@ -0,0 +1,151 @@ +## +## Russian tables (KOI8-R byte encoding) +## +## Contributed by Danil Pismenny + +package Date::Language::Russian; + +use strict; +use warnings; + +use Date::Language (); + +use base 'Date::Language'; + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: Russian localization for Date::Format (KOI8-R) + +our (@DoW, @DoWs, @MoY, @MoYs, @MoY2, @DoWs2, @AMPM, @Dsuf, %MoY, %DoW); + +@MoY = ( + "\xf1\xce\xd7\xc1\xd2\xd1", # Января + "\xe6\xc5\xd7\xd2\xc1\xcc\xd1", # Февраля + "\xed\xc1\xd2\xd4\xc1", # Марта + "\xe1\xd0\xd2\xc5\xcc\xd1", # Апреля + "\xed\xc1\xd1", # Мая + "\xe9\xc0\xce\xd1", # Июня + "\xe9\xc0\xcc\xd1", # Июля + "\xe1\xd7\xc7\xd5\xd3\xd4\xc1", # Августа + "\xf3\xc5\xce\xd4\xd1\xc2\xd2\xd1", # Сентября + "\xef\xcb\xd4\xd1\xc2\xd2\xd1", # Октября + "\xee\xcf\xd1\xc2\xd2\xd1", # Ноября + "\xe4\xc5\xcb\xc1\xc2\xd2\xd1", # Декабря +); + +@MoY2 = ( + "\xf1\xce\xd7\xc1\xd2\xd8", # Январь + "\xe6\xc5\xd7\xd2\xc1\xcc\xd8", # Февраль + "\xed\xc1\xd2\xd4", # Март + "\xe1\xd0\xd2\xc5\xcc\xd8", # Апрель + "\xed\xc1\xca", # Май + "\xe9\xc0\xce\xd8", # Июнь + "\xe9\xc0\xcc\xd8", # Июль + "\xe1\xd7\xc7\xd5\xd3\xd4", # Август + "\xf3\xc5\xce\xd4\xd1\xc2\xd2\xd8", # Сентябрь + "\xef\xcb\xd4\xd1\xc2\xd2\xd8", # Октябрь + "\xee\xcf\xd1\xc2\xd2\xd8", # Ноябрь + "\xe4\xc5\xcb\xc1\xc2\xd2\xd8", # Декабрь +); + +@MoYs = ( + "\xf1\xce\xd7", # Янв + "\xe6\xc5\xd7", # Фев + "\xed\xd2\xd4", # Мрт + "\xe1\xd0\xd2", # Апр + "\xed\xc1\xca", # Май + "\xe9\xc0\xce", # Июн + "\xe9\xc0\xcc", # Июл + "\xe1\xd7\xc7", # Авг + "\xf3\xc5\xce", # Сен + "\xef\xcb\xd4", # Окт + "\xee\xcf\xd1", # Ноя + "\xe4\xc5\xcb", # Дек +); + +@DoW = ( + "\xf0\xcf\xce\xc5\xc4\xc5\xcc\xd8\xce\xc9\xcb", # Понедельник + "\xf7\xd4\xcf\xd2\xce\xc9\xcb", # Вторник + "\xf3\xd2\xc5\xc4\xc1", # Среда + "\xfe\xc5\xd4\xd7\xc5\xd2\xc7", # Четверг + "\xf0\xd1\xd4\xce\xc9\xc3\xc1", # Пятница + "\xf3\xd5\xc2\xc2\xcf\xd4\xc1", # Суббота + "\xf7\xcf\xd3\xcb\xd2\xc5\xd3\xc5\xce\xd8\xc5", # Воскресенье +); + +@DoWs = ( + "\xf0\xce", # Пн + "\xf7\xd4", # Вт + "\xf3\xd2", # Ср + "\xfe\xd4", # Чт + "\xf0\xd4", # Пт + "\xf3\xc2", # Сб + "\xf7\xd3", # Вс +); + +@DoWs2 = ( + "\xf0\xce\xc4", # Пнд + "\xf7\xd4\xd2", # Втр + "\xf3\xd2\xc4", # Срд + "\xfe\xd4\xd7", # Чтв + "\xf0\xd4\xce", # Птн + "\xf3\xc2\xd4", # Сбт + "\xf7\xd3\xcb", # Вск +); + +@AMPM = ( + "\xc4\xd0", # дп + "\xd0\xd0", # пп +); + +Date::Language::_build_lookups(); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } + +sub format_d { $_[0]->[3] } +sub format_m { $_[0]->[4] + 1 } +sub format_o { $_[0]->[3] . '.' } + +sub format_Q { $MoY2[$_[0]->[4]] } + +sub str2time { + my ($self,$value) = @_; + map {$value=~s/(\s|^)$DoWs2[$_](\s)/$DoWs[$_]$2/ig} (0..6); + $value=~s/(\s+|^)\xed\xc1\xd2(\s+)/$1\xed\xd2\xd4$2/; + return $self->SUPER::str2time($value); +} + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::Russian - Russian localization for Date::Format (KOI8-R) + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/Russian_cp1251.pm b/git/usr/share/perl5/vendor_perl/Date/Language/Russian_cp1251.pm new file mode 100644 index 0000000000000000000000000000000000000000..9c1315b8b5de7591295b1be55d7eb7b9d63bf1b8 --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/Russian_cp1251.pm @@ -0,0 +1,98 @@ +## +## Russian cp1251 (CP1251 byte encoding) +## + +package Date::Language::Russian_cp1251; + +use strict; +use warnings; + +use Date::Language (); + +use base 'Date::Language'; + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: Russian localization for Date::Format (CP1251) + +our (@DoW, @DoWs, @MoY, @MoYs, @AMPM, @Dsuf, %MoY, %DoW); + +@DoW = ( + "\xc2\xee\xf1\xea\xf0\xe5\xf1\xe5\xed\xfc\xe5", # Воскресенье + "\xcf\xee\xed\xe5\xe4\xe5\xeb\xfc\xed\xe8\xea", # Понедельник + "\xc2\xf2\xee\xf0\xed\xe8\xea", # Вторник + "\xd1\xf0\xe5\xe4\xe0", # Среда + "\xd7\xe5\xf2\xe2\xe5\xf0\xe3", # Четверг + "\xcf\xff\xf2\xed\xe8\xf6\xe0", # Пятница + "\xd1\xf3\xe1\xe1\xee\xf2\xe0", # Суббота +); + +@MoY = ( + "\xdf\xed\xe2\xe0\xf0\xfc", # Январь + "\xd4\xe5\xe2\xf0\xe0\xeb\xfc", # Февраль + "\xcc\xe0\xf0\xf2", # Март + "\xc0\xef\xf0\xe5\xeb\xfc", # Апрель + "\xcc\xe0\xe9", # Май + "\xc8\xfe\xed\xfc", # Июнь + "\xc8\xfe\xeb\xfc", # Июль + "\xc0\xe2\xe3\xf3\xf1\xf2", # Август + "\xd1\xe5\xed\xf2\xff\xe1\xf0\xfc", # Сентябрь + "\xce\xea\xf2\xff\xe1\xf0\xfc", # Октябрь + "\xcd\xee\xff\xe1\xf0\xfc", # Ноябрь + "\xc4\xe5\xea\xe0\xe1\xf0\xfc", # Декабрь +); + +@DoWs = ( + "\xc2\xf1\xea", # Вск + "\xcf\xed\xe4", # Пнд + "\xc2\xf2\xf0", # Втр + "\xd1\xf0\xe4", # Срд + "\xd7\xf2\xe2", # Чтв + "\xcf\xf2\xed", # Птн + "\xd1\xe1\xf2", # Сбт +); + +@MoYs = map { substr($_,0,3) } @MoY; +@AMPM = qw(AM PM); + +@Dsuf = ('e') x 31; + +Date::Language::_build_lookups(); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } +sub format_o { sprintf("%2de",$_[0]->[3]) } + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::Russian_cp1251 - Russian localization for Date::Format (CP1251) + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/Russian_koi8r.pm b/git/usr/share/perl5/vendor_perl/Date/Language/Russian_koi8r.pm new file mode 100644 index 0000000000000000000000000000000000000000..9ad307440052dab16a4c329b7930fa104e5e75b7 --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/Russian_koi8r.pm @@ -0,0 +1,98 @@ +## +## Russian koi8r (KOI8-R byte encoding) +## + +package Date::Language::Russian_koi8r; + +use strict; +use warnings; + +use Date::Language (); + +use base 'Date::Language'; + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: Russian localization for Date::Format (KOI8-R variant) + +our (@DoW, @DoWs, @MoY, @MoYs, @AMPM, @Dsuf, %MoY, %DoW); + +@DoW = ( + "\xf7\xcf\xd3\xcb\xd2\xc5\xd3\xc5\xce\xd8\xc5", # Воскресенье + "\xf0\xcf\xce\xc5\xc4\xc5\xcc\xd8\xce\xc9\xcb", # Понедельник + "\xf7\xd4\xcf\xd2\xce\xc9\xcb", # Вторник + "\xf3\xd2\xc5\xc4\xc1", # Среда + "\xfe\xc5\xd4\xd7\xc5\xd2\xc7", # Четверг + "\xf0\xd1\xd4\xce\xc9\xc3\xc1", # Пятница + "\xf3\xd5\xc2\xc2\xcf\xd4\xc1", # Суббота +); + +@MoY = ( + "\xf1\xce\xd7\xc1\xd2\xd8", # Январь + "\xe6\xc5\xd7\xd2\xc1\xcc\xd8", # Февраль + "\xed\xc1\xd2\xd4", # Март + "\xe1\xd0\xd2\xc5\xcc\xd8", # Апрель + "\xed\xc1\xca", # Май + "\xe9\xc0\xce\xd8", # Июнь + "\xe9\xc0\xcc\xd8", # Июль + "\xe1\xd7\xc7\xd5\xd3\xd4", # Август + "\xf3\xc5\xce\xd4\xd1\xc2\xd2\xd8", # Сентябрь + "\xef\xcb\xd4\xd1\xc2\xd2\xd8", # Октябрь + "\xee\xcf\xd1\xc2\xd2\xd8", # Ноябрь + "\xe4\xc5\xcb\xc1\xc2\xd2\xd8", # Декабрь +); + +@DoWs = ( + "\xf7\xd3\xcb", # Вск + "\xf0\xce\xc4", # Пнд + "\xf7\xd4\xd2", # Втр + "\xf3\xd2\xc4", # Срд + "\xfe\xd4\xd7", # Чтв + "\xf0\xd4\xce", # Птн + "\xf3\xc2\xd4", # Сбт +); + +@MoYs = map { substr($_,0,3) } @MoY; +@AMPM = qw(AM PM); + +@Dsuf = ('e') x 31; + +Date::Language::_build_lookups(); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } +sub format_o { sprintf("%2de",$_[0]->[3]) } + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::Russian_koi8r - Russian localization for Date::Format (KOI8-R variant) + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/Sidama.pm b/git/usr/share/perl5/vendor_perl/Date/Language/Sidama.pm new file mode 100644 index 0000000000000000000000000000000000000000..e457c8f2afac882ca6a3b784c67f2ef117d9bd94 --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/Sidama.pm @@ -0,0 +1,67 @@ +## +## Sidama tables +## + +package Date::Language::Sidama; + +use strict; +use warnings; + +use Date::Language (); +use base 'Date::Language'; + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: Sidama localization for Date::Format + +our (@DoW, @DoWs, @MoY, @MoYs, @AMPM, @Dsuf, %MoY, %DoW); + +@DoW = qw(Sambata Sanyo Maakisanyo Roowe Hamuse Arbe Qidaame); +@MoY = qw(January February March April May June + July August September October November December); +@DoWs = map { substr($_,0,3) } @DoW; +@MoYs = map { substr($_,0,3) } @MoY; +@AMPM = qw(soodo hawwaro); + +@Dsuf = (qw(th st nd rd th th th th th th)) x 3; +@Dsuf[11,12,13] = qw(th th th); +@Dsuf[30,31] = qw(th st); + +Date::Language::_build_lookups(); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::Sidama - Sidama localization for Date::Format + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/Somali.pm b/git/usr/share/perl5/vendor_perl/Date/Language/Somali.pm new file mode 100644 index 0000000000000000000000000000000000000000..61b7b9eecab9adbd77c746cf66b5206ef47c759f --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/Somali.pm @@ -0,0 +1,92 @@ +## +## Somali tables +## + +package Date::Language::Somali; + +use strict; +use warnings; + +use Date::Language (); +use base 'Date::Language'; + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: Somali localization for Date::Format + +our (@DoW, @DoWs, @MoY, @MoYs, @AMPM, @Dsuf, %MoY, %DoW); + +@DoW = qw(Axad Isniin Salaaso Arbaco Khamiis Jimco Sabti); +@MoY = ( +"Bisha Koobaad", +"Bisha Labaad", +"Bisha Saddexaad", +"Bisha Afraad", +"Bisha Shanaad", +"Bisha Lixaad", +"Bisha Todobaad", +"Bisha Sideedaad", +"Bisha Sagaalaad", +"Bisha Tobnaad", +"Bisha Kow iyo Tobnaad", +"Bisha Laba iyo Tobnaad" +); +@DoWs = map { substr($_,0,3) } @DoW; +@MoYs = ( +"Kob", +"Lab", +"Sad", +"Afr", +"Sha", +"Lix", +"Tod", +"Sid", +"Sag", +"Tob", +"KIT", +"LIT" +); +@AMPM = qw(SN GN); + +@Dsuf = (qw(th st nd rd th th th th th th)) x 3; +@Dsuf[11,12,13] = qw(th th th); +@Dsuf[30,31] = qw(th st); + +Date::Language::_build_lookups(); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::Somali - Somali localization for Date::Format + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/Spanish.pm b/git/usr/share/perl5/vendor_perl/Date/Language/Spanish.pm new file mode 100644 index 0000000000000000000000000000000000000000..26ff9beb3130840cc66a954ad880b1d6f7f7e1c0 --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/Spanish.pm @@ -0,0 +1,65 @@ +## +## Spanish tables +## + +package Date::Language::Spanish; + +use strict; +use warnings; +use utf8; +use Date::Language (); + +use base 'Date::Language'; + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: Spanish localization for Date::Format + +our @DoW = qw(domingo lunes martes miércoles jueves viernes sábado); +our @MoY = qw(enero febrero marzo abril mayo junio + julio agosto septiembre octubre noviembre diciembre); +our @DoWs = map { substr($_,0,3) } @DoW; +our @MoYs = map { substr($_,0,3) } @MoY; +our @AMPM = qw(AM PM); + +our @Dsuf = ((qw(ro do ro to to to mo vo no mo)) x 3, 'ro'); + +our ( %MoY, %DoW ); +Date::Language::_build_lookups(); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::Spanish - Spanish localization for Date::Format + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/Swedish.pm b/git/usr/share/perl5/vendor_perl/Date/Language/Swedish.pm new file mode 100644 index 0000000000000000000000000000000000000000..29e6a46f10c2570edb0b88cdeec049685f518a81 --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/Swedish.pm @@ -0,0 +1,67 @@ +## +## Swedish tables +## Contributed by Matthew Musgrove +## Corrected by dempa +## + +package Date::Language::Swedish; + +use strict; +use warnings; +use base 'Date::Language'; +use Date::Language::English (); + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: Swedish localization for Date::Format + +our @MoY = qw(januari februari mars april maj juni juli augusti september oktober november december); +our @MoYs = map { substr($_,0,3) } @MoY; +our @DoW = map($_ . "dagen", qw(sön mån tis ons tors fre lör)); +our @DoWs = map { substr($_,0,2) } @DoW; + +# the ordinals are not typically used in modern times +our @Dsuf = ('a' x 2, 'e' x 29); + +our @AMPM = @{Date::Language::English::AMPM}; + +our ( %MoY, %DoW ); +Date::Language::_build_lookups(); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } +sub format_o { sprintf("%2de",$_[0]->[3]) } + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::Swedish - Swedish localization for Date::Format + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/Tigrinya.pm b/git/usr/share/perl5/vendor_perl/Date/Language/Tigrinya.pm new file mode 100644 index 0000000000000000000000000000000000000000..4b29696878e8753799cf2f3c9d754ee3e5a175a6 --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/Tigrinya.pm @@ -0,0 +1,88 @@ +## +## Tigrinya tables +## + +package Date::Language::Tigrinya; + +use strict; +use warnings; + +use Date::Language (); +use base 'Date::Language'; + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: Tigrinya localization for Date::Format + +our (@DoW, @DoWs, @MoY, @MoYs, @AMPM, @Dsuf, %MoY, %DoW); + +@DoW = ( +"\x{1230}\x{1295}\x{1260}\x{1275}", +"\x{1230}\x{1291}\x{12ed}", +"\x{1230}\x{1209}\x{1235}", +"\x{1228}\x{1261}\x{12d5}", +"\x{1213}\x{1219}\x{1235}", +"\x{12d3}\x{122d}\x{1262}", +"\x{1240}\x{12f3}\x{121d}" +); +@MoY = ( +"\x{1303}\x{1295}\x{12e9}\x{12c8}\x{122a}", +"\x{134c}\x{1265}\x{1229}\x{12c8}\x{122a}", +"\x{121b}\x{122d}\x{127d}", +"\x{12a4}\x{1355}\x{1228}\x{120d}", +"\x{121c}\x{12ed}", +"\x{1301}\x{1295}", +"\x{1301}\x{120b}\x{12ed}", +"\x{12a6}\x{1308}\x{1235}\x{1275}", +"\x{1234}\x{1355}\x{1274}\x{121d}\x{1260}\x{122d}", +"\x{12a6}\x{12ad}\x{1270}\x{12cd}\x{1260}\x{122d}", +"\x{1296}\x{126c}\x{121d}\x{1260}\x{122d}", +"\x{12f2}\x{1234}\x{121d}\x{1260}\x{122d}" +); +@DoWs = map { substr($_,0,3) } @DoW; +@MoYs = map { substr($_,0,3) } @MoY; +@AMPM = ( +"\x{1295}/\x{1230}", +"\x{12F5}/\x{1230}" +); + +@Dsuf = ("\x{12ed}" x 31); + +Date::Language::_build_lookups(); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::Tigrinya - Tigrinya localization for Date::Format + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/TigrinyaEritrean.pm b/git/usr/share/perl5/vendor_perl/Date/Language/TigrinyaEritrean.pm new file mode 100644 index 0000000000000000000000000000000000000000..12f8c1122a466e9fc1d39d2b2c4bde3b75cce863 --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/TigrinyaEritrean.pm @@ -0,0 +1,121 @@ +## +## Tigrinya-Eritrean tables +## + +package Date::Language::TigrinyaEritrean; + +use strict; +use warnings; +use base 'Date::Language'; + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: TigrinyaEritrean localization for Date::Format + +our (@DoW, @DoWs, @MoY, @MoYs, @AMPM, @Dsuf, %MoY, %DoW); + +if ( $] >= 5.006 ) { +@DoW = ( +"\x{1230}\x{1295}\x{1260}\x{1275}", +"\x{1230}\x{1291}\x{12ed}", +"\x{1230}\x{1209}\x{1235}", +"\x{1228}\x{1261}\x{12d5}", +"\x{1213}\x{1219}\x{1235}", +"\x{12d3}\x{122d}\x{1262}", +"\x{1240}\x{12f3}\x{121d}" +); +@MoY = ( +"\x{1303}\x{1295}\x{12e9}\x{12c8}\x{122a}", +"\x{134c}\x{1265}\x{1229}\x{12c8}\x{122a}", +"\x{121b}\x{122d}\x{127d}", +"\x{12a4}\x{1355}\x{1228}\x{120d}", +"\x{121c}\x{12ed}", +"\x{1301}\x{1295}", +"\x{1301}\x{120b}\x{12ed}", +"\x{12a6}\x{1308}\x{1235}\x{1275}", +"\x{1234}\x{1355}\x{1274}\x{121d}\x{1260}\x{122d}", +"\x{12a6}\x{12ad}\x{1270}\x{12cd}\x{1260}\x{122d}", +"\x{1296}\x{126c}\x{121d}\x{1260}\x{122d}", +"\x{12f2}\x{1234}\x{121d}\x{1260}\x{122d}" +); +@DoWs = map { substr($_,0,3) } @DoW; +@MoYs = map { substr($_,0,3) } @MoY; +@AMPM = ( +"\x{1295}/\x{1230}", +"\x{12F5}/\x{1230}" +); + +@Dsuf = ("\x{12ed}" x 31); +} +else { +@DoW = ( +"ሰንበት", +"ሰኑይ", +"ሰሉስ", +"ረቡዕ", +"ሓሙስ", +"ዓርቢ", +"ቀዳም" +); +@MoY = ( +"ጥሪ", +"ለካቲት", +"መጋቢት", +"ሚያዝያ", +"ግንቦት", +"ሰነ", +"ሓምለ", +"ነሓሰ", +"መስከረም", +"ጥቅምቲ", +"ሕዳር", +"ታሕሳስ" +); +@DoWs = map { substr($_,0,9) } @DoW; +@MoYs = map { substr($_,0,9) } @MoY; +@AMPM = ( +"ን/ሰ", +"ድ/ሰ" +); + +@Dsuf = ("ይ" x 31); +} + +Date::Language::_build_lookups(); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::TigrinyaEritrean - TigrinyaEritrean localization for Date::Format + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/TigrinyaEthiopian.pm b/git/usr/share/perl5/vendor_perl/Date/Language/TigrinyaEthiopian.pm new file mode 100644 index 0000000000000000000000000000000000000000..ebf3039726342da9a19431d7d6f4f996b5368497 --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/TigrinyaEthiopian.pm @@ -0,0 +1,123 @@ +## +## Tigrinya-Ethiopian tables +## + +package Date::Language::TigrinyaEthiopian; + +use strict; +use warnings; + +use Date::Language (); +use base qw(Date::Language); + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: TigrinyaEthiopian localization for Date::Format + +our (@DoW, @DoWs, @MoY, @MoYs, @AMPM, @Dsuf, %MoY, %DoW); + +if ( $] >= 5.006 ) { +@DoW = ( +"\x{1230}\x{1295}\x{1260}\x{1275}", +"\x{1230}\x{1291}\x{12ed}", +"\x{1230}\x{1209}\x{1235}", +"\x{1228}\x{1261}\x{12d5}", +"\x{1213}\x{1219}\x{1235}", +"\x{12d3}\x{122d}\x{1262}", +"\x{1240}\x{12f3}\x{121d}" +); +@MoY = ( +"\x{1303}\x{1295}\x{12e9}\x{12c8}\x{122a}", +"\x{134c}\x{1265}\x{1229}\x{12c8}\x{122a}", +"\x{121b}\x{122d}\x{127d}", +"\x{12a4}\x{1355}\x{1228}\x{120d}", +"\x{121c}\x{12ed}", +"\x{1301}\x{1295}", +"\x{1301}\x{120b}\x{12ed}", +"\x{12a6}\x{1308}\x{1235}\x{1275}", +"\x{1234}\x{1355}\x{1274}\x{121d}\x{1260}\x{122d}", +"\x{12a6}\x{12ad}\x{1270}\x{12cd}\x{1260}\x{122d}", +"\x{1296}\x{126c}\x{121d}\x{1260}\x{122d}", +"\x{12f2}\x{1234}\x{121d}\x{1260}\x{122d}" +); +@DoWs = map { substr($_,0,3) } @DoW; +@MoYs = map { substr($_,0,3) } @MoY; +@AMPM = ( +"\x{1295}/\x{1230}", +"\x{12F5}/\x{1230}" +); + +@Dsuf = ("\x{12ed}" x 31); +} +else { +@DoW = ( +"ሰንበት", +"ሰኑይ", +"ሰሉስ", +"ረቡዕ", +"ሓሙስ", +"ዓርቢ", +"ቀዳም" +); +@MoY = ( +"ጃንዩወሪ", +"ፌብሩወሪ", +"ማርች", +"ኤፕረል", +"ሜይ", +"ጁን", +"ጁላይ", +"ኦገስት", +"ሴፕቴምበር", +"ኦክተውበር", +"ኖቬምበር", +"ዲሴምበር" +); +@DoWs = map { substr($_,0,9) } @DoW; +@MoYs = map { substr($_,0,9) } @MoY; +@AMPM = ( +"ን/ሰ", +"ድ/ሰ" +); + +@Dsuf = ("ይ" x 31); +} + +Date::Language::_build_lookups(); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[$_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[$_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::TigrinyaEthiopian - TigrinyaEthiopian localization for Date::Format + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/Date/Language/Turkish.pm b/git/usr/share/perl5/vendor_perl/Date/Language/Turkish.pm new file mode 100644 index 0000000000000000000000000000000000000000..75e4d74f9ebcd1e92c9bac50cb6d16bb68897c7f --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/Date/Language/Turkish.pm @@ -0,0 +1,87 @@ +#----------------------------------------------------# +# +# Turkish tables +# Burak Gürsoy +# Last modified: Sat Nov 15 20:28:32 2003 +# +# use Date::Language; +# my $turkish = Date::Language->new('Turkish'); +# print $turkish->time2str("%e %b %Y, %a %T\n", time); +# print $turkish->str2time("25 Haz 1996 21:09:55 +0100"); +#----------------------------------------------------# + +package Date::Language::Turkish; + +use strict; +use warnings; +use utf8; +use base 'Date::Language'; + +our $VERSION = '2.35'; # VERSION: generated +# ABSTRACT: Turkish localization for Date::Format + +our @DoW = qw(Pazar Pazartesi Salı Çarşamba Perşembe Cuma Cumartesi); +our @MoY = qw(Ocak Şubat Mart Nisan Mayıs Haziran Temmuz Ağustos Eylül Ekim Kasım Aralık); +our @DoWs = map { substr($_,0,3) } @DoW; +$DoWs[1] = 'Pzt'; # Since we'll get two 'Paz' s +$DoWs[-1] = 'Cmt'; # Since we'll get two 'Cum' s +our @MoYs = map { substr($_,0,3) } @MoY; +our @AMPM = ('',''); # no am-pm thingy + +# not easy as in english... maybe we can just use a dot "." ? :) +our %DsufMAP = ( +(map {$_ => 'inci', $_+10 => 'inci', $_+20 => 'inci' } 1,2,5,8 ), +(map {$_ => 'nci', $_+10 => 'nci', $_+20 => 'nci' } 7 ), +(map {$_ => 'nci', $_+10 => 'nci', $_+20 => 'nci' } 2 ), +(map {$_ => 'üncü', $_+10 => 'üncü', $_+20 => 'üncü' } 3,4 ), +(map {$_ => 'uncu', $_+10 => 'uncu', $_+20 => 'uncu' } 9 ), +(map {$_ => 'ncı', $_+10 => 'ncı', $_+20 => 'ncı' } 6 ), +(map {$_ => 'uncu', } 10,30 ), + 20 => 'nci', + 31 => 'inci', +); + +our @Dsuf = map{ $DsufMAP{$_} } sort {$a <=> $b} keys %DsufMAP; + +our ( %MoY, %DoW ); +Date::Language::_build_lookups(); + +# Formatting routines + +sub format_a { $DoWs[$_[0]->[6]] } +sub format_A { $DoW[ $_[0]->[6]] } +sub format_b { $MoYs[$_[0]->[4]] } +sub format_B { $MoY[ $_[0]->[4]] } +sub format_h { $MoYs[$_[0]->[4]] } +sub format_p { '' } # disable +sub format_P { '' } # disable +sub format_o { sprintf("%2d%s",$_[0]->[3],$Dsuf[$_[0]->[3]-1]) } + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Date::Language::Turkish - Turkish localization for Date::Format + +=head1 VERSION + +version 2.35 + +=head1 AUTHOR + +Graham + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2020 by Graham Barr. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/git/usr/share/perl5/vendor_perl/HTTP/Request/Common.pm b/git/usr/share/perl5/vendor_perl/HTTP/Request/Common.pm new file mode 100644 index 0000000000000000000000000000000000000000..1a4e84ecebe11142623bab34c55098454158fb05 --- /dev/null +++ b/git/usr/share/perl5/vendor_perl/HTTP/Request/Common.pm @@ -0,0 +1,577 @@ +package HTTP::Request::Common; + +use strict; +use warnings; + +our $VERSION = '7.01'; + +our $DYNAMIC_FILE_UPLOAD ||= 0; # make it defined (don't know why) +our $READ_BUFFER_SIZE = 8192; + +use Exporter 5.57 'import'; + +our @EXPORT =qw(GET HEAD PUT PATCH POST OPTIONS); +our @EXPORT_OK = qw($DYNAMIC_FILE_UPLOAD DELETE); + +require HTTP::Request; +use Carp(); +use File::Spec; + +my $CRLF = "\015\012"; # "\r\n" is not portable + +sub GET { _simple_req('GET', @_); } +sub HEAD { _simple_req('HEAD', @_); } +sub DELETE { _simple_req('DELETE', @_); } +sub PATCH { request_type_with_data('PATCH', @_); } +sub POST { request_type_with_data('POST', @_); } +sub PUT { request_type_with_data('PUT', @_); } +sub OPTIONS { request_type_with_data('OPTIONS', @_); } + +sub request_type_with_data +{ + my $type = shift; + my $url = shift; + my $req = HTTP::Request->new($type => $url); + my $content; + $content = shift if @_ and ref $_[0]; + my($k, $v); + while (($k,$v) = splice(@_, 0, 2)) { + if (lc($k) eq 'content') { + $content = $v; + } + else { + $req->push_header($k, $v); + } + } + my $ct = $req->header('Content-Type'); + unless ($ct) { + $ct = 'application/x-www-form-urlencoded'; + } + elsif ($ct eq 'form-data') { + $ct = 'multipart/form-data'; + } + + if (ref $content) { + if ($ct =~ m,^multipart/form-data\s*(;|$),i) { + require HTTP::Headers::Util; + my @v = HTTP::Headers::Util::split_header_words($ct); + Carp::carp("Multiple Content-Type headers") if @v > 1; + @v = @{$v[0]}; + + my $boundary; + my $boundary_index; + for (my @tmp = @v; @tmp;) { + my($k, $v) = splice(@tmp, 0, 2); + if ($k eq "boundary") { + $boundary = $v; + $boundary_index = @v - @tmp - 1; + last; + } + } + + ($content, $boundary) = form_data($content, $boundary, $req); + + if ($boundary_index) { + $v[$boundary_index] = $boundary; + } + else { + push(@v, boundary => $boundary); + } + + $ct = HTTP::Headers::Util::join_header_words(@v); + } + else { + # We use a temporary URI object to format + # the application/x-www-form-urlencoded content. + require URI; + my $url = URI->new('http:'); + $url->query_form(ref($content) eq "HASH" ? %$content : @$content); + $content = $url->query; + } + } + + $req->header('Content-Type' => $ct); # might be redundant + if (defined($content)) { + $req->header('Content-Length' => + length($content)) unless ref($content); + $req->content($content); + } + else { + $req->header('Content-Length' => 0); + } + $req; +} + + +sub _simple_req +{ + my($method, $url) = splice(@_, 0, 2); + my $req = HTTP::Request->new($method => $url); + my($k, $v); + my $content; + while (($k,$v) = splice(@_, 0, 2)) { + if (lc($k) eq 'content') { + $req->add_content($v); + $content++; + } + else { + $req->push_header($k, $v); + } + } + if ($content && !defined($req->header("Content-Length"))) { + $req->header("Content-Length", length(${$req->content_ref})); + } + $req; +} + + +sub form_data # RFC1867 +{ + my($data, $boundary, $req) = @_; + my @data = ref($data) eq "HASH" ? %$data : @$data; # copy + my $fhparts; + my @parts; + while (my ($k,$v) = splice(@data, 0, 2)) { + if (!ref($v)) { + $k =~ s/([\\\"])/\\$1/g; # escape quotes and backslashes + no warnings 'uninitialized'; + push(@parts, + qq(Content-Disposition: form-data; name="$k"$CRLF$CRLF$v)); + } + else { + my($file, $usename, @headers) = @$v; + unless (defined $usename) { + $usename = $file; + $usename = (File::Spec->splitpath($usename))[-1] if defined($usename); + } + $k =~ s/([\\\"])/\\$1/g; + my $disp = qq(form-data; name="$k"); + if (defined($usename) and length($usename)) { + $usename =~ s/([\\\"])/\\$1/g; + $disp .= qq(; filename="$usename"); + } + my $content = ""; + my $h = HTTP::Headers->new(@headers); + if ($file) { + open(my $fh, "<", $file) or Carp::croak("Can't open file $file: $!"); + binmode($fh); + if ($DYNAMIC_FILE_UPLOAD) { + # will read file later, close it now in order to + # not accumulate to many open file handles + close($fh); + $content = \$file; + } + else { + local($/) = undef; # slurp files + $content = <$fh>; + close($fh); + } + unless ($h->header("Content-Type")) { + require LWP::MediaTypes; + LWP::MediaTypes::guess_media_type($file, $h); + } + } + if ($h->header("Content-Disposition")) { + # just to get it sorted first + $disp = $h->header("Content-Disposition"); + $h->remove_header("Content-Disposition"); + } + if ($h->header("Content")) { + $content = $h->header("Content"); + $h->remove_header("Content"); + } + my $head = join($CRLF, "Content-Disposition: $disp", + $h->as_string($CRLF), + ""); + if (ref $content) { + push(@parts, [$head, $$content]); + $fhparts++; + } + else { + push(@parts, $head . $content); + } + } + } + return ("", "none") unless @parts; + + my $content; + if ($fhparts) { + $boundary = boundary(10) # hopefully enough randomness + unless $boundary; + + # add the boundaries to the @parts array + for (1..@parts-1) { + splice(@parts, $_*2-1, 0, "$CRLF--$boundary$CRLF"); + } + unshift(@parts, "--$boundary$CRLF"); + push(@parts, "$CRLF--$boundary--$CRLF"); + + # See if we can generate Content-Length header + my $length = 0; + for (@parts) { + if (ref $_) { + my ($head, $f) = @$_; + my $file_size; + unless ( -f $f && ($file_size = -s _) ) { + # The file is either a dynamic file like /dev/audio + # or perhaps a file in the /proc file system where + # stat may return a 0 size even though reading it + # will produce data. So we cannot make + # a Content-Length header. + undef $length; + last; + } + $length += $file_size + length $head; + } + else { + $length += length; + } + } + $length && $req->header('Content-Length' => $length); + + # set up a closure that will return content piecemeal + $content = sub { + for (;;) { + unless (@parts) { + defined $length && $length != 0 && + Carp::croak "length of data sent did not match calculated Content-Length header. Probably because uploaded file changed in size during transfer."; + return; + } + my $p = shift @parts; + unless (ref $p) { + $p .= shift @parts while @parts && !ref($parts[0]); + defined $length && ($length -= length $p); + return $p; + } + my($buf, $fh) = @$p; + unless (ref($fh)) { + my $file = $fh; + undef($fh); + open($fh, "<", $file) || Carp::croak("Can't open file $file: $!"); + binmode($fh); + } + my $buflength = length $buf; + my $n = read($fh, $buf, $READ_BUFFER_SIZE, $buflength); + if ($n) { + $buflength += $n; + unshift(@parts, ["", $fh]); + } + else { + close($fh); + } + if ($buflength) { + defined $length && ($length -= $buflength); + return $buf + } + } + }; + + } + else { + $boundary = boundary() unless $boundary; + + my $bno = 0; + CHECK_BOUNDARY: + { + for (@parts) { + if (index($_, $boundary) >= 0) { + # must have a better boundary + $boundary = boundary(++$bno); + redo CHECK_BOUNDARY; + } + } + last; + } + $content = "--$boundary$CRLF" . + join("$CRLF--$boundary$CRLF", @parts) . + "$CRLF--$boundary--$CRLF"; + } + + wantarray ? ($content, $boundary) : $content; +} + + +sub boundary +{ + my $size = shift || return "xYzZY"; + require MIME::Base64; + my $b = MIME::Base64::encode(join("", map chr(rand(256)), 1..$size*3), ""); + $b =~ s/[\W]/X/g; # ensure alnum only + $b; +} + +1; + +=pod + +=encoding UTF-8 + +=head1 NAME + +HTTP::Request::Common - Construct common HTTP::Request objects + +=head1 VERSION + +version 7.01 + +=head1 SYNOPSIS + + use HTTP::Request::Common; + $ua = LWP::UserAgent->new; + $ua->request(GET 'http://www.sn.no/'); + $ua->request(POST 'http://somewhere/foo', foo => bar, bar => foo); + $ua->request(PATCH 'http://somewhere/foo', foo => bar, bar => foo); + $ua->request(PUT 'http://somewhere/foo', foo => bar, bar => foo); + $ua->request(OPTIONS 'http://somewhere/foo', foo => bar, bar => foo); + +=head1 DESCRIPTION + +This module provides functions that return newly created C +objects. These functions are usually more convenient to use than the +standard C constructor for the most common requests. + +Note that L has several convenience methods, including +C, C, C, C and C. + +The following functions are provided: + +=over 4 + +=item GET $url + +=item GET $url, Header => Value,... + +The C function returns an L object initialized with +the "GET" method and the specified URL. It is roughly equivalent to the +following call + + HTTP::Request->new( + GET => $url, + HTTP::Headers->new(Header => Value,...), + ) + +but is less cluttered. What is different is that a header named +C will initialize the content part of the request instead of +setting a header field. Note that GET requests should normally not +have a content, so this hack makes more sense for the C, C + and C functions described below. + +The C method of L exists as a shortcut for +C<< $ua->request(GET ...) >>. + +=item HEAD $url + +=item HEAD $url, Header => Value,... + +Like GET() but the method in the request is "HEAD". + +The C method of L exists as a shortcut for +C<< $ua->request(HEAD ...) >>. + +=item DELETE $url + +=item DELETE $url, Header => Value,... + +Like C but the method in the request is C. This function +is not exported by default. + +=item PATCH $url + +=item PATCH $url, Header => Value,... + +=item PATCH $url, $form_ref, Header => Value,... + +=item PATCH $url, Header => Value,..., Content => $form_ref + +=item PATCH $url, Header => Value,..., Content => $content + +The same as C below, but the method in the request is C. + +=item PUT $url + +=item PUT $url, Header => Value,... + +=item PUT $url, $form_ref, Header => Value,... + +=item PUT $url, Header => Value,..., Content => $form_ref + +=item PUT $url, Header => Value,..., Content => $content + +The same as C below, but the method in the request is C + +=item OPTIONS $url + +=item OPTIONS $url, Header => Value,... + +=item OPTIONS $url, $form_ref, Header => Value,... + +=item OPTIONS $url, Header => Value,..., Content => $form_ref + +=item OPTIONS $url, Header => Value,..., Content => $content + +The same as C below, but the method in the request is C + +This was added in version 6.21, so you should require that in your code: + + use HTTP::Request::Common 6.21; + +=item POST $url + +=item POST $url, Header => Value,... + +=item POST $url, $form_ref, Header => Value,... + +=item POST $url, Header => Value,..., Content => $form_ref + +=item POST $url, Header => Value,..., Content => $content + +C, C and C all work with the same parameters. + + %data = ( title => 'something', body => something else' ); + $ua = LWP::UserAgent->new(); + $request = HTTP::Request::Common::POST( $url, [ %data ] ); + $response = $ua->request($request); + +They take a second optional array or hash reference +parameter C<$form_ref>. The content can also be specified +directly using the C pseudo-header, and you may also provide +the C<$form_ref> this way. + +The C pseudo-header steals a bit of the header field namespace as +there is no way to directly specify a header that is actually called +"Content". If you really need this you must update the request +returned in a separate statement. + +The C<$form_ref> argument can be used to pass key/value pairs for the +form content. By default we will initialize a request using the +C content type. This means that +you can emulate an HTML Eform> POSTing like this: + + POST 'http://www.perl.org/survey.cgi', + [ name => 'Gisle Aas', + email => 'gisle@aas.no', + gender => 'M', + born => '1964', + perc => '3%', + ]; + +This will create an L object that looks like this: + + POST http://www.perl.org/survey.cgi + Content-Length: 66 + Content-Type: application/x-www-form-urlencoded + + name=Gisle%20Aas&email=gisle%40aas.no&gender=M&born=1964&perc=3%25 + +Multivalued form fields can be specified by either repeating the field +name or by passing the value as an array reference. + +The POST method also supports the C content used +for I as specified in RFC 1867. You trigger +this content format by specifying a content type of C<'form-data'> as +one of the request headers. If one of the values in the C<$form_ref> is +an array reference, then it is treated as a file part specification +with the following interpretation: + + [ $file, $filename, Header => Value... ] + [ undef, $filename, Header => Value,..., Content => $content ] + +The first value in the array ($file) is the name of a file to open. +This file will be read and its content placed in the request. The +routine will croak if the file can't be opened. Use an C as +$file value if you want to specify the content directly with a +C header. The $filename is the filename to report in the +request. If this value is undefined, then the basename of the $file +will be used. You can specify an empty string as $filename if you +want to suppress sending the filename when you provide a $file value. + +If a $file is provided by no C header, then C +and C will be filled in automatically with the values +returned by C + +Sending my F<~/.profile> to the survey used as example above can be +achieved by this: + + POST 'http://www.perl.org/survey.cgi', + Content_Type => 'form-data', + Content => [ name => 'Gisle Aas', + email => 'gisle@aas.no', + gender => 'M', + born => '1964', + init => ["$ENV{HOME}/.profile"], + ] + +This will create an L object that almost looks this (the +boundary and the content of your F<~/.profile> is likely to be +different): + + POST http://www.perl.org/survey.cgi + Content-Length: 388 + Content-Type: multipart/form-data; boundary="6G+f" + + --6G+f + Content-Disposition: form-data; name="name" + + Gisle Aas + --6G+f + Content-Disposition: form-data; name="email" + + gisle@aas.no + --6G+f + Content-Disposition: form-data; name="gender" + + M + --6G+f + Content-Disposition: form-data; name="born" + + 1964 + --6G+f + Content-Disposition: form-data; name="init"; filename=".profile" + Content-Type: text/plain + + PATH=/local/perl/bin:$PATH + export PATH + + --6G+f-- + +If you set the C<$DYNAMIC_FILE_UPLOAD> variable (exportable) to some TRUE +value, then you get back a request object with a subroutine closure as +the content attribute. This subroutine will read the content of any +files on demand and return it in suitable chunks. This allow you to +upload arbitrary big files without using lots of memory. You can even +upload infinite files like F if you wish; however, if +the file is not a plain file, there will be no C header +defined for the request. Not all servers (or server +applications) like this. Also, if the file(s) change in size between +the time the C is calculated and the time that the last +chunk is delivered, the subroutine will C. + +The C method of L exists as a shortcut for +C<< $ua->request(POST ...) >>. + +=back + +=head1 SEE ALSO + +L, L + +Also, there are some examples in L that you might +find useful. For example, batch requests are explained there. + +=head1 AUTHOR + +Gisle Aas + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 1994 by Gisle Aas. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut + +__END__ + + +#ABSTRACT: Construct common HTTP::Request objects diff --git a/go/CONTRIBUTING.md b/go/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..4cd76c29503d5dcee45240cd4de94e4f25c78d28 --- /dev/null +++ b/go/CONTRIBUTING.md @@ -0,0 +1,35 @@ +# Contributing to Go + +Go is an open source project. + +It is the work of hundreds of contributors. We appreciate your help! + +## Before filing an issue + +If you are unsure whether you have found a bug, please consider asking in the [golang-nuts mailing +list](https://groups.google.com/forum/#!forum/golang-nuts) or [other forums](https://golang.org/help/) first. If +the behavior you are seeing is confirmed as a bug or issue, it can easily be re-raised in the issue tracker. + +## Filing issues + +Sensitive security-related issues should be reported to [security@golang.org](mailto:security@golang.org). +See the [security policy](https://golang.org/security) for details. + +The recommended way to file an issue is by running `go bug`. +Otherwise, when filing an issue, make sure to answer these five questions: + +1. What version of Go are you using (`go version`)? +2. What operating system and processor architecture are you using? +3. What did you do? +4. What did you expect to see? +5. What did you see instead? + +For change proposals, see [Proposing Changes To Go](https://go.dev/s/proposal-process). + +## Contributing code + +Please read the [Contribution Guidelines](https://golang.org/doc/contribute.html) before sending patches. + +Unless otherwise noted, the Go source files are distributed under +the BSD-style license found in the LICENSE file. + diff --git a/go/LICENSE b/go/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..2a7cf70da6e498df9c11ab6a5eaa2ddd7af34da4 --- /dev/null +++ b/go/LICENSE @@ -0,0 +1,27 @@ +Copyright 2009 The Go Authors. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google LLC nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/go/PATENTS b/go/PATENTS new file mode 100644 index 0000000000000000000000000000000000000000..733099041f84fa1e58611ab2e11af51c1f26d1d2 --- /dev/null +++ b/go/PATENTS @@ -0,0 +1,22 @@ +Additional IP Rights Grant (Patents) + +"This implementation" means the copyrightable works distributed by +Google as part of the Go project. + +Google hereby grants to You a perpetual, worldwide, non-exclusive, +no-charge, royalty-free, irrevocable (except as stated in this section) +patent license to make, have made, use, offer to sell, sell, import, +transfer and otherwise run, modify and propagate the contents of this +implementation of Go, where such license applies only to those patent +claims, both currently owned or controlled by Google and acquired in +the future, licensable by Google that are necessarily infringed by this +implementation of Go. This grant does not include claims that would be +infringed only as a consequence of further modification of this +implementation. If you or your agent or exclusive licensee institute or +order or agree to the institution of patent litigation against any +entity (including a cross-claim or counterclaim in a lawsuit) alleging +that this implementation of Go or any code incorporated within this +implementation of Go constitutes direct or contributory patent +infringement, or inducement of patent infringement, then any patent +rights granted to you under this License for this implementation of Go +shall terminate as of the date such litigation is filed. diff --git a/go/README.md b/go/README.md new file mode 100644 index 0000000000000000000000000000000000000000..71c9d1dc2993880f38d227085d1b48c4070d1e85 --- /dev/null +++ b/go/README.md @@ -0,0 +1,42 @@ +# The Go Programming Language + +Go is an open source programming language that makes it easy to build simple, +reliable, and efficient software. + +![Gopher image](https://golang.org/doc/gopher/fiveyears.jpg) +*Gopher image by [Renee French][rf], licensed under [Creative Commons 4.0 Attribution license][cc4-by].* + +Our canonical Git repository is located at https://go.googlesource.com/go. +There is a mirror of the repository at https://github.com/golang/go. + +Unless otherwise noted, the Go source files are distributed under the +BSD-style license found in the LICENSE file. + +### Download and Install + +#### Binary Distributions + +Official binary distributions are available at https://go.dev/dl/. + +After downloading a binary release, visit https://go.dev/doc/install +for installation instructions. + +#### Install From Source + +If a binary distribution is not available for your combination of +operating system and architecture, visit +https://go.dev/doc/install/source +for source installation instructions. + +### Contributing + +Go is the work of thousands of contributors. We appreciate your help! + +To contribute, please read the contribution guidelines at https://go.dev/doc/contribute. + +Note that the Go project uses the issue tracker for bug reports and +proposals only. See https://go.dev/wiki/Questions for a list of +places to ask questions about the Go language. + +[rf]: https://reneefrench.blogspot.com/ +[cc4-by]: https://creativecommons.org/licenses/by/4.0/ diff --git a/go/SECURITY.md b/go/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..e1718f0b012f7cea592027ae7574a6878f05f3fc --- /dev/null +++ b/go/SECURITY.md @@ -0,0 +1,13 @@ +# Security Policy + +## Supported Versions + +We support the past two Go releases (for example, Go 1.17.x and Go 1.18.x when Go 1.18.x is the latest stable release). + +See https://go.dev/wiki/Go-Release-Cycle and in particular the +[Release Maintenance](https://go.dev/wiki/Go-Release-Cycle#release-maintenance) +part of that page. + +## Reporting a Vulnerability + +See https://go.dev/security/policy for how to report a vulnerability. diff --git a/go/VERSION b/go/VERSION new file mode 100644 index 0000000000000000000000000000000000000000..5378f3c07548b648fde9888490504b9b4d13526a --- /dev/null +++ b/go/VERSION @@ -0,0 +1,2 @@ +go1.26.3 +time 2026-05-04T20:36:18Z diff --git a/go/codereview.cfg b/go/codereview.cfg new file mode 100644 index 0000000000000000000000000000000000000000..521e90c1db833ac8b1d6684786f02981a6585a33 --- /dev/null +++ b/go/codereview.cfg @@ -0,0 +1,2 @@ +branch: release-branch.go1.26 +parent-branch: master diff --git a/go/go.env b/go/go.env new file mode 100644 index 0000000000000000000000000000000000000000..6ff2b921d464bc64266c9d84a67a33fb5505d216 --- /dev/null +++ b/go/go.env @@ -0,0 +1,12 @@ +# This file contains the initial defaults for go command configuration. +# Values set by 'go env -w' and written to the user's go/env file override these. +# The environment overrides everything else. + +# Use the Go module mirror and checksum database by default. +# See https://proxy.golang.org for details. +GOPROXY=https://proxy.golang.org,direct +GOSUMDB=sum.golang.org + +# Automatically download newer toolchains as directed by go.mod files. +# See https://go.dev/doc/toolchain for details. +GOTOOLCHAIN=auto diff --git a/huggingface/.check_for_update_done b/huggingface/.check_for_update_done new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/java/NOTICE b/java/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..45484c2619d376ae5a76b134a2b9cdb4720c33ff --- /dev/null +++ b/java/NOTICE @@ -0,0 +1,63 @@ +# Notices for Eclipse Temurin + +This content is produced and maintained by the Eclipse Temurin project. + + * Project home: https://projects.eclipse.org/projects/adoptium.temurin + +## Trademarks + +Eclipse Temurin is a trademark of the Eclipse Foundation. Eclipse, and the +Eclipse Logo are registered trademarks of the Eclipse Foundation. + +Java and all Java-based trademarks are trademarks of Oracle Corporation in +the United States, other countries, or both. + +## Copyright + +All content is the property of the respective authors or their employers. +For more information regarding authorship of content, please consult the +listed source code repository logs. + +## Declared Project Licenses + +This program and the accompanying materials are made available under the terms +of the GNU General Public License, version 2, with the Classpath Exception. + +Additional information relating to the program and accompanying materials +license and usage is available as follows. + * For Eclipse Temurin version 8 see the LICENSE and ASSEMBLY_EXCEPTION files +in the top level directory of the installation. + * For Eclipse Temurin version 9 or later see the files under the legal/ +directory in the top level directory of the installation. + +SPDX-License-Identifier: GPL-2.0 WITH Classpath-exception-2.0 + +## Source Code + +The project maintains the following source code repositories which may be +relevant to this content: + + * https://github.com/adoptium/temurin-build + * https://github.com/adoptium/jdk + * https://github.com/adoptium/jdk8u + * https://github.com/adoptium/jdk11u + * https://github.com/adoptium/jdk17u + * https://github.com/adoptium/jdk20 + * and so on + +## Third-party Content + +This program and accompanying materials contains third-party content. + * For Eclipse Temurin version 8 see the THIRD_PARTY_LICENSE file in the +top level directory of the installation. + * For Eclipse Temurin version 9 or later see the files under the legal/ +directory in the top level directory of the installation. + +## Cryptography + +Content may contain encryption software. The country in which you are currently +may have restrictions on the import, possession, and use, and/or re-export to +another country, of encryption software. BEFORE using any encryption software, +please check the country's laws, regulations and policies concerning the import, +possession, or use, and re-export of encryption software, to see if this is +permitted. diff --git a/java/release b/java/release new file mode 100644 index 0000000000000000000000000000000000000000..4a26d501290bc9489bbf5a76be9321a543fcfe26 --- /dev/null +++ b/java/release @@ -0,0 +1,19 @@ +IMPLEMENTOR="Eclipse Adoptium" +IMPLEMENTOR_VERSION="Temurin-23.0.2+7" +JAVA_RUNTIME_VERSION="23.0.2+7" +JAVA_VERSION="23.0.2" +JAVA_VERSION_DATE="2025-01-21" +LIBC="default" +MODULES="java.base java.compiler java.datatransfer java.xml java.prefs java.desktop java.instrument java.logging java.management java.security.sasl java.naming java.rmi java.management.rmi java.net.http java.scripting java.security.jgss java.transaction.xa java.sql java.sql.rowset java.xml.crypto java.se java.smartcardio jdk.accessibility jdk.internal.jvmstat jdk.attach jdk.charsets jdk.internal.opt jdk.zipfs jdk.compiler jdk.crypto.cryptoki jdk.crypto.ec jdk.crypto.mscapi jdk.dynalink jdk.internal.ed jdk.editpad jdk.internal.vm.ci jdk.graal.compiler jdk.graal.compiler.management jdk.hotspot.agent jdk.httpserver jdk.incubator.vector jdk.internal.le jdk.internal.md jdk.jartool jdk.javadoc jdk.jcmd jdk.management jdk.management.agent jdk.jconsole jdk.jdeps jdk.jdwp.agent jdk.jdi jdk.jfr jdk.jlink jdk.jpackage jdk.jshell jdk.jsobject jdk.jstatd jdk.localedata jdk.management.jfr jdk.naming.dns jdk.naming.rmi jdk.net jdk.nio.mapmode jdk.sctp jdk.security.auth jdk.security.jgss jdk.unsupported jdk.unsupported.desktop jdk.xml.dom" +OS_ARCH="x86_64" +OS_NAME="Windows" +SOURCE=".:git:ff87e76b386d" +BUILD_SOURCE="git:aaf9cbd0641cf21daa951c69ef6d7183b3af9e99" +BUILD_SOURCE_REPO="https://github.com/adoptium/temurin-build.git" +SOURCE_REPO="https://github.com/adoptium/jdk23u.git" +FULL_VERSION="23.0.2+7" +SEMANTIC_VERSION="23.0.2+7" +BUILD_INFO="OS: Windows Server 2022 Version: 10.0" +JVM_VARIANT="Hotspot" +JVM_VERSION="23.0.2+7" +IMAGE_TYPE="JDK" diff --git a/java21/release b/java21/release new file mode 100644 index 0000000000000000000000000000000000000000..a3a1384541fe07fe7d0029293d1839e7570357fa --- /dev/null +++ b/java21/release @@ -0,0 +1,19 @@ +IMPLEMENTOR="Eclipse Adoptium" +IMPLEMENTOR_VERSION="Temurin-21.0.11+10" +JAVA_RUNTIME_VERSION="21.0.11+10-LTS" +JAVA_VERSION="21.0.11" +JAVA_VERSION_DATE="2026-04-21" +LIBC="default" +MODULES="java.base java.compiler java.datatransfer java.xml java.prefs java.desktop java.instrument java.logging java.management java.security.sasl java.naming java.rmi java.management.rmi java.net.http java.scripting java.security.jgss java.transaction.xa java.sql java.sql.rowset java.xml.crypto java.se java.smartcardio jdk.accessibility jdk.internal.jvmstat jdk.attach jdk.charsets jdk.internal.opt jdk.zipfs jdk.compiler jdk.crypto.ec jdk.crypto.cryptoki jdk.crypto.mscapi jdk.dynalink jdk.internal.ed jdk.editpad jdk.hotspot.agent jdk.httpserver jdk.incubator.vector jdk.internal.le jdk.internal.vm.ci jdk.internal.vm.compiler jdk.internal.vm.compiler.management jdk.jartool jdk.javadoc jdk.jcmd jdk.management jdk.management.agent jdk.jconsole jdk.jdeps jdk.jdwp.agent jdk.jdi jdk.jfr jdk.jlink jdk.jpackage jdk.jshell jdk.jsobject jdk.jstatd jdk.localedata jdk.management.jfr jdk.naming.dns jdk.naming.rmi jdk.net jdk.nio.mapmode jdk.random jdk.sctp jdk.security.auth jdk.security.jgss jdk.unsupported jdk.unsupported.desktop jdk.xml.dom" +OS_ARCH="x86_64" +OS_NAME="Windows" +SOURCE=".:git:254494ad7d75" +BUILD_SOURCE="git:a612825ee82a20ac872d60958c349854c1f29a8e" +BUILD_SOURCE_REPO="https://github.com/adoptium/temurin-build.git" +SOURCE_REPO="https://github.com/adoptium/jdk21u.git" +FULL_VERSION="21.0.11+10-LTS" +SEMANTIC_VERSION="21.0.11+10" +BUILD_INFO="OS: Windows Server 2022 Version: 10.0" +JVM_VARIANT="Hotspot" +JVM_VERSION="21.0.11+10-LTS" +IMAGE_TYPE="JDK" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/__pycache__/datetime_parse.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/__pycache__/datetime_parse.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cdb24ebf1afe430a9b6e32ebc2215291bd36bb70 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/__pycache__/datetime_parse.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/__pycache__/decorator.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/__pycache__/decorator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f629d12b2bb1fd34e5e79f940298d9d9d3ac1858 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/__pycache__/decorator.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/__pycache__/env_settings.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/__pycache__/env_settings.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ed16910cb1437fa415cca3861c87f855afa89f1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/__pycache__/env_settings.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/__pycache__/error_wrappers.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/__pycache__/error_wrappers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c025453c2803a15cf69b5db5d3636121f391b6ea Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/__pycache__/error_wrappers.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/__pycache__/errors.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/__pycache__/errors.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a8f16edeb2a11dd2df46341c048fcfa8169e597 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/__pycache__/errors.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/__pycache__/fields.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/__pycache__/fields.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..afeef5ce63862e814f8aaaba41887790dd24c01f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/__pycache__/fields.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pygments-2.20.0.dist-info/INSTALLER b/micromamba_root/envs/pytorch_env/Lib/site-packages/pygments-2.20.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/pygments-2.20.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pygments-2.20.0.dist-info/METADATA b/micromamba_root/envs/pytorch_env/Lib/site-packages/pygments-2.20.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..3dea62032aff25161bb49b38d237376f18fbaec1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/pygments-2.20.0.dist-info/METADATA @@ -0,0 +1,57 @@ +Metadata-Version: 2.4 +Name: Pygments +Version: 2.20.0 +Summary: Pygments is a syntax highlighting package written in Python. +Project-URL: Homepage, https://pygments.org +Project-URL: Documentation, https://pygments.org/docs +Project-URL: Source, https://github.com/pygments/pygments +Project-URL: Bug Tracker, https://github.com/pygments/pygments/issues +Project-URL: Changelog, https://github.com/pygments/pygments/blob/master/CHANGES +Author-email: Georg Brandl +Maintainer: Matthäus G. Chajdas +Maintainer-email: Georg Brandl , Jean Abou Samra +License-Expression: BSD-2-Clause +License-File: AUTHORS +License-File: LICENSE +Keywords: syntax highlighting +Classifier: Development Status :: 6 - Mature +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: End Users/Desktop +Classifier: Intended Audience :: System Administrators +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Text Processing :: Filters +Classifier: Topic :: Utilities +Requires-Python: >=3.9 +Provides-Extra: plugins +Provides-Extra: windows-terminal +Requires-Dist: colorama>=0.4.6; extra == 'windows-terminal' +Description-Content-Type: text/x-rst + +Pygments +~~~~~~~~ + +Pygments is a syntax highlighting package written in Python. + +It is a generic syntax highlighter suitable for use in code hosting, forums, +wikis or other applications that need to prettify source code. Highlights +are: + +* a wide range of over 500 languages and other text formats is supported +* special attention is paid to details, increasing quality by a fair amount +* support for new languages and formats are added easily +* a number of output formats, presently HTML, LaTeX, RTF, SVG, all image + formats that PIL supports and ANSI sequences +* it is usable as a command-line tool and as a library + +Copyright 2006-present by the Pygments team, see ``AUTHORS``. +Licensed under the BSD, see ``LICENSE`` for details. diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pygments-2.20.0.dist-info/RECORD b/micromamba_root/envs/pytorch_env/Lib/site-packages/pygments-2.20.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..a49f0b332187f1a78291d45ac9614c427fae199f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/pygments-2.20.0.dist-info/RECORD @@ -0,0 +1,686 @@ +../../Scripts/pygmentize.exe,sha256=ZOs7iDytAHCakL1eBGXmnSPbjP--pCZWVRlC8zHVSSE,108364 +pygments-2.20.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +pygments-2.20.0.dist-info/METADATA,sha256=4FKPUbMEJ_rpRyNmK6Yi-NjbKk2NPxNlaY1npSRQqEU,2476 +pygments-2.20.0.dist-info/RECORD,, +pygments-2.20.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87 +pygments-2.20.0.dist-info/entry_points.txt,sha256=uUXw-XhMKBEX4pWcCtpuTTnPhL3h7OEE2jWi51VQsa8,53 +pygments-2.20.0.dist-info/licenses/AUTHORS,sha256=DbYDpfRJn2kMRCVHf_ZkwWbaMl06zDtajU3j2wckQ9A,10873 +pygments-2.20.0.dist-info/licenses/LICENSE,sha256=qdZvHVJt8C4p3Oc0NtNOVuhjL0bCdbvf_HBWnogvnxc,1331 +pygments/__init__.py,sha256=ZzpnXpvnv0c7r_OIS8h7UeaESqYNKMy__pV7KCiWXxw,2962 +pygments/__main__.py,sha256=QZWj0T6TTRsqr-w-0YvVILo1DyAvzzydGCRONwdEzqo,351 +pygments/__pycache__/__init__.cpython-311.pyc,, +pygments/__pycache__/__main__.cpython-311.pyc,, +pygments/__pycache__/cmdline.cpython-311.pyc,, +pygments/__pycache__/console.cpython-311.pyc,, +pygments/__pycache__/filter.cpython-311.pyc,, +pygments/__pycache__/formatter.cpython-311.pyc,, +pygments/__pycache__/lexer.cpython-311.pyc,, +pygments/__pycache__/modeline.cpython-311.pyc,, +pygments/__pycache__/plugin.cpython-311.pyc,, +pygments/__pycache__/regexopt.cpython-311.pyc,, +pygments/__pycache__/scanner.cpython-311.pyc,, +pygments/__pycache__/sphinxext.cpython-311.pyc,, +pygments/__pycache__/style.cpython-311.pyc,, +pygments/__pycache__/token.cpython-311.pyc,, +pygments/__pycache__/unistring.cpython-311.pyc,, +pygments/__pycache__/util.cpython-311.pyc,, +pygments/cmdline.py,sha256=_dOnrta_2GIe8Jg-1Y0pb5vWi8L6QTiJzyoTuHrYrbM,23542 +pygments/console.py,sha256=C189JAwhC1Qh0AKgshzb1wVDzFqBnv1VZ45kTEDIO30,1721 +pygments/filter.py,sha256=1dnbkq2AdC3AkHt3DaXwnOkTBLChl1kR6naSLwnr_tc,1913 +pygments/filters/__init__.py,sha256=03ZYdIYmxnWCh7gNXD7lEQ869Df4kzHnOGM44iJxan8,40349 +pygments/filters/__pycache__/__init__.cpython-311.pyc,, +pygments/formatter.py,sha256=PTBnTW0EHke2vzlAKuvHJkj3-_CMj8duIx-3yVUie-o,4369 +pygments/formatters/__init__.py,sha256=qPG4q5cuaZRGBglmEJVLP4SDv43QI3tAUskj30M-mOY,5352 +pygments/formatters/__pycache__/__init__.cpython-311.pyc,, +pygments/formatters/__pycache__/_mapping.cpython-311.pyc,, +pygments/formatters/__pycache__/bbcode.cpython-311.pyc,, +pygments/formatters/__pycache__/groff.cpython-311.pyc,, +pygments/formatters/__pycache__/html.cpython-311.pyc,, +pygments/formatters/__pycache__/img.cpython-311.pyc,, +pygments/formatters/__pycache__/irc.cpython-311.pyc,, +pygments/formatters/__pycache__/latex.cpython-311.pyc,, +pygments/formatters/__pycache__/other.cpython-311.pyc,, +pygments/formatters/__pycache__/pangomarkup.cpython-311.pyc,, +pygments/formatters/__pycache__/rtf.cpython-311.pyc,, +pygments/formatters/__pycache__/svg.cpython-311.pyc,, +pygments/formatters/__pycache__/terminal.cpython-311.pyc,, +pygments/formatters/__pycache__/terminal256.cpython-311.pyc,, +pygments/formatters/_mapping.py,sha256=1Cw37FuQlNacnxRKmtlPX4nyLoX9_ttko5ZwscNUZZ4,4176 +pygments/formatters/bbcode.py,sha256=lvG1REZJv0pM6VMe-QwLSuo0Yl1Ra_X51wh93fW8A2k,3299 +pygments/formatters/groff.py,sha256=anF3fNbDYwwOlppOUoKTZg4FzzPbZrE4jcJCMd49_1g,5085 +pygments/formatters/html.py,sha256=qe4P6qIV462HkZovS8s5xKKyYXPQQvUjz6Wj7HX1CxY,36053 +pygments/formatters/img.py,sha256=41uSY0pKg9VmKJYrHuavCVgg0z-mg81p28QEMktwf1o,23304 +pygments/formatters/irc.py,sha256=hdOqAvF02bI8CY8_tutnUptBZpWEBLzVAqS4_YA0tew,4907 +pygments/formatters/latex.py,sha256=cQmE1Nj4E9q5N0XQJBqpc6dLtu5UNOtYq3plPyCX1Hk,19261 +pygments/formatters/other.py,sha256=Hq6qY4POBZ_llAWRr1gzSO9UoeYPONlLMBK60RkW4bg,4989 +pygments/formatters/pangomarkup.py,sha256=L4jU6oO18UqEMqXeN5FkPtkisXrXuXq9wcecgy_6dzo,2209 +pygments/formatters/rtf.py,sha256=YQYW8NTrB4XfOjLbQzutyD4j35TimFNZ0T39dET9DOo,11924 +pygments/formatters/svg.py,sha256=oksXT-ZnTHDsn1WtWgBs9V7qmKFswAKx7jV37tb2tYY,7141 +pygments/formatters/terminal.py,sha256=q7jLLanle33eCZkDr4CoHAN-dHBFf1DBhi4FcBQ8_1E,4629 +pygments/formatters/terminal256.py,sha256=PpA_oATHCih3UTjrbfKqIRUcvsyp_TeBaGw3kpIxeBA,11717 +pygments/lexer.py,sha256=gNMYzmdSkTNyWfqiLJ37oUd1KrN_dMXtsPyaX2-n9EA,35154 +pygments/lexers/__init__.py,sha256=G4dtqE5QMEAqoaaD1rwSZZeuqKhMyS4utlMz1szkrTg,12070 +pygments/lexers/__pycache__/__init__.cpython-311.pyc,, +pygments/lexers/__pycache__/_ada_builtins.cpython-311.pyc,, +pygments/lexers/__pycache__/_asy_builtins.cpython-311.pyc,, +pygments/lexers/__pycache__/_cl_builtins.cpython-311.pyc,, +pygments/lexers/__pycache__/_cocoa_builtins.cpython-311.pyc,, +pygments/lexers/__pycache__/_csound_builtins.cpython-311.pyc,, +pygments/lexers/__pycache__/_css_builtins.cpython-311.pyc,, +pygments/lexers/__pycache__/_googlesql_builtins.cpython-311.pyc,, +pygments/lexers/__pycache__/_julia_builtins.cpython-311.pyc,, +pygments/lexers/__pycache__/_lasso_builtins.cpython-311.pyc,, +pygments/lexers/__pycache__/_lilypond_builtins.cpython-311.pyc,, +pygments/lexers/__pycache__/_lua_builtins.cpython-311.pyc,, +pygments/lexers/__pycache__/_luau_builtins.cpython-311.pyc,, +pygments/lexers/__pycache__/_mapping.cpython-311.pyc,, +pygments/lexers/__pycache__/_mql_builtins.cpython-311.pyc,, +pygments/lexers/__pycache__/_mysql_builtins.cpython-311.pyc,, +pygments/lexers/__pycache__/_openedge_builtins.cpython-311.pyc,, +pygments/lexers/__pycache__/_php_builtins.cpython-311.pyc,, +pygments/lexers/__pycache__/_postgres_builtins.cpython-311.pyc,, +pygments/lexers/__pycache__/_qlik_builtins.cpython-311.pyc,, +pygments/lexers/__pycache__/_scheme_builtins.cpython-311.pyc,, +pygments/lexers/__pycache__/_scilab_builtins.cpython-311.pyc,, +pygments/lexers/__pycache__/_sourcemod_builtins.cpython-311.pyc,, +pygments/lexers/__pycache__/_sql_builtins.cpython-311.pyc,, +pygments/lexers/__pycache__/_stan_builtins.cpython-311.pyc,, +pygments/lexers/__pycache__/_stata_builtins.cpython-311.pyc,, +pygments/lexers/__pycache__/_tsql_builtins.cpython-311.pyc,, +pygments/lexers/__pycache__/_usd_builtins.cpython-311.pyc,, +pygments/lexers/__pycache__/_vbscript_builtins.cpython-311.pyc,, +pygments/lexers/__pycache__/_vim_builtins.cpython-311.pyc,, +pygments/lexers/__pycache__/actionscript.cpython-311.pyc,, +pygments/lexers/__pycache__/ada.cpython-311.pyc,, +pygments/lexers/__pycache__/agile.cpython-311.pyc,, +pygments/lexers/__pycache__/algebra.cpython-311.pyc,, +pygments/lexers/__pycache__/ambient.cpython-311.pyc,, +pygments/lexers/__pycache__/amdgpu.cpython-311.pyc,, +pygments/lexers/__pycache__/ampl.cpython-311.pyc,, +pygments/lexers/__pycache__/apdlexer.cpython-311.pyc,, +pygments/lexers/__pycache__/apl.cpython-311.pyc,, +pygments/lexers/__pycache__/archetype.cpython-311.pyc,, +pygments/lexers/__pycache__/arrow.cpython-311.pyc,, +pygments/lexers/__pycache__/arturo.cpython-311.pyc,, +pygments/lexers/__pycache__/asc.cpython-311.pyc,, +pygments/lexers/__pycache__/asm.cpython-311.pyc,, +pygments/lexers/__pycache__/asn1.cpython-311.pyc,, +pygments/lexers/__pycache__/automation.cpython-311.pyc,, +pygments/lexers/__pycache__/bare.cpython-311.pyc,, +pygments/lexers/__pycache__/basic.cpython-311.pyc,, +pygments/lexers/__pycache__/bdd.cpython-311.pyc,, +pygments/lexers/__pycache__/berry.cpython-311.pyc,, +pygments/lexers/__pycache__/bibtex.cpython-311.pyc,, +pygments/lexers/__pycache__/blueprint.cpython-311.pyc,, +pygments/lexers/__pycache__/boa.cpython-311.pyc,, +pygments/lexers/__pycache__/bqn.cpython-311.pyc,, +pygments/lexers/__pycache__/business.cpython-311.pyc,, +pygments/lexers/__pycache__/c_cpp.cpython-311.pyc,, +pygments/lexers/__pycache__/c_like.cpython-311.pyc,, +pygments/lexers/__pycache__/capnproto.cpython-311.pyc,, +pygments/lexers/__pycache__/carbon.cpython-311.pyc,, +pygments/lexers/__pycache__/cddl.cpython-311.pyc,, +pygments/lexers/__pycache__/chapel.cpython-311.pyc,, +pygments/lexers/__pycache__/clean.cpython-311.pyc,, +pygments/lexers/__pycache__/codeql.cpython-311.pyc,, +pygments/lexers/__pycache__/comal.cpython-311.pyc,, +pygments/lexers/__pycache__/compiled.cpython-311.pyc,, +pygments/lexers/__pycache__/configs.cpython-311.pyc,, +pygments/lexers/__pycache__/console.cpython-311.pyc,, +pygments/lexers/__pycache__/cplint.cpython-311.pyc,, +pygments/lexers/__pycache__/crystal.cpython-311.pyc,, +pygments/lexers/__pycache__/csound.cpython-311.pyc,, +pygments/lexers/__pycache__/css.cpython-311.pyc,, +pygments/lexers/__pycache__/d.cpython-311.pyc,, +pygments/lexers/__pycache__/dalvik.cpython-311.pyc,, +pygments/lexers/__pycache__/data.cpython-311.pyc,, +pygments/lexers/__pycache__/dax.cpython-311.pyc,, +pygments/lexers/__pycache__/devicetree.cpython-311.pyc,, +pygments/lexers/__pycache__/diff.cpython-311.pyc,, +pygments/lexers/__pycache__/dns.cpython-311.pyc,, +pygments/lexers/__pycache__/dotnet.cpython-311.pyc,, +pygments/lexers/__pycache__/dsls.cpython-311.pyc,, +pygments/lexers/__pycache__/dylan.cpython-311.pyc,, +pygments/lexers/__pycache__/ecl.cpython-311.pyc,, +pygments/lexers/__pycache__/eiffel.cpython-311.pyc,, +pygments/lexers/__pycache__/elm.cpython-311.pyc,, +pygments/lexers/__pycache__/elpi.cpython-311.pyc,, +pygments/lexers/__pycache__/email.cpython-311.pyc,, +pygments/lexers/__pycache__/erlang.cpython-311.pyc,, +pygments/lexers/__pycache__/esoteric.cpython-311.pyc,, +pygments/lexers/__pycache__/ezhil.cpython-311.pyc,, +pygments/lexers/__pycache__/factor.cpython-311.pyc,, +pygments/lexers/__pycache__/fantom.cpython-311.pyc,, +pygments/lexers/__pycache__/felix.cpython-311.pyc,, +pygments/lexers/__pycache__/fift.cpython-311.pyc,, +pygments/lexers/__pycache__/floscript.cpython-311.pyc,, +pygments/lexers/__pycache__/forth.cpython-311.pyc,, +pygments/lexers/__pycache__/fortran.cpython-311.pyc,, +pygments/lexers/__pycache__/foxpro.cpython-311.pyc,, +pygments/lexers/__pycache__/freefem.cpython-311.pyc,, +pygments/lexers/__pycache__/func.cpython-311.pyc,, +pygments/lexers/__pycache__/functional.cpython-311.pyc,, +pygments/lexers/__pycache__/futhark.cpython-311.pyc,, +pygments/lexers/__pycache__/gcodelexer.cpython-311.pyc,, +pygments/lexers/__pycache__/gdscript.cpython-311.pyc,, +pygments/lexers/__pycache__/gleam.cpython-311.pyc,, +pygments/lexers/__pycache__/go.cpython-311.pyc,, +pygments/lexers/__pycache__/grammar_notation.cpython-311.pyc,, +pygments/lexers/__pycache__/graph.cpython-311.pyc,, +pygments/lexers/__pycache__/graphics.cpython-311.pyc,, +pygments/lexers/__pycache__/graphql.cpython-311.pyc,, +pygments/lexers/__pycache__/graphviz.cpython-311.pyc,, +pygments/lexers/__pycache__/gsql.cpython-311.pyc,, +pygments/lexers/__pycache__/hare.cpython-311.pyc,, +pygments/lexers/__pycache__/haskell.cpython-311.pyc,, +pygments/lexers/__pycache__/haxe.cpython-311.pyc,, +pygments/lexers/__pycache__/hdl.cpython-311.pyc,, +pygments/lexers/__pycache__/hexdump.cpython-311.pyc,, +pygments/lexers/__pycache__/html.cpython-311.pyc,, +pygments/lexers/__pycache__/idl.cpython-311.pyc,, +pygments/lexers/__pycache__/igor.cpython-311.pyc,, +pygments/lexers/__pycache__/inferno.cpython-311.pyc,, +pygments/lexers/__pycache__/installers.cpython-311.pyc,, +pygments/lexers/__pycache__/int_fiction.cpython-311.pyc,, +pygments/lexers/__pycache__/iolang.cpython-311.pyc,, +pygments/lexers/__pycache__/j.cpython-311.pyc,, +pygments/lexers/__pycache__/javascript.cpython-311.pyc,, +pygments/lexers/__pycache__/jmespath.cpython-311.pyc,, +pygments/lexers/__pycache__/jslt.cpython-311.pyc,, +pygments/lexers/__pycache__/json5.cpython-311.pyc,, +pygments/lexers/__pycache__/jsonnet.cpython-311.pyc,, +pygments/lexers/__pycache__/jsx.cpython-311.pyc,, +pygments/lexers/__pycache__/julia.cpython-311.pyc,, +pygments/lexers/__pycache__/jvm.cpython-311.pyc,, +pygments/lexers/__pycache__/kuin.cpython-311.pyc,, +pygments/lexers/__pycache__/kusto.cpython-311.pyc,, +pygments/lexers/__pycache__/ldap.cpython-311.pyc,, +pygments/lexers/__pycache__/lean.cpython-311.pyc,, +pygments/lexers/__pycache__/lilypond.cpython-311.pyc,, +pygments/lexers/__pycache__/lisp.cpython-311.pyc,, +pygments/lexers/__pycache__/macaulay2.cpython-311.pyc,, +pygments/lexers/__pycache__/make.cpython-311.pyc,, +pygments/lexers/__pycache__/maple.cpython-311.pyc,, +pygments/lexers/__pycache__/markup.cpython-311.pyc,, +pygments/lexers/__pycache__/math.cpython-311.pyc,, +pygments/lexers/__pycache__/matlab.cpython-311.pyc,, +pygments/lexers/__pycache__/maxima.cpython-311.pyc,, +pygments/lexers/__pycache__/meson.cpython-311.pyc,, +pygments/lexers/__pycache__/mime.cpython-311.pyc,, +pygments/lexers/__pycache__/minecraft.cpython-311.pyc,, +pygments/lexers/__pycache__/mips.cpython-311.pyc,, +pygments/lexers/__pycache__/ml.cpython-311.pyc,, +pygments/lexers/__pycache__/modeling.cpython-311.pyc,, +pygments/lexers/__pycache__/modula2.cpython-311.pyc,, +pygments/lexers/__pycache__/mojo.cpython-311.pyc,, +pygments/lexers/__pycache__/monte.cpython-311.pyc,, +pygments/lexers/__pycache__/mosel.cpython-311.pyc,, +pygments/lexers/__pycache__/ncl.cpython-311.pyc,, +pygments/lexers/__pycache__/nimrod.cpython-311.pyc,, +pygments/lexers/__pycache__/nit.cpython-311.pyc,, +pygments/lexers/__pycache__/nix.cpython-311.pyc,, +pygments/lexers/__pycache__/numbair.cpython-311.pyc,, +pygments/lexers/__pycache__/oberon.cpython-311.pyc,, +pygments/lexers/__pycache__/objective.cpython-311.pyc,, +pygments/lexers/__pycache__/ooc.cpython-311.pyc,, +pygments/lexers/__pycache__/openscad.cpython-311.pyc,, +pygments/lexers/__pycache__/other.cpython-311.pyc,, +pygments/lexers/__pycache__/parasail.cpython-311.pyc,, +pygments/lexers/__pycache__/parsers.cpython-311.pyc,, +pygments/lexers/__pycache__/pascal.cpython-311.pyc,, +pygments/lexers/__pycache__/pawn.cpython-311.pyc,, +pygments/lexers/__pycache__/pddl.cpython-311.pyc,, +pygments/lexers/__pycache__/perl.cpython-311.pyc,, +pygments/lexers/__pycache__/phix.cpython-311.pyc,, +pygments/lexers/__pycache__/php.cpython-311.pyc,, +pygments/lexers/__pycache__/pointless.cpython-311.pyc,, +pygments/lexers/__pycache__/pony.cpython-311.pyc,, +pygments/lexers/__pycache__/praat.cpython-311.pyc,, +pygments/lexers/__pycache__/procfile.cpython-311.pyc,, +pygments/lexers/__pycache__/prolog.cpython-311.pyc,, +pygments/lexers/__pycache__/promql.cpython-311.pyc,, +pygments/lexers/__pycache__/prql.cpython-311.pyc,, +pygments/lexers/__pycache__/ptx.cpython-311.pyc,, +pygments/lexers/__pycache__/python.cpython-311.pyc,, +pygments/lexers/__pycache__/q.cpython-311.pyc,, +pygments/lexers/__pycache__/qlik.cpython-311.pyc,, +pygments/lexers/__pycache__/qvt.cpython-311.pyc,, +pygments/lexers/__pycache__/r.cpython-311.pyc,, +pygments/lexers/__pycache__/rdf.cpython-311.pyc,, +pygments/lexers/__pycache__/rebol.cpython-311.pyc,, +pygments/lexers/__pycache__/rego.cpython-311.pyc,, +pygments/lexers/__pycache__/rell.cpython-311.pyc,, +pygments/lexers/__pycache__/resource.cpython-311.pyc,, +pygments/lexers/__pycache__/ride.cpython-311.pyc,, +pygments/lexers/__pycache__/rita.cpython-311.pyc,, +pygments/lexers/__pycache__/rnc.cpython-311.pyc,, +pygments/lexers/__pycache__/roboconf.cpython-311.pyc,, +pygments/lexers/__pycache__/robotframework.cpython-311.pyc,, +pygments/lexers/__pycache__/ruby.cpython-311.pyc,, +pygments/lexers/__pycache__/rust.cpython-311.pyc,, +pygments/lexers/__pycache__/sas.cpython-311.pyc,, +pygments/lexers/__pycache__/savi.cpython-311.pyc,, +pygments/lexers/__pycache__/scdoc.cpython-311.pyc,, +pygments/lexers/__pycache__/scripting.cpython-311.pyc,, +pygments/lexers/__pycache__/sgf.cpython-311.pyc,, +pygments/lexers/__pycache__/shell.cpython-311.pyc,, +pygments/lexers/__pycache__/sieve.cpython-311.pyc,, +pygments/lexers/__pycache__/slash.cpython-311.pyc,, +pygments/lexers/__pycache__/smalltalk.cpython-311.pyc,, +pygments/lexers/__pycache__/smithy.cpython-311.pyc,, +pygments/lexers/__pycache__/smv.cpython-311.pyc,, +pygments/lexers/__pycache__/snobol.cpython-311.pyc,, +pygments/lexers/__pycache__/solidity.cpython-311.pyc,, +pygments/lexers/__pycache__/soong.cpython-311.pyc,, +pygments/lexers/__pycache__/sophia.cpython-311.pyc,, +pygments/lexers/__pycache__/special.cpython-311.pyc,, +pygments/lexers/__pycache__/spice.cpython-311.pyc,, +pygments/lexers/__pycache__/sql.cpython-311.pyc,, +pygments/lexers/__pycache__/srcinfo.cpython-311.pyc,, +pygments/lexers/__pycache__/stata.cpython-311.pyc,, +pygments/lexers/__pycache__/supercollider.cpython-311.pyc,, +pygments/lexers/__pycache__/tablegen.cpython-311.pyc,, +pygments/lexers/__pycache__/tact.cpython-311.pyc,, +pygments/lexers/__pycache__/tal.cpython-311.pyc,, +pygments/lexers/__pycache__/tcl.cpython-311.pyc,, +pygments/lexers/__pycache__/teal.cpython-311.pyc,, +pygments/lexers/__pycache__/templates.cpython-311.pyc,, +pygments/lexers/__pycache__/teraterm.cpython-311.pyc,, +pygments/lexers/__pycache__/testing.cpython-311.pyc,, +pygments/lexers/__pycache__/text.cpython-311.pyc,, +pygments/lexers/__pycache__/textedit.cpython-311.pyc,, +pygments/lexers/__pycache__/textfmts.cpython-311.pyc,, +pygments/lexers/__pycache__/theorem.cpython-311.pyc,, +pygments/lexers/__pycache__/thingsdb.cpython-311.pyc,, +pygments/lexers/__pycache__/tlb.cpython-311.pyc,, +pygments/lexers/__pycache__/tls.cpython-311.pyc,, +pygments/lexers/__pycache__/tnt.cpython-311.pyc,, +pygments/lexers/__pycache__/trafficscript.cpython-311.pyc,, +pygments/lexers/__pycache__/typoscript.cpython-311.pyc,, +pygments/lexers/__pycache__/typst.cpython-311.pyc,, +pygments/lexers/__pycache__/ul4.cpython-311.pyc,, +pygments/lexers/__pycache__/unicon.cpython-311.pyc,, +pygments/lexers/__pycache__/urbi.cpython-311.pyc,, +pygments/lexers/__pycache__/usd.cpython-311.pyc,, +pygments/lexers/__pycache__/varnish.cpython-311.pyc,, +pygments/lexers/__pycache__/verification.cpython-311.pyc,, +pygments/lexers/__pycache__/verifpal.cpython-311.pyc,, +pygments/lexers/__pycache__/vip.cpython-311.pyc,, +pygments/lexers/__pycache__/vyper.cpython-311.pyc,, +pygments/lexers/__pycache__/web.cpython-311.pyc,, +pygments/lexers/__pycache__/webassembly.cpython-311.pyc,, +pygments/lexers/__pycache__/webidl.cpython-311.pyc,, +pygments/lexers/__pycache__/webmisc.cpython-311.pyc,, +pygments/lexers/__pycache__/wgsl.cpython-311.pyc,, +pygments/lexers/__pycache__/whiley.cpython-311.pyc,, +pygments/lexers/__pycache__/wowtoc.cpython-311.pyc,, +pygments/lexers/__pycache__/wren.cpython-311.pyc,, +pygments/lexers/__pycache__/x10.cpython-311.pyc,, +pygments/lexers/__pycache__/xorg.cpython-311.pyc,, +pygments/lexers/__pycache__/yang.cpython-311.pyc,, +pygments/lexers/__pycache__/yara.cpython-311.pyc,, +pygments/lexers/__pycache__/zig.cpython-311.pyc,, +pygments/lexers/_ada_builtins.py,sha256=dZb-lodsSM6L5emLlgLg-rClm2HumvnHK72CetnSRdA,1546 +pygments/lexers/_asy_builtins.py,sha256=zg54fGhgzWXQUk6-qZ6OW5GTL9d4OrnB8SJQkjrD0xs,27290 +pygments/lexers/_cl_builtins.py,sha256=oBF00ZkJyD14LkYuR603EDFIMyitkze12aT7UzDYLYs,13997 +pygments/lexers/_cocoa_builtins.py,sha256=ab6sq-iy5LapE1cNYyl8PJXLg6EINXx-lMRbwERdKYs,105176 +pygments/lexers/_csound_builtins.py,sha256=wuWiQjmEMhaVvsV8b_efsebgU0YKIoMC0ECpOavTCIM,18417 +pygments/lexers/_css_builtins.py,sha256=qhmC4tRGG53zvzMQE1qn794LvbVODRtVacxWCP3kIkA,12449 +pygments/lexers/_googlesql_builtins.py,sha256=mGfOGuKKjZoHHAAZq6Hpc68x0qKycx-SX_wGDScSOYI,16135 +pygments/lexers/_julia_builtins.py,sha256=u6v0yAzZjqUENjiIQ5qMfcso1r_6ERqGbj3aHwFnyqA,11886 +pygments/lexers/_lasso_builtins.py,sha256=YO_c_f05ZoxspHxCR3oWQCpZhbAJUzBJBhVuuwTjr5c,134513 +pygments/lexers/_lilypond_builtins.py,sha256=-_4i4gpgDgcFHvaZMJL2s1rI9dSNY2ZC6vO6ul7Hml0,115114 +pygments/lexers/_lua_builtins.py,sha256=MsDV9sEbJngKoXSZu0xXawGvd6XjFf125nuXBNoffdU,8111 +pygments/lexers/_luau_builtins.py,sha256=YLUj2bcZ0Cb0SBkIlNXWHFGDUFkpddOJx-ukrZx1cMc,958 +pygments/lexers/_mapping.py,sha256=YbQJB1eqeGk7ol5NgMMPLrD3VGdTwgQCl3TvLwtxwxA,70758 +pygments/lexers/_mql_builtins.py,sha256=CkcvMyHYh4U5rGgV6AgShxRnTOv0tmqEbOiVdpaFLqs,24716 +pygments/lexers/_mysql_builtins.py,sha256=SqiVYVVirtnN4lSgtfeRPxtVpcumjUvvUq9n8JObuQ4,26876 +pygments/lexers/_openedge_builtins.py,sha256=AzF1o6eAkMc6vnvmeVqNnUZUVijzbNYkjzrUdtCQe3M,49401 +pygments/lexers/_php_builtins.py,sha256=9g-WLT3qbSGolQJB_4PS6FW_r7HVXBWvI5OWxKtbwok,108054 +pygments/lexers/_postgres_builtins.py,sha256=QGg2mBTThgv4LdXjFm5wrKaKnCU9DubmJi6lXB7y2Mg,13346 +pygments/lexers/_qlik_builtins.py,sha256=3ZkCSDjtxSxXDI9erigWTLSUct_ap_W0LqfZjFeKQYI,12598 +pygments/lexers/_scheme_builtins.py,sha256=O3BRtt5suTESbZ_bSReQ6D0r0G_Sq_i4wCcUkdUrdS0,32567 +pygments/lexers/_scilab_builtins.py,sha256=E33R0mknNc-5eZ9Ugu7u7Av_vUxAaQoMTtdx3MceyxU,52414 +pygments/lexers/_sourcemod_builtins.py,sha256=8qspLxCLsfN9J7N0SWZRNs0A-qJOIGRBAJaNMeWaOBQ,26780 +pygments/lexers/_sql_builtins.py,sha256=fLphonB6wv6Oit8zanJiExgRoLvZoFW4l9lNH-PTYvw,6770 +pygments/lexers/_stan_builtins.py,sha256=sIoONg4TjLkGN7Ab0tZB1HM7tQ071_Z2c41n9lXZl04,16623 +pygments/lexers/_stata_builtins.py,sha256=ymh8GxEca6eSCgHnqsLqsi9OrfRqYnt5O8yBeinJ7DE,27230 +pygments/lexers/_tsql_builtins.py,sha256=Mw6UnMByju0U-OBgT8af3A4utfrS00Tn5lDnaxBtj9c,15463 +pygments/lexers/_usd_builtins.py,sha256=SGp_ePf2VuktrFV59q6df4mTyxZV7AZYs0TJFSWoBAI,1661 +pygments/lexers/_vbscript_builtins.py,sha256=TFtyc11yvpD_OlNrrFbcCOJoUYkWMq3EeHHCpw_zJNc,4228 +pygments/lexers/_vim_builtins.py,sha256=bB6kdLFM33uoY-sAtsRuUZOoccaa4gDAsdFg4WAEsoU,57069 +pygments/lexers/actionscript.py,sha256=kbHhoDl7JjVzREMv1UuxYBRJaPrxHDkmEAC5COmOIVw,11737 +pygments/lexers/ada.py,sha256=m2O7dYzJVc3iuSgaC-Ti-Gh3CG-JmpZit_DPZpu1IIM,5356 +pygments/lexers/agile.py,sha256=Du-vjnGZEPHuE40XxTMO-XLt56pYcIaKIAxIwcYHFH0,899 +pygments/lexers/algebra.py,sha256=2iQSGxfVuBXBHAJdzbbPvtpvROYTfxfMivDagk9yfh8,10032 +pygments/lexers/ambient.py,sha256=8Nk8WX4qrId9zj_zgjJBuFT40yQXG2OXxFhhF3R00g8,2608 +pygments/lexers/amdgpu.py,sha256=KMDLdb-1aK9RJaNsSkPyiU3DQE_HdjBF0paw_yiJMRA,1726 +pygments/lexers/ampl.py,sha256=IKuMVE6aXsa4S6qpuc_DvEsJmJpyKDNga09BPFLvYxA,4179 +pygments/lexers/apdlexer.py,sha256=puSpLBWevciSc8G0wg2Y_yQIoGgqPes0UBkpFImqvO4,30803 +pygments/lexers/apl.py,sha256=-jhPYsBVT4ckL7CZmukIZNi6tfaJJbBk2vutld372rs,3407 +pygments/lexers/archetype.py,sha256=buhH2WHtxBowy_KD5SPm5vgHpmLoKMdV9tgMs_bE4xU,11577 +pygments/lexers/arrow.py,sha256=e6mb3Ix4jL7TMGNUpk8iRbJy_VF7VY2J0VUknlo1EvA,3567 +pygments/lexers/arturo.py,sha256=GkklOaiEJTOz8E0zdxd_hd1zXwv7lYgp8IJl7uh13hg,11417 +pygments/lexers/asc.py,sha256=CvFSi7FYDW6eu-5oiKGc0MN3aF1XVZDoFI5-3mHpBDk,1696 +pygments/lexers/asm.py,sha256=jHJ3CDtvHgu4hX4kVvvJyciFLWM6FAYFDPG_zjBTyrc,42219 +pygments/lexers/asn1.py,sha256=MLakOeBFkdhKKr42eHFzonpGITEJxR_God8vqjWPva4,4267 +pygments/lexers/automation.py,sha256=gdSYslkW9sblDcvMeK1ay15rb9vRuK56pPOJzdxlIvg,19834 +pygments/lexers/bare.py,sha256=AdqL9Z20nd0bhNGWielLhAHej6V8_8m1OWUkCOrSBx8,3023 +pygments/lexers/basic.py,sha256=NqNxIeHhjBUtenwCdJ88WWEE3N7a16DA9g1_D1mdmF0,27992 +pygments/lexers/bdd.py,sha256=KeuOzXBLJRxxM2gV7aMuYsdV_aJFHyBuF8ptBpWxD5M,1644 +pygments/lexers/berry.py,sha256=vIfT4sBtm6ao64WdNkJTVJmS00BiFdEWvb3obBXBeX8,3212 +pygments/lexers/bibtex.py,sha256=sgfFqXyNyCxROHIe8C0gre69rzbADALnpDtTaqHfSas,4814 +pygments/lexers/blueprint.py,sha256=dW-L5bFIiWxRPDashee2EOYmXIRHdwuCZ1y3iN-a6_0,6191 +pygments/lexers/boa.py,sha256=VqYF1Yg_XdDA5tK_Eiuo1rr7ediBsKUTpB6xza_B5d4,3924 +pygments/lexers/bqn.py,sha256=se4W2XPsNiT36z0Am9X5F4yNLrQvMI5X8miY6R9SEM8,3674 +pygments/lexers/business.py,sha256=MXYomjQiYaTmnUgjQ7LUxjcU1i2iVDjZdXPTeqOlDjM,28348 +pygments/lexers/c_cpp.py,sha256=2ViQoLY22Y6xdzXDmwz30rMcij7EemNq4vpTEsfl7sg,18321 +pygments/lexers/c_like.py,sha256=rafLNQqcEbf-97VpDtSIQZSSmdiMD4oBYeEs7DZyByg,32024 +pygments/lexers/capnproto.py,sha256=kc3rT95GkeQmrW1LeP5HMVb7Nk8sqXkW6OJkkWIHYbA,2177 +pygments/lexers/carbon.py,sha256=_M-0YbofjZMrJIaiXKoT6wpkd3_6fFq-OdSZ7V961I4,3214 +pygments/lexers/cddl.py,sha256=7Wri2q2yKexWo0CD7s2c7AoCAMbrwyEE6f_gz5B6x1Y,5079 +pygments/lexers/chapel.py,sha256=SvZXNJijW0greFToDHZQ0yeo4_3niyTx31Iz_yLctck,5159 +pygments/lexers/clean.py,sha256=_oV3Tbmrpl3S1phPMS6gyMWyGZGj6Wy0q8adpf5vunY,6421 +pygments/lexers/codeql.py,sha256=hAX51uWeG5Zk9JhXSnOxPMaznFOpaX4ZnZHZ2krrPGk,2579 +pygments/lexers/comal.py,sha256=0fcTyV5h36zPlxoQPWWGet2yaYi5ESXiFpx6EbsqP00,3182 +pygments/lexers/compiled.py,sha256=PRimy7eb2weP7X6bEukz1JaSLuQAETO34K7maHLGbxA,1429 +pygments/lexers/configs.py,sha256=YDBIWV_R2SiRb0Cbxol-S8RRieDfAg_YcThc1BmZ90I,50925 +pygments/lexers/console.py,sha256=MrTIkXDYQ71z0yDepwbpO9WwXPQRPHAFAOvt_ngscxU,4183 +pygments/lexers/cplint.py,sha256=wPs_Zh0OJ2_UUeF9_mu_r-X_65DJSWMCTKOmOyjWLz8,1392 +pygments/lexers/crystal.py,sha256=k8Xy8TpfGKTPvsP1WikxILScILD8iXZ5qceLZopsLYE,15757 +pygments/lexers/csound.py,sha256=7KHoJv8wtuIe9dques4mFFkQLULcGQ23dgZ_KBd0f_k,17001 +pygments/lexers/css.py,sha256=OVjsd0Kn9pNH6iltS4ikjy9nnilPlCVx-VAZ26n3UJ8,26439 +pygments/lexers/d.py,sha256=ee5oImP1BcHYZ93UwXoHIzw6BztgR3WCCv3ksu2J-o0,9923 +pygments/lexers/dalvik.py,sha256=0f5mB5y8g0l1ID2liJ_5qM2NjyR_SBs7ckuIDeNbbj8,4609 +pygments/lexers/data.py,sha256=MhLXoZXYMZFmmKlqL8RV5zp-eUwVb0yFzsyzXYrpKiw,27049 +pygments/lexers/dax.py,sha256=N-5fxukBfFtFCT2LJoyg1VJsfldWHxXKLY3ZPLnPrig,8101 +pygments/lexers/devicetree.py,sha256=Tig-tTSrpmGzbGxN2ka4MMTiC344roav9A4hoc9o_kw,4826 +pygments/lexers/diff.py,sha256=-627lmuYpJ2uUVUM_orVGgXJGXIBGSVHbmlqflCEeaM,5385 +pygments/lexers/dns.py,sha256=ElzSN3IEoRs1g6iWMnzVIV8H0x9WSEF1wBjm2a0ByxE,3894 +pygments/lexers/dotnet.py,sha256=GmoaOxSoITkYdAUaVJ0Z1RQa6MvcRxh1gQ3XxgEs4X8,39444 +pygments/lexers/dsls.py,sha256=a6Jdv3w1aF3vpQJrnF32MNHAl6pEZkkeGB1cYv-x2Hw,36753 +pygments/lexers/dylan.py,sha256=fi8mSyni4dnGP5x1crE6BKNqLWJs4dDWdmkur-TbbNc,10412 +pygments/lexers/ecl.py,sha256=XJ66PU9EjkXJwA4f1OfC0RdfP49v8N62RZXnFVVAYNo,6374 +pygments/lexers/eiffel.py,sha256=m2eVPDG9J-VXieCeOy0S7zHPjiFHQB9F6bOIy-K3MDQ,2693 +pygments/lexers/elm.py,sha256=Xj3HlbUTEkEUFwhem4NCujx55tQ2TS61_Kcf6BCPHAI,3155 +pygments/lexers/elpi.py,sha256=RZqAVzdxfA_BqBmtMHj8ATw5f9e24SKL-QeO14QuKk4,7904 +pygments/lexers/email.py,sha256=NPlGc2L6F3KWWDop3ZOJGpUM6LDnOEqKZj1YJG3vP2M,4807 +pygments/lexers/erlang.py,sha256=2aUlVBVFtQdR2QISsDeKTOPjGrV7r1ckyXL17KJot9c,19150 +pygments/lexers/esoteric.py,sha256=tmJ9Pa1wYtYgR6yDqgp3zDYuXPFzXw7SLTHOH_eE3p0,10503 +pygments/lexers/ezhil.py,sha256=tbGYtGnqZAB8ffnyPdeMMJHtKYJ7OAciUFRrR_8QpXM,3275 +pygments/lexers/factor.py,sha256=HBUqNcwd4VplYw30ScuC8YgdipFAYiqjRgWsyT0s4xQ,19533 +pygments/lexers/fantom.py,sha256=w9IU1x61Codd7Oxv5DpvVlkVPn_bfvVLiP8Ae3660zM,10234 +pygments/lexers/felix.py,sha256=DvPOs_Em6fFtUBQCaZWWHWgnvAFeBrDe97Cy9XyQ8ps,9658 +pygments/lexers/fift.py,sha256=Q9OLJivp4ngqFso7APCvX85h-ghdbp9ZqpP8GKHws1M,1647 +pygments/lexers/floscript.py,sha256=TcyuCiv9bAb89x1_7_Zq6nUhsdsHAF2DPsKZ6m1W1NU,2670 +pygments/lexers/forth.py,sha256=4e0OCfJGcElkQrHInmQMucvsI9dljuPx4FYg38dyjno,7196 +pygments/lexers/fortran.py,sha256=ouvOHdMbj56j40Nrj21WCRf4rNKpuwphxmtlUVsnzhc,10385 +pygments/lexers/foxpro.py,sha256=nV8yyES39QoFmTNlM8xl3MteOsvmt6yV1l6x6xnXqIU,26298 +pygments/lexers/freefem.py,sha256=ZmZLIYLXtCK2kWqGzBmrkp7ychOy7vgfaorafUkUl1I,26916 +pygments/lexers/func.py,sha256=ZjOerj3njJcaGnHWc_npWjxb4D5O-udxBRK7RLHEibU,3703 +pygments/lexers/functional.py,sha256=4m9JlAnfpXxSkQQIrNOob2VTwin6hPLAqWuhv9aVkAg,697 +pygments/lexers/futhark.py,sha256=mCU2yvloJF5LN7uRE_8rCVqA8HAINny04HXVxjSiM4g,3746 +pygments/lexers/gcodelexer.py,sha256=t8JMWaaDjWZwdGiRGwrpsYtfjKTmibwlRyOLCiJZ8qw,877 +pygments/lexers/gdscript.py,sha256=VNOwd7KcDREvoBAfw66GjxxQygPsHH2akdzRbPNKqoQ,7569 +pygments/lexers/gleam.py,sha256=Jx6LnUpWV9pmjdSYLUMt16c3UamZ-v5X6CcuEhWxf-8,2395 +pygments/lexers/go.py,sha256=ynHVStw2XUJFlUiTS4UqY65fLkvcJBMNzoYtSNSl_BU,3786 +pygments/lexers/grammar_notation.py,sha256=ZGYcwhSvOolw1J7cA9Pc7hVpcIselaCgxwsvAf5yRgc,8046 +pygments/lexers/graph.py,sha256=X_IsdjxXZn5p9Dq4cLXyqwo4C8emcYA8NP6VZ9ZTBaU,4111 +pygments/lexers/graphics.py,sha256=IeruxvEQR1Wsu-YyLpAjkUnisLDzUrk2cd0xXrDCbjw,39148 +pygments/lexers/graphql.py,sha256=RWE_kfVUDEAnv_-SYyOi9IJUks61NvOakmUfWOlorzo,5604 +pygments/lexers/graphviz.py,sha256=DRNWwetEWasJDtiLkdqkKsQHDryJ5W80wUD2PE6oKCs,1937 +pygments/lexers/gsql.py,sha256=pzSj5Pd4vtNLES-pIdxaG0vOVTqUWE9UuOUw0RrY-oc,3993 +pygments/lexers/hare.py,sha256=eCrRPwcswXL-ZHTWNlhE1A05G9rxzS20_IqSddv2M9Y,2652 +pygments/lexers/haskell.py,sha256=sr5gq3U7xt0D2Bi41xdTsBaponX6otP1qPyRMCuxM7E,33323 +pygments/lexers/haxe.py,sha256=_MzQJTWx18kD9bP_sniBshKbtOZDRm4OZnifaOgw_aY,31169 +pygments/lexers/hdl.py,sha256=2jYX3fRWZ9mAZ_QER1WH58SvJaOdYQt0OmOxo3X2JK0,22741 +pygments/lexers/hexdump.py,sha256=VvYp_NTaE-6NUuSG4FMezwcjxbPnAz0fOWMzr3Y2Gm4,3656 +pygments/lexers/html.py,sha256=O6qkpyOylH2n1Zi1qzlmBsIEW31RfvzBn7jKTaAR2LQ,21999 +pygments/lexers/idl.py,sha256=W2QRH1j9LMaNvC5jb6MkP4dLYo_OQU6lQlCAlQveFH4,15452 +pygments/lexers/igor.py,sha256=Sv5EGBJeKy0UOyl6-GF3lBeeoWArVcMDJtQtl2RXRYo,31636 +pygments/lexers/inferno.py,sha256=cjVMyOg6jhJ6nYX333Z6KaCCeS0pNVHv4WTxyFGY8Tg,3138 +pygments/lexers/installers.py,sha256=ioK2JUPSJk9vcsoe3NASvMt-paXd1_Nn3e8WmaqJ7CE,14494 +pygments/lexers/int_fiction.py,sha256=BUjvXilUiuMF-euXEQDzQZs45jn_aLs17eTKcfEptrI,56547 +pygments/lexers/iolang.py,sha256=kMUBUqVvdHlB79ez0pFZPRf0NgiEC2SdtYUwdjnbE90,1908 +pygments/lexers/j.py,sha256=56qUbs1C7wKdZ6-WpNnxHntNqsxWroqiO7keI2yoR1o,4856 +pygments/lexers/javascript.py,sha256=muyCVZQAsXbhT7IHZkoqAkI5myhRaHze6JMAR4zILNs,63246 +pygments/lexers/jmespath.py,sha256=726PDpRr1g2Ky_x5pZORhbXofXxkfr5HXQ8eHMhX5xg,2085 +pygments/lexers/jslt.py,sha256=UOVw1J3uK-hVRWomoFK2jMS_yeuo5iqga-LhXUJI660,3703 +pygments/lexers/json5.py,sha256=GyeZ58AxKkJJiiH7JuPmakDZXropa6bDkFRguJHifqU,2505 +pygments/lexers/jsonnet.py,sha256=_T7Y16sW7nFuAoGFuyWUKCrUyJAC4FTWZVoeSt0mTXk,5639 +pygments/lexers/jsx.py,sha256=O0evHioyudtWLhVmAXRrIfkEd5KRiokgHu8l9_Kn8sM,2696 +pygments/lexers/julia.py,sha256=F0twMg0iLBNDdedsoJG4Rn5LoMciVu9cufyUVdxKQPY,11713 +pygments/lexers/jvm.py,sha256=cf5V7NOLIvB2s7RM9wghESYRCoCDyrGjRuPmY8bfGAw,72936 +pygments/lexers/kuin.py,sha256=n2lMina8SskpfA2KbPYQFwVJOSHgNYu10U5pz5YiajE,11408 +pygments/lexers/kusto.py,sha256=pyUfWLf9Q0Qwqu74DyPAbRh20lkPDLhxnExD1FVl8Z4,3480 +pygments/lexers/ldap.py,sha256=_ya4_InnSIRj-RYjGagWFZJDy1NdgQUocQzVWjiRp68,6554 +pygments/lexers/lean.py,sha256=qP_iwUQ7MJZ1C5s3KYBW8Wu6-uuVj4PAG3a2Ghjp99U,8588 +pygments/lexers/lilypond.py,sha256=o264ovGZFrcx8ZwpKRX-gjUECK1w5T8T0n6LoTjP92U,9755 +pygments/lexers/lisp.py,sha256=a5MGcmtrWTaeEj_5Uv8YMODr3dVV6s1v1_SMBh_Ch9Q,157903 +pygments/lexers/macaulay2.py,sha256=hLNDs1TdubudvqqovYN6a4Ne9JjnU4FvNE6EE2hPn8Q,34139 +pygments/lexers/make.py,sha256=wAV0KRRXTAFMliLfAKXDihQIE2VAVUvWjFZ-yuM7a08,7834 +pygments/lexers/maple.py,sha256=OBjODNLgqanyw522CE7n9thZctWi47Uua2hPBfj7KF4,7963 +pygments/lexers/markup.py,sha256=4TMRfujXvOE9xiWwTiT_fq1lau4dKSoXYac1hWMLYRs,65264 +pygments/lexers/math.py,sha256=Nspl6IZtCyh9egiYUahboWSmy4cJCVZUBxyVnCuF1ag,698 +pygments/lexers/matlab.py,sha256=QYVBdA-IRNcuWggBJNC9lpq3jgX_1w9GQwpv907VfZM,133030 +pygments/lexers/maxima.py,sha256=ha-f-JzGkjggAr5kxmVq7_uJTCcpHstQWnsLHYIhNwU,2718 +pygments/lexers/meson.py,sha256=ZpNVp7lSHwJHEj7pwXlGcy9Lftdc6MMgJiOoY2TnfM8,4345 +pygments/lexers/mime.py,sha256=l5BsFkad3agJ6KDg_IHI6nU0Ao0Y9EcwjYoYP8vQD-g,7585 +pygments/lexers/minecraft.py,sha256=bBbMbqvsVgTfO7CBxf03oGP_qOAgrw06PSzH1QF7txs,13701 +pygments/lexers/mips.py,sha256=QpgBoMPzsk1t90cIF0W_EV-QZ8LwgTapS-fSISxZcFc,4659 +pygments/lexers/ml.py,sha256=shDPgWARTzTEhGDeblV7ZW2j6yZEeBiYqx2z24SDP7A,35393 +pygments/lexers/modeling.py,sha256=2_ucVFy7Z4yoKx90E9-ASI9t4t1LIoeQ3yHarhghz-c,13764 +pygments/lexers/modula2.py,sha256=dXW0KNFu3ETgABsPMsIhdJI0DKF-KWtT831FKsz2VXw,53075 +pygments/lexers/mojo.py,sha256=imOlg8mQCoKwi_rsuMiifZrzsAsSqT2KckCs_MV5uVE,24236 +pygments/lexers/monte.py,sha256=JTx-jSrFKlWRwA1qzhPd647ETGSElwhP4YMlVrfXyX8,6292 +pygments/lexers/mosel.py,sha256=HEYOmZiANhe9VdkTpBt7mhPi_tPGBUkVsnzTh2HVdVI,9300 +pygments/lexers/ncl.py,sha256=RZXkxOK-iHspLX_sFVT0wc5H6v-pa4kKghP79fJGQPQ,64002 +pygments/lexers/nimrod.py,sha256=L8Ww5CUaP-ojywoQZXnjC08m5Be64fBynSf5aWGIaPw,6416 +pygments/lexers/nit.py,sha256=xwu2P49Hu8YxEL7mgpV5WWFw6OYF1iJg9DVnc7H1SXk,2728 +pygments/lexers/nix.py,sha256=M2E-k--F7pneuMAOae9ag4srJsKhWJ1f1fRueO6PtKM,4424 +pygments/lexers/numbair.py,sha256=KZOw96Tj7Gly-f9F8NA-tdGd53SIt5UgbpokZsfnzWM,1761 +pygments/lexers/oberon.py,sha256=uH1FkPeXCfdd0IQ_--S8SHUNaf2dnjiQZjtIT-jxu4A,4216 +pygments/lexers/objective.py,sha256=KME-J0UL2HJYAk2fHNhf7ApQe4XF8GH6qGOvYA1wPS4,23300 +pygments/lexers/ooc.py,sha256=HEjWHdQDVk7tRb_TuEb1_C5qi-peJwwyYBVAhf49MS0,3005 +pygments/lexers/openscad.py,sha256=te2iL8VkfXul_PYXlz8UK3_QtMjdmNgt0YHCYEvdEtM,3703 +pygments/lexers/other.py,sha256=OAlXzsrVDUx4Ma25fyG98U5LaBEHyt-LJZ2IHvMJJWY,1766 +pygments/lexers/parasail.py,sha256=oPcs7fRYNkV0isPSRmw-2cPfMgzTtNPi6bJOm7vq-9o,2722 +pygments/lexers/parsers.py,sha256=g4tVvf36yhT_aH_b737o0o1joojcf-XckD2HdNoNbsQ,26598 +pygments/lexers/pascal.py,sha256=4dewXkwc12f_iiMfdNDqbxb_oqAEX2dCzb5VIZ62V54,30992 +pygments/lexers/pawn.py,sha256=adsa-7sPuPk7mO7lB08auabEpeZdNewVqTBg6FS8mCk,8256 +pygments/lexers/pddl.py,sha256=a8A2keCF9qNQvVZQirgBV5fH4u3cjrta8-eZJ8tsxmY,2992 +pygments/lexers/perl.py,sha256=uYMj6amZPawLf-KjICg9LLU5-ADKzqEYKqi7VXnvm0k,39195 +pygments/lexers/phix.py,sha256=nEWWt5-OoIDapw4IJ_cNL19Th8Ztt6OIQgeuogVed10,23252 +pygments/lexers/php.py,sha256=U6wmxPM-pS-SY1N3qdv0ebUDBxLH6-EFIFcatUvg74w,13171 +pygments/lexers/pointless.py,sha256=gNcuhhOY9cEpIPyGFjMh2DItNB1UD8CmjceXkDRModE,1977 +pygments/lexers/pony.py,sha256=HKqf5AngUOdXN1N1VvSg0jTj3NUAzGBOPdXwSFamvmM,3282 +pygments/lexers/praat.py,sha256=sfVAd7zfRsI-TcCouuYMWlcU8EBxAwJ4wkh0ZuNsZ34,12679 +pygments/lexers/procfile.py,sha256=fhRTtscyMMPcPbvzjxVtXix1mYlpO-4JuWUL7Db4ENI,1158 +pygments/lexers/prolog.py,sha256=4YvPZbAFLWNZMbZhvtIulWib0PQLA_TB93gjkNywFRA,12869 +pygments/lexers/promql.py,sha256=04fS_R6HBWhpKNe3WPp_QXgIdFvJr5p6KxStZYw7yHU,4741 +pygments/lexers/prql.py,sha256=XJhd8dpEWPBIKmQXx_09-z1NyotLXIskpuzX36HykHo,8750 +pygments/lexers/ptx.py,sha256=dEaNSReAjAymIwVM_MnbdY4hd3muK79q200hYwN72cw,4504 +pygments/lexers/python.py,sha256=79A_yJqjVHp_ZeS1rY8Pcc4cwZ_7-zI2WWkeUmZgUrA,54202 +pygments/lexers/q.py,sha256=2CbJYgRu8uz8wOSp5FMr086KCC7IjSRmIODVY0uKrCA,6939 +pygments/lexers/qlik.py,sha256=9b6Q-6jXeeraIRcWtsKsYWCOlBhfmjNzIN49pUvMR-I,3696 +pygments/lexers/qvt.py,sha256=rpT5oD4awEKMs3uBCbNlzY1zCz7AVeqM-BikLTQHo8k,6106 +pygments/lexers/r.py,sha256=hzgUUH9gCsqqwTG9eCt1JVMd9RW0dy6IY_jTvRntF-U,6477 +pygments/lexers/rdf.py,sha256=FM154fB1lxfOpSpeW6bWOVld5kJBgEuYyT9udt-EcK0,16063 +pygments/lexers/rebol.py,sha256=CQ3pMaAz64UMqiQVrYoREnOgjU5QPeF_H3aaHNdVRC8,18262 +pygments/lexers/rego.py,sha256=Yi0G4secTWOL7CUhLLCzJ9gA6SJzDJpPJNij3hXixC0,1751 +pygments/lexers/rell.py,sha256=0gZStI953aFjFMyMVX_UKfwZmzV3uj3Tnl_5F20BPx0,2487 +pygments/lexers/resource.py,sha256=RDEY7iSv2hgQ3V-I1DeOKVOumNKgFqbV2Me_9Y21o10,2930 +pygments/lexers/ride.py,sha256=1zg7kGYPKRIekyuZY3f6OVqRlXyrX-sR-tHEX1M9nz4,5038 +pygments/lexers/rita.py,sha256=fCNElPik6dDIZzGd96kKgdlY4Qqp_zVI87waTBHMBfg,1130 +pygments/lexers/rnc.py,sha256=PNfnnTlnZjNvvG33BNMCqPzdA9LZEYvDsGoaDd_2mn8,1975 +pygments/lexers/roboconf.py,sha256=l6BeJIS-ZAUb3zc5GEuVIb0edrRpPFmKdffEBx74Zxg,2077 +pygments/lexers/robotframework.py,sha256=8s1U7GldhzRPGR7d8_rMSG0ZJz9ZOm-LGqBTGILwt2U,18451 +pygments/lexers/ruby.py,sha256=BxndG-3gLg7wEGvICiNDAMygQR9Qs0xrmq7DwfoLvMs,22756 +pygments/lexers/rust.py,sha256=7qD3KGVir-tUWf_bPBt4EX8l9aIWe8TblMCFI75oorc,8263 +pygments/lexers/sas.py,sha256=9hmGYhmKo7ri9oCmZdsoEFMz6z3AwKD4LcTUIn52lYU,9459 +pygments/lexers/savi.py,sha256=HCllgBe3rzP_7-2b1hSUEbE2dYz08Iysxc6Dcxj3f2c,4881 +pygments/lexers/scdoc.py,sha256=9n64S-bO1dI4x-2Kzh2jrDM6gEmB5YI7ch6ndPB4-cw,2527 +pygments/lexers/scripting.py,sha256=c-i_cMFhYEHQZZbLgJn0jyiD52vWeZVxUK6wFV2Fib4,82959 +pygments/lexers/sgf.py,sha256=ya_sG4TOvDWwzEM6cIi40XSbhkTuHCqvo-uHnNYfi5Q,1988 +pygments/lexers/shell.py,sha256=si6MAn6S7pHfyX65NkwQdjxtLtEu1M4l7K2lUHvyzWw,36384 +pygments/lexers/sieve.py,sha256=CXR9S1nGeVTln2u5R600hxgkAmJFVVTTTBh_k3aw-pk,2517 +pygments/lexers/slash.py,sha256=molh5sNG8UtheHffQGjjHLxVtyg2oCp4B8cvgDyf004,8487 +pygments/lexers/smalltalk.py,sha256=q52NHegl3pjn1jMkJWA9J0nOA_A5VzUULZAPgb-6uNU,7207 +pygments/lexers/smithy.py,sha256=hqEImo4B-i0hddNo1r0k5eHLOlArtRW4W5PsLBdllk4,2662 +pygments/lexers/smv.py,sha256=D51In9Qr2nWFicYAOX_bJpeFgmJ3BUkEXnvXPmA04D4,2808 +pygments/lexers/snobol.py,sha256=BX_1VPUZi-ckKCYlF2sttQprF2bLUHOi8blhInFHv9s,2781 +pygments/lexers/solidity.py,sha256=pz0DZ0xiHwufhbQ9hdCPrHMjA7NMsa6hxZ1nO-A4Y3E,3166 +pygments/lexers/soong.py,sha256=TVqBJzJxLwCEDmb5Aix2_AVuZILYyPWcAzFbzINNQAM,2342 +pygments/lexers/sophia.py,sha256=MAkWLYxhHJNcc3UUzWD3VDLzVRbf6IAd2uz4q7DY3wI,3379 +pygments/lexers/special.py,sha256=8gpTiLICFNwIcahm282mi8Nqi_6gwYMsAfjJIM2Bq6k,3588 +pygments/lexers/spice.py,sha256=UcrjK2KJDDKSEgEOeLXTayqRwirWdsywrfH9MqwPPIY,2801 +pygments/lexers/sql.py,sha256=zz_TFZtf5R29cvkBFG1PDJ-0KKrY7FjA-RDky-gfNlk,41656 +pygments/lexers/srcinfo.py,sha256=MHj02VB7WP3AcoOz1WVYAqNM_3oFLjEaAda075kXVBU,1749 +pygments/lexers/stata.py,sha256=KojmkxWHlEk-HvmxI313a52nzH_JHNqfv6r3jJoFDy8,6418 +pygments/lexers/supercollider.py,sha256=H-qwP6sUaotemsXxuugpui6KnU3jtIdDfS3bGt3Jvh4,3700 +pygments/lexers/tablegen.py,sha256=ryuzw-ArLdvlY55YJBn6ebOzDo3L8UnbR5xcZB8xMso,4012 +pygments/lexers/tact.py,sha256=YbOWYNp302ZBPM5affzM4-CudJ4xRZyJb-_vSDCozCo,10812 +pygments/lexers/tal.py,sha256=xZYmhv8mBr-A3oeoFkcSP7nDbX1r21kKOnhsLTtL3bE,2907 +pygments/lexers/tcl.py,sha256=MXMAo2wCZeq5oR7VzsNbamawun_vMOk2gOEDnGk6yOc,5515 +pygments/lexers/teal.py,sha256=pgpPi9xWPumSr-heSpGBGDcU5s3qN0aFUj2maHLE3MM,3525 +pygments/lexers/templates.py,sha256=ndJMdue33qQ_thsortAra1fm_-szMN40S5bZXBLY54w,75734 +pygments/lexers/teraterm.py,sha256=YCdvILRq-FdOJ_HfiIkYVToH3c6I2QRbQoH17Q49Hx8,10045 +pygments/lexers/testing.py,sha256=GF5SpanGwjgKKoYari32SdtdOWWXXje8xVX5-ZzTjLg,10813 +pygments/lexers/text.py,sha256=yq6mOLz3PizKNMm4_Y8UHn9vEeBfqEY5W-3M7dk1jYs,1071 +pygments/lexers/textedit.py,sha256=V-Ijh0eULTWtx3S_6vT7JcyjQO-CNirpAbEpkczLGCE,7763 +pygments/lexers/textfmts.py,sha256=WSiJDzNKCcOsBoTU4NCYU33ti5ZHGi0Px29eGjT6pB0,15527 +pygments/lexers/theorem.py,sha256=c-eg6tIYWUbxSYgrOtLZfFxro4g91JcAIwrIJGLPooU,17903 +pygments/lexers/thingsdb.py,sha256=FNKjArS1vadHEN3ZXaZdDLqvcG59GbF6Ak5M8RMsTLU,6257 +pygments/lexers/tlb.py,sha256=vWsFq_MrIrzgG2q-qdzpcoNiv9KkNow4x9ebs9_HAwA,1453 +pygments/lexers/tls.py,sha256=GZ1lvZ8PUk1-LThq1KuiqSEnMqJVqiHo_A-16aKuJOc,1543 +pygments/lexers/tnt.py,sha256=MNYTfkix0x5L1pDV8V8zGLS7GU8z7bt-wpiBap2W09U,10459 +pygments/lexers/trafficscript.py,sha256=1Tawom6bKJM-u1kYey21xFaHep3D9kl62rV3RaHSvcI,1509 +pygments/lexers/typoscript.py,sha256=dWAuOYYk0X4xE_fxKgcXz-sMYlG2wxQR4m_d7PW2PYs,8335 +pygments/lexers/typst.py,sha256=ZtV37NCQCoSqEKrAhffuZtUp1kDahKQx8PxMLrR2G6k,7170 +pygments/lexers/ul4.py,sha256=joM-US0-2BEWRHHK6eyZ-Y--306YgbMrevMY0hg8QTY,10502 +pygments/lexers/unicon.py,sha256=9D-GilKOqIEaowGHmdvHRjhqyigRk320ARAr-G_snew,18628 +pygments/lexers/urbi.py,sha256=j87k6fe60kZdbJ6AJA4g9E0no1EP0bxJY06UVP0YgnU,6085 +pygments/lexers/usd.py,sha256=tP9kHPZUJcE_flPvKEsF7wTck4FuQW75S8ELh4IYJEI,3307 +pygments/lexers/varnish.py,sha256=INCtYbol1yV_NXMh51CMDZDacEHgiB3SmR3H5uW-Fkc,7476 +pygments/lexers/verification.py,sha256=QISJmmz7cmYaXZphW5so4PfdKJo0rdZWuj_de64mafk,3937 +pygments/lexers/verifpal.py,sha256=0iZTQWawF9f7lFZnFNPTwYRiu6L_25PtEI83tuCAmKY,2664 +pygments/lexers/vip.py,sha256=pM5xFoeu-2GPWqAVzZJe6xPYr6WJPlozVI5084SHQ80,5714 +pygments/lexers/vyper.py,sha256=rw2yD9c2L7yPtXqKPd0RdxJSZK-aJbW5jEa0gHfKEO0,5618 +pygments/lexers/web.py,sha256=YMrxoHlKlQwfFJlae9_T9F1Vp03YA7IWsmgqLzh6pgI,916 +pygments/lexers/webassembly.py,sha256=Y48VdBp8b4SI10PEt8biOm-gteYgmNc_bRR-KvulfnQ,5701 +pygments/lexers/webidl.py,sha256=MQMaZFskluB29lMGpiGP2f6fzoja4vV8FtoCGFQH6fM,10519 +pygments/lexers/webmisc.py,sha256=GnSTSHfsAUGy5DYF_qwFmMsyabnzTstaEG96Fub53fk,40567 +pygments/lexers/wgsl.py,sha256=vgDtY_q42TGRvcsyS7viSadU8D3eHvatfoCNNnEP0zE,11883 +pygments/lexers/whiley.py,sha256=MC2V7o1s7LIoLy0Fk-i8OymBoN0dpK2BPjIrdQwsnVk,4020 +pygments/lexers/wowtoc.py,sha256=XnLSSX7p_RkwZIzlmYXO873d4byX9-A3dfvzNL5Eocw,4079 +pygments/lexers/wren.py,sha256=2lhzwpS27xW6nERY_NeODgNN9X6mB7vl3odXSPngqY8,3232 +pygments/lexers/x10.py,sha256=77pAyohtv9PFwPvJPGgq-Vw8tEXo9Sny1MnTchFpTTI,1946 +pygments/lexers/xorg.py,sha256=LUKU91t1Opc3W_F64UGzx0nB-HqKlN3Cn_6tFzt5IYw,928 +pygments/lexers/yang.py,sha256=yIvwteHWBWL2-8zZscnCPJOnq3rMOXh5lxJujywA_Zo,4502 +pygments/lexers/yara.py,sha256=_ISzhko7v9AhJ-1cWINZSyG3my2vJOyFSHxSjm4VdTY,2430 +pygments/lexers/zig.py,sha256=q0tuplpRFAUSS29hg_XiRH22Ctve2EFAT5xo7TNAlrk,3975 +pygments/modeline.py,sha256=me8g5rySidvPtMBOrDy2O1sMqZd02lBHMY5KDZefUws,1008 +pygments/plugin.py,sha256=P6zIw-vkSQ0k1WKHrzbBTjpwlCZPbR-6Qe_dO9Bjdu0,1928 +pygments/regexopt.py,sha256=d2hTvazlow5zzZIOCVnfeEG2CY0GrY_igH1kCSSf7ow,3308 +pygments/scanner.py,sha256=DtoLi1pOKpNu-6jiakJpSQLUi_ep29SQQhv7oAwYWME,3095 +pygments/sphinxext.py,sha256=qmiWv5b7qq6bNUT2Y2wZejV2ImQmvtzGJFg6LcGENl0,7901 +pygments/style.py,sha256=Hrie373bgWU81ZNwVjZM-GNBoxBxVe1W1Tr3MzJLdkY,6411 +pygments/styles/__init__.py,sha256=2vgGKnbyt0nf_CSDEtMhHxppPSAPr2jafzl5FiXFuGs,2009 +pygments/styles/__pycache__/__init__.cpython-311.pyc,, +pygments/styles/__pycache__/_mapping.cpython-311.pyc,, +pygments/styles/__pycache__/abap.cpython-311.pyc,, +pygments/styles/__pycache__/algol.cpython-311.pyc,, +pygments/styles/__pycache__/algol_nu.cpython-311.pyc,, +pygments/styles/__pycache__/arduino.cpython-311.pyc,, +pygments/styles/__pycache__/autumn.cpython-311.pyc,, +pygments/styles/__pycache__/borland.cpython-311.pyc,, +pygments/styles/__pycache__/bw.cpython-311.pyc,, +pygments/styles/__pycache__/coffee.cpython-311.pyc,, +pygments/styles/__pycache__/colorful.cpython-311.pyc,, +pygments/styles/__pycache__/default.cpython-311.pyc,, +pygments/styles/__pycache__/dracula.cpython-311.pyc,, +pygments/styles/__pycache__/emacs.cpython-311.pyc,, +pygments/styles/__pycache__/friendly.cpython-311.pyc,, +pygments/styles/__pycache__/friendly_grayscale.cpython-311.pyc,, +pygments/styles/__pycache__/fruity.cpython-311.pyc,, +pygments/styles/__pycache__/gh_dark.cpython-311.pyc,, +pygments/styles/__pycache__/gruvbox.cpython-311.pyc,, +pygments/styles/__pycache__/igor.cpython-311.pyc,, +pygments/styles/__pycache__/inkpot.cpython-311.pyc,, +pygments/styles/__pycache__/lightbulb.cpython-311.pyc,, +pygments/styles/__pycache__/lilypond.cpython-311.pyc,, +pygments/styles/__pycache__/lovelace.cpython-311.pyc,, +pygments/styles/__pycache__/manni.cpython-311.pyc,, +pygments/styles/__pycache__/material.cpython-311.pyc,, +pygments/styles/__pycache__/monokai.cpython-311.pyc,, +pygments/styles/__pycache__/murphy.cpython-311.pyc,, +pygments/styles/__pycache__/native.cpython-311.pyc,, +pygments/styles/__pycache__/nord.cpython-311.pyc,, +pygments/styles/__pycache__/onedark.cpython-311.pyc,, +pygments/styles/__pycache__/paraiso_dark.cpython-311.pyc,, +pygments/styles/__pycache__/paraiso_light.cpython-311.pyc,, +pygments/styles/__pycache__/pastie.cpython-311.pyc,, +pygments/styles/__pycache__/perldoc.cpython-311.pyc,, +pygments/styles/__pycache__/rainbow_dash.cpython-311.pyc,, +pygments/styles/__pycache__/rrt.cpython-311.pyc,, +pygments/styles/__pycache__/sas.cpython-311.pyc,, +pygments/styles/__pycache__/solarized.cpython-311.pyc,, +pygments/styles/__pycache__/staroffice.cpython-311.pyc,, +pygments/styles/__pycache__/stata_dark.cpython-311.pyc,, +pygments/styles/__pycache__/stata_light.cpython-311.pyc,, +pygments/styles/__pycache__/tango.cpython-311.pyc,, +pygments/styles/__pycache__/trac.cpython-311.pyc,, +pygments/styles/__pycache__/vim.cpython-311.pyc,, +pygments/styles/__pycache__/vs.cpython-311.pyc,, +pygments/styles/__pycache__/xcode.cpython-311.pyc,, +pygments/styles/__pycache__/zenburn.cpython-311.pyc,, +pygments/styles/_mapping.py,sha256=6lovFUE29tz6EsV3XYY4hgozJ7q1JL7cfO3UOlgnS8w,3312 +pygments/styles/abap.py,sha256=T7Ad121Kjz8ZbuphyhulULwXyvXubSS6Czc0MDOFiJ8,752 +pygments/styles/algol.py,sha256=6v6ZXLxPJsm_1qPqOu5ihAuWhVk644NdPXPcZqiOTTI,2265 +pygments/styles/algol_nu.py,sha256=581Lf5db303g7zDb7z-VlvGlFNpbXMIlAnrRBxtjGts,2286 +pygments/styles/arduino.py,sha256=oFF5gjfbQNBigKxFhC7giUIHWl0ieCshhsm9UxCIzqg,4560 +pygments/styles/autumn.py,sha256=P9IX5utjDvdJgevM0kNGwE-wvVysRh1lgMkjO1dhDDE,2198 +pygments/styles/borland.py,sha256=V8qTD8SrS0wLohp2udIirlijbHfPoIlWZkYpqxSdkSw,1614 +pygments/styles/bw.py,sha256=e4Fo6Kyax2aRhqKsjsqvi2CW6lkU9QnjKoPrESZAj-I,1409 +pygments/styles/coffee.py,sha256=0jxdctCEKbR1AqzA59fFQK4sVBdErrRkGCUn6fPF4sg,2311 +pygments/styles/colorful.py,sha256=opkfOcjFTtDn9Fty6ogM7okFMB6bA0iR0VtTdBPE9NE,2835 +pygments/styles/default.py,sha256=WFLDucKJS_ac5Jqutmglbz4ITc4jTTQEOnqLIMpSttA,2591 +pygments/styles/dracula.py,sha256=H-EM1WM3Ixd2OBY9bzoObKl4IzdmhirfDVFbJ9Wsi0Q,2185 +pygments/styles/emacs.py,sha256=iEYWPgQrDQk4RdDf8-g7j4mtoFRzo2xcKvZE1ys9mJU,2538 +pygments/styles/friendly.py,sha256=S43XMczW53tKftmarEL4-nTroPVdN6k8fbNrINzR_QU,2607 +pygments/styles/friendly_grayscale.py,sha256=el2E804DEkKZ6ApXt3N5FTmHAkIhqkJj-omhE1E8mdE,2831 +pygments/styles/fruity.py,sha256=mrNDixp39QIoitRBo-yMOr8tnYLAwGd0EIMw2A6Gd8g,1327 +pygments/styles/gh_dark.py,sha256=yb4EOBAYsQ9g5IGEOqyZ5LKI-MUbwz32l9WB5EcMLaA,3593 +pygments/styles/gruvbox.py,sha256=_QZtRq9y1s3NYADHqek-DXELQqueOnVDXvWJ_1aTGgo,3390 +pygments/styles/igor.py,sha256=QO_M5-Z1xIxVnusEU4LZr4VT--nTERVt-cpfbnOv4yk,740 +pygments/styles/inkpot.py,sha256=bJvNWikqnAWLjx2AH4t_tW4jR0TsrUyVFXFVPAfOgkM,2407 +pygments/styles/lightbulb.py,sha256=CnDv1mF1X5k1msVvRS_diR4tkp06E_jg0tK9cdHEFCQ,3175 +pygments/styles/lilypond.py,sha256=gSCiazPPWfR_9-BV5BYHe6-2gSor4vOHnz3nyFQI2QA,2069 +pygments/styles/lovelace.py,sha256=vZ-S9tS-QUOwfA0RHYBhSTRE3h1ZU-bZnuMW7O6ksyw,3181 +pygments/styles/manni.py,sha256=dpsJC1Zees0e9IcWirqWuSzQxwD0jIbjhFquM23dmWM,2446 +pygments/styles/material.py,sha256=eyyAaJgp1Fnjl4-_D39_l1wH5CW4W0VWScQ3Q0jtAgU,4204 +pygments/styles/monokai.py,sha256=3CwJJm_YVGibzFi8nhK_b5d4cNzgV8z-L6RzC1UVA7Q,5187 +pygments/styles/murphy.py,sha256=HsPd80nObb3Ov3-7yJQbnJr3z9mCyz30Pjn_nkWkMYo,2808 +pygments/styles/native.py,sha256=oazEJUbuaHqqOZR5vx-jIhTPIw7dC6QZnKxW-xLr7fs,2046 +pygments/styles/nord.py,sha256=t7fZj04LUgsLaHpio66FqOGMKb7a2VC3teUlmInPfRg,5394 +pygments/styles/onedark.py,sha256=UXrMzVvA9OVP7OhCQ5gL0CaZrk5jo_I84HJm7LEN5GQ,2126 +pygments/styles/paraiso_dark.py,sha256=rx5_j4gnZRy2j-3hAhFmWpnjnd-Vfz3Z7fcwEXRUGm0,5665 +pygments/styles/paraiso_light.py,sha256=iERjbYRemqgsisv_9TjanBig4bJ_-80xRz5B5puhMc0,5671 +pygments/styles/pastie.py,sha256=mnKebFiJ2do9A_wTPq4tKtgw-TQqpb0lP3kNbemQ2to,2528 +pygments/styles/perldoc.py,sha256=-e1T4QBEQNE_l17RYW-WBowNprg2uL_hFjhSDcaMiDM,2233 +pygments/styles/rainbow_dash.py,sha256=YP2HPVXJLmOy8Yz8p8u5GbkAyuKxLlNmu6ITZBMa1Mc,2393 +pygments/styles/rrt.py,sha256=vs4pnWwmMIQR0eGczp06AYazsYiR0KFcRiRUzSf3rXc,1295 +pygments/styles/sas.py,sha256=ER-JjZgU2wEJWk5K06iHAFPjVYD1iMkvjjE0rlNOt2Y,1443 +pygments/styles/solarized.py,sha256=VdtLYhQ7xDj_iTHP_Ekr6rAdMcE3fRSrglngVSal63M,4250 +pygments/styles/staroffice.py,sha256=peExkIBqPkRhqXFpW99n49t6pMwehI_pDYVUmQwkgdA,834 +pygments/styles/stata_dark.py,sha256=N6imWykqHoT5drOn-sVRUzt1AZMKG3HHU-Q7LKz2d50,1260 +pygments/styles/stata_light.py,sha256=YW7ih4teXoEuUHImOK2rGSCVxfnj43tlcKPXUsrDkRg,1292 +pygments/styles/tango.py,sha256=Af0WVTxpH_cUdHr_ua69JDijTLI5aG1RmBTF7o2KTgk,7140 +pygments/styles/trac.py,sha256=-h5iU-LjSmt-dQ7y5jXwJ5LQ9ABR5QD5RlPRjhnzmv8,1984 +pygments/styles/vim.py,sha256=dWqCVC2YT45dLSpMTwLBPkKYgRsT1-cFf7ZHoc2PQpA,2022 +pygments/styles/vs.py,sha256=7HJehhtiHE5nibjC3r3X-aYHBm5BccL33LgO_4anEiU,1133 +pygments/styles/xcode.py,sha256=HmB6aPkxvmo4za5DijhLb5AXSyv6UbWnwOUoRUNBaZA,1507 +pygments/styles/zenburn.py,sha256=Ax7iBbMzvVQNTpT3YdMwCEkL-nIXnpr60aVrR4Lpa6o,2206 +pygments/token.py,sha256=DVil5T2ltHkTgQTUYy1dMtgyigjavCs1ypE4Qf2CrGo,6229 +pygments/unistring.py,sha256=Z4w4HfOVUhueCURRkfhAqQ2b-69UzkhY4xuHevYEy5g,63211 +pygments/util.py,sha256=zk935tJSpwSA9zxNmV1TuhcEP0MfboXiRZSGQnLPEqk,10046 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pygments-2.20.0.dist-info/WHEEL b/micromamba_root/envs/pytorch_env/Lib/site-packages/pygments-2.20.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..b1b94fd58e7e9ed0ef3449473bc48de68afcc3fe --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/pygments-2.20.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.29.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pygments-2.20.0.dist-info/entry_points.txt b/micromamba_root/envs/pytorch_env/Lib/site-packages/pygments-2.20.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..15498e35f53320bd5e1de176928daabf26be0109 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/pygments-2.20.0.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[console_scripts] +pygmentize = pygments.cmdline:main diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pygments/__main__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/pygments/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..818bfc3ae6ac4b79e029f714c56101ab2b1076ea --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/pygments/__main__.py @@ -0,0 +1,17 @@ +""" + pygments.__main__ + ~~~~~~~~~~~~~~~~~ + + Main entry point for ``python -m pygments``. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +import sys +import pygments.cmdline + +try: + sys.exit(pygments.cmdline.main(sys.argv)) +except KeyboardInterrupt: + sys.exit(1) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf-6.11.0.dist-info/INSTALLER b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf-6.11.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf-6.11.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf-6.11.0.dist-info/METADATA b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf-6.11.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..7614ce603bd3f2847a4d76a54bccbb2b29510c2c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf-6.11.0.dist-info/METADATA @@ -0,0 +1,172 @@ +Metadata-Version: 2.4 +Name: pypdf +Version: 6.11.0 +Summary: A pure-python PDF library capable of splitting, merging, cropping, and transforming PDF files +Author-email: Mathieu Fenniak +Maintainer: stefan6419846 +Maintainer-email: Martin Thoma +Requires-Python: >=3.9 +Description-Content-Type: text/markdown +License-Expression: BSD-3-Clause +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Operating System :: OS Independent +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Typing :: Typed +License-File: LICENSE +Requires-Dist: typing_extensions >= 4.0; python_version < '3.11' +Requires-Dist: cryptography>3.0 ; extra == "crypto" +Requires-Dist: PyCryptodome ; extra == "cryptodome" +Requires-Dist: flit ; extra == "dev" +Requires-Dist: pip-tools ; extra == "dev" +Requires-Dist: pre-commit ; extra == "dev" +Requires-Dist: pytest-cov ; extra == "dev" +Requires-Dist: pytest-socket ; extra == "dev" +Requires-Dist: pytest-timeout ; extra == "dev" +Requires-Dist: pytest-xdist ; extra == "dev" +Requires-Dist: wheel ; extra == "dev" +Requires-Dist: myst_parser ; extra == "docs" +Requires-Dist: sphinx ; extra == "docs" +Requires-Dist: sphinx_rtd_theme ; extra == "docs" +Requires-Dist: fonttools ; extra == "fonts" +Requires-Dist: cryptography>3.0 ; extra == "full" +Requires-Dist: fonttools ; extra == "full" +Requires-Dist: Pillow>=8.0.0 ; extra == "full" +Requires-Dist: Pillow>=8.0.0 ; extra == "image" +Project-URL: Bug Reports, https://github.com/py-pdf/pypdf/issues +Project-URL: Changelog, https://pypdf.readthedocs.io/en/latest/meta/CHANGELOG.html +Project-URL: Documentation, https://pypdf.readthedocs.io/en/latest/ +Project-URL: Source, https://github.com/py-pdf/pypdf +Provides-Extra: crypto +Provides-Extra: cryptodome +Provides-Extra: dev +Provides-Extra: docs +Provides-Extra: fonts +Provides-Extra: full +Provides-Extra: image + +[![PyPI version](https://badge.fury.io/py/pypdf.svg)](https://badge.fury.io/py/pypdf) +[![Python Support](https://img.shields.io/pypi/pyversions/pypdf.svg)](https://pypi.org/project/pypdf/) +[![](https://img.shields.io/badge/-documentation-green)](https://pypdf.readthedocs.io/en/stable/) +[![GitHub last commit](https://img.shields.io/github/last-commit/py-pdf/pypdf)](https://github.com/py-pdf/pypdf) +[![codecov](https://codecov.io/gh/py-pdf/pypdf/branch/main/graph/badge.svg?token=id42cGNZ5Z)](https://codecov.io/gh/py-pdf/pypdf) + +# pypdf + +pypdf is a free and open-source pure-python PDF library capable of splitting, +[merging](https://pypdf.readthedocs.io/en/stable/user/merging-pdfs.html), +[cropping, and transforming](https://pypdf.readthedocs.io/en/stable/user/cropping-and-transforming.html) +the pages of PDF files. It can also add +custom data, viewing options, and +[passwords](https://pypdf.readthedocs.io/en/stable/user/encryption-decryption.html) +to PDF files. pypdf can +[retrieve text](https://pypdf.readthedocs.io/en/stable/user/extract-text.html) +and +[metadata](https://pypdf.readthedocs.io/en/stable/user/metadata.html) +from PDFs as well. + +See [pdfly](https://github.com/py-pdf/pdfly) for a CLI application that uses pypdf to interact with PDFs. + +## Installation + +Install pypdf using pip: + +``` +pip install pypdf +``` + +For using pypdf with AES encryption or decryption, install extra dependencies: + +``` +pip install pypdf[crypto] +``` + +> **NOTE**: `pypdf` 3.1.0 and above include significant improvements compared to +> previous versions. Please refer to [the migration +> guide](https://pypdf.readthedocs.io/en/latest/user/migration-1-to-2.html) for +> more information. + +## Usage + +```python +from pypdf import PdfReader + +reader = PdfReader("example.pdf") +number_of_pages = len(reader.pages) +page = reader.pages[0] +text = page.extract_text() +``` + +pypdf can do a lot more, e.g. splitting, merging, reading and creating annotations, decrypting and encrypting. Check out the +[documentation](https://pypdf.readthedocs.io/en/stable/) for additional usage +examples! + +For questions and answers, visit +[StackOverflow](https://stackoverflow.com/questions/tagged/pypdf) +(tagged with [pypdf](https://stackoverflow.com/questions/tagged/pypdf)). + +## Contributions + +Maintaining pypdf is a collaborative effort. You can support the project by +writing documentation, helping to narrow down issues, and submitting code. +See the [CONTRIBUTING.md](https://github.com/py-pdf/pypdf/blob/main/CONTRIBUTING.md) file for more information. + +### Q&A + +The experience pypdf users have covers the whole range from beginner to expert. You can contribute to the pypdf community by answering questions +on [StackOverflow](https://stackoverflow.com/questions/tagged/pypdf), +helping in [discussions](https://github.com/py-pdf/pypdf/discussions), +and asking users who report issues for [MCVE](https://stackoverflow.com/help/minimal-reproducible-example)'s (Code + example PDF!). + + +### Issues + +A good bug ticket includes a MCVE - a minimal complete verifiable example. +For pypdf, this means that you must upload a PDF that causes the bug to occur +as well as the code you're executing with all of the output. Use +`print(pypdf.__version__)` to tell us which version you're using. + +### Code + +All code contributions are welcome, but smaller ones have a better chance to +get included in a timely manner. Adding unit tests for new features or test +cases for bugs you've fixed help us to ensure that the Pull Request (PR) is fine. + +pypdf includes a test suite which can be executed with `pytest`: + +```bash +$ pytest +===================== test session starts ===================== +platform linux -- Python 3.6.15, pytest-7.0.1, pluggy-1.0.0 +rootdir: /home/moose/GitHub/Martin/pypdf +plugins: cov-3.0.0 +collected 233 items + +tests/test_basic_features.py .. [ 0%] +tests/test_constants.py . [ 1%] +tests/test_filters.py .................x..... [ 11%] +tests/test_generic.py ................................. [ 25%] +............. [ 30%] +tests/test_javascript.py .. [ 31%] +tests/test_merger.py . [ 32%] +tests/test_page.py ......................... [ 42%] +tests/test_pagerange.py ................ [ 49%] +tests/test_papersizes.py .................. [ 57%] +tests/test_reader.py .................................. [ 72%] +............... [ 78%] +tests/test_utils.py .................... [ 87%] +tests/test_workflows.py .......... [ 91%] +tests/test_writer.py ................. [ 98%] +tests/test_xmp.py ... [100%] + +========== 232 passed, 1 xfailed, 1 warning in 4.52s ========== +``` + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf-6.11.0.dist-info/RECORD b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf-6.11.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..bb8520c2315b05296654cd53b8a0f3e4fc20895b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf-6.11.0.dist-info/RECORD @@ -0,0 +1,117 @@ +pypdf-6.11.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +pypdf-6.11.0.dist-info/METADATA,sha256=CtshuoZJKOHMmxTvHuhCwjxzYRaFMUM2nQPr4PfaquM,7229 +pypdf-6.11.0.dist-info/RECORD,, +pypdf-6.11.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pypdf-6.11.0.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82 +pypdf-6.11.0.dist-info/licenses/LICENSE,sha256=qXrCMOXzPvEKU2eoUOsB-R8aCwZONHQsd5TSKUVX9SQ,1605 +pypdf/__init__.py,sha256=YS_1ZrQ3jBPHsRgMstqJrAts3lUApj_lMOMK5qiLG5w,1283 +pypdf/__pycache__/__init__.cpython-311.pyc,, +pypdf/__pycache__/_cmap.cpython-311.pyc,, +pypdf/__pycache__/_doc_common.cpython-311.pyc,, +pypdf/__pycache__/_encryption.cpython-311.pyc,, +pypdf/__pycache__/_font.cpython-311.pyc,, +pypdf/__pycache__/_page.cpython-311.pyc,, +pypdf/__pycache__/_page_labels.cpython-311.pyc,, +pypdf/__pycache__/_protocols.cpython-311.pyc,, +pypdf/__pycache__/_reader.cpython-311.pyc,, +pypdf/__pycache__/_utils.cpython-311.pyc,, +pypdf/__pycache__/_version.cpython-311.pyc,, +pypdf/__pycache__/_writer.cpython-311.pyc,, +pypdf/__pycache__/constants.cpython-311.pyc,, +pypdf/__pycache__/errors.cpython-311.pyc,, +pypdf/__pycache__/filters.cpython-311.pyc,, +pypdf/__pycache__/pagerange.cpython-311.pyc,, +pypdf/__pycache__/papersizes.cpython-311.pyc,, +pypdf/__pycache__/types.cpython-311.pyc,, +pypdf/__pycache__/xmp.cpython-311.pyc,, +pypdf/_cmap.py,sha256=C47qIFgI1SKn5LrT4iKznGlkdStYo6O3JZkEKS7gkkE,12572 +pypdf/_codecs/__init__.py,sha256=A11ERAtwtWrpGVOzTSlrC1a3T9HClWLBWRwGe3_Pfu0,1373 +pypdf/_codecs/__pycache__/__init__.cpython-311.pyc,, +pypdf/_codecs/__pycache__/_codecs.cpython-311.pyc,, +pypdf/_codecs/__pycache__/adobe_glyphs.cpython-311.pyc,, +pypdf/_codecs/__pycache__/core_font_metrics.cpython-311.pyc,, +pypdf/_codecs/__pycache__/pdfdoc.cpython-311.pyc,, +pypdf/_codecs/__pycache__/std.cpython-311.pyc,, +pypdf/_codecs/__pycache__/symbol.cpython-311.pyc,, +pypdf/_codecs/__pycache__/zapfding.cpython-311.pyc,, +pypdf/_codecs/_codecs.py,sha256=46oRZJySwGxCJp1kjIer7js_TYSjj4Gs2i2Uce3v-eE,10555 +pypdf/_codecs/adobe_glyphs.py,sha256=t3cDFPDqwIz1w9B0gdVzjdc8eEK9AuRjk5f7laEw_fY,447213 +pypdf/_codecs/core_font_metrics.py,sha256=FLPWbTZ4hxeQWXgg1jo5e4qXKCFkKEY5e85U2bLFM6k,114968 +pypdf/_codecs/pdfdoc.py,sha256=xfSvMFYsvxuaSQ0Uu9vZDKaB0Wu85h1uCiB1i9rAcUU,4269 +pypdf/_codecs/std.py,sha256=DyQMuEpAGEpS9uy1jWf4cnj-kqShPOAij5sI7Q1YD8E,2630 +pypdf/_codecs/symbol.py,sha256=nIaGQIlhWCJiPMHrwUlmGHH-_fOXyEKvguRmuKXcGAk,3734 +pypdf/_codecs/zapfding.py,sha256=PQxjxRC616d41xF3exVxP1W8nM4QrZfjO3lmtLxpE_s,3742 +pypdf/_crypt_providers/__init__.py,sha256=wlKCpMu5L37QYfnLKWSAs3sFIWIiw9ayNwXc60GwjqU,2746 +pypdf/_crypt_providers/__pycache__/__init__.cpython-311.pyc,, +pypdf/_crypt_providers/__pycache__/_base.cpython-311.pyc,, +pypdf/_crypt_providers/__pycache__/_cryptography.cpython-311.pyc,, +pypdf/_crypt_providers/__pycache__/_fallback.cpython-311.pyc,, +pypdf/_crypt_providers/__pycache__/_pycryptodome.cpython-311.pyc,, +pypdf/_crypt_providers/_base.py,sha256=NFBXEdhbrg9k01PVfNN_k7lEAYl2BkgXIOi5ofU_-R8,1735 +pypdf/_crypt_providers/_cryptography.py,sha256=lsBDbJhg5lHOA8h1yNGUSXKf-IYDoetIs5RYQhjHWI4,5239 +pypdf/_crypt_providers/_fallback.py,sha256=gXcro_K7q4IYDL5XGVRxoFmXjXXMa6TleDDwxWyCj4E,3382 +pypdf/_crypt_providers/_pycryptodome.py,sha256=HeGdtXQUNqHONvlL_YmSrXe12FjMHCDPOrNDBsZy9KE,3992 +pypdf/_doc_common.py,sha256=dw4q1FFXYq7F4DdSnJ9uv_TPEUiXE5u0LtBH8bYjUOM,54495 +pypdf/_encryption.py,sha256=O6CpakvHaCMBJv0z8yFLZLrFeOHuCczzSrYl-Mh-05M,49684 +pypdf/_font.py,sha256=bvsqvUgueFAtgyp7hQuKpB6T86g6gtR2XmXkjeIxTjo,22657 +pypdf/_page.py,sha256=IiiDNXWPuCoFkcz0xWSfHRWEm_hyDhdznkI9bp0_fxM,90311 +pypdf/_page_labels.py,sha256=gzIL5BTjlJf-Vt1rC_klCMoMsnnsZcUYsBWY3IG2dUE,8637 +pypdf/_protocols.py,sha256=7qz92LVdPrYkSpdUPpAp9U4GW5jxNBTfVcpUWwUhEOo,2123 +pypdf/_reader.py,sha256=bu9ljqzsYu5QA7j2Lc-TOclBO5aL2nfYNyyBrBWW3oE,60398 +pypdf/_text_extraction/__init__.py,sha256=a3Z33rQVTiMKGtwt7_bfXlPosbST8rzELoNnt053_Qw,8515 +pypdf/_text_extraction/__pycache__/__init__.cpython-311.pyc,, +pypdf/_text_extraction/__pycache__/_text_extractor.cpython-311.pyc,, +pypdf/_text_extraction/_layout_mode/__init__.py,sha256=RUQIwiUwzneNtcljnVM6jkRaem6pgP7mOD2-MBmtpvw,340 +pypdf/_text_extraction/_layout_mode/__pycache__/__init__.cpython-311.pyc,, +pypdf/_text_extraction/_layout_mode/__pycache__/_fixed_width_page.cpython-311.pyc,, +pypdf/_text_extraction/_layout_mode/__pycache__/_text_state_manager.cpython-311.pyc,, +pypdf/_text_extraction/_layout_mode/__pycache__/_text_state_params.cpython-311.pyc,, +pypdf/_text_extraction/_layout_mode/_fixed_width_page.py,sha256=eJveDbyMooG970qJOhM5Rwb9ZoyyJDynzWpV9a7IS20,15370 +pypdf/_text_extraction/_layout_mode/_text_state_manager.py,sha256=AQXpB8EmixVWEWX3WlxAqpxcMcnvcus8z0GScGkfgbE,8224 +pypdf/_text_extraction/_layout_mode/_text_state_params.py,sha256=hyw6pnC8upBkoFVUJ3LH8hBIIHrNwiqaqcYyzIIyr6Y,5481 +pypdf/_text_extraction/_text_extractor.py,sha256=tUqbvC69MFcGQGUBt_Y8rqsVNf-8sMFxADyKnai0ojI,14388 +pypdf/_utils.py,sha256=6ont_F-LsKjtXzduSj3f7_PmCiIixNhES0HHVIRk7CE,20855 +pypdf/_version.py,sha256=b0mPFGl-QnqnSLUfrl5haFAfaStrKciZJA0yE99546Q,23 +pypdf/_writer.py,sha256=_gjG7s0NHTuL5JmKfJCKPKy31NVR6E0_J-15bqqW9kk,133586 +pypdf/annotations/__init__.py,sha256=f2k_-jAn39CCB27KxQ_e93GinnzkAHbUnnSeGJl1jyE,990 +pypdf/annotations/__pycache__/__init__.cpython-311.pyc,, +pypdf/annotations/__pycache__/_base.cpython-311.pyc,, +pypdf/annotations/__pycache__/_markup_annotations.cpython-311.pyc,, +pypdf/annotations/__pycache__/_non_markup_annotations.cpython-311.pyc,, +pypdf/annotations/_base.py,sha256=YIRTzTdkqj8DUWSTmy0frkfTr4joe5HUGzROUof4oIo,961 +pypdf/annotations/_markup_annotations.py,sha256=sWKhGBCG7X9ojAvEaRMEoJP-fY6FcrlFdOmtefIZBm0,11862 +pypdf/annotations/_non_markup_annotations.py,sha256=Z2IUvcCOcTcpJhSXrex_9riYM2D64XxFQ_vac10BNRU,3649 +pypdf/constants.py,sha256=n2cu-HOmoW5_6xQWVEKo42rSJJ0P90hL1s8z-pF0ocs,23634 +pypdf/errors.py,sha256=Bw1W9hxOsDgwqwU6YoQ2l0-JiUyTq6l5QjVCr-W4GFA,1947 +pypdf/filters.py,sha256=mUWCPMpxtM8IcHVyz5Ap3BuPT0yiNvd5-9uIXMR6qcM,31338 +pypdf/generic/__init__.py,sha256=VrqdYftQECePDU2rXVMgEqRaYFR8zOV_fvJgo19x_uw,3468 +pypdf/generic/__pycache__/__init__.cpython-311.pyc,, +pypdf/generic/__pycache__/_appearance_stream.cpython-311.pyc,, +pypdf/generic/__pycache__/_base.cpython-311.pyc,, +pypdf/generic/__pycache__/_data_structures.cpython-311.pyc,, +pypdf/generic/__pycache__/_files.cpython-311.pyc,, +pypdf/generic/__pycache__/_fit.cpython-311.pyc,, +pypdf/generic/__pycache__/_image_inline.cpython-311.pyc,, +pypdf/generic/__pycache__/_image_xobject.cpython-311.pyc,, +pypdf/generic/__pycache__/_link.cpython-311.pyc,, +pypdf/generic/__pycache__/_outline.cpython-311.pyc,, +pypdf/generic/__pycache__/_rectangle.cpython-311.pyc,, +pypdf/generic/__pycache__/_utils.cpython-311.pyc,, +pypdf/generic/__pycache__/_viewerpref.cpython-311.pyc,, +pypdf/generic/_appearance_stream.py,sha256=McDL0gcKNN9NXNU6ZPxgt7OYol2-FoNWYVmAwgAw4PM,26834 +pypdf/generic/_base.py,sha256=9tKiKoe3AUVkHEcme_Ju2LdtVd9jGKoLafAzVCrZRhw,32984 +pypdf/generic/_data_structures.py,sha256=zVyUxv4ErS1qfrtSvYvvSK-QMHStwAEc-HFH0_jp7go,66413 +pypdf/generic/_files.py,sha256=zYag1Cu8bFSyFxD-kNHSiaN4w95qMd4G2e_ApjLUxFs,16327 +pypdf/generic/_fit.py,sha256=X_iADJj1YY4PUStS7rFWC2xR2LUVSvKtUAky0AFAIDM,5515 +pypdf/generic/_image_inline.py,sha256=eGuaAYB_cl6B1gq-iFCys3_YlYUSxCrYfhMDdc2JB70,12847 +pypdf/generic/_image_xobject.py,sha256=ozcXOAN5nlyocOUul4kgQMcoz-M3RL0-aZ3ug0wZr6s,22243 +pypdf/generic/_link.py,sha256=0rpUav79U4OzB6001SSnmIaURkIGtRDi3OmlAWAPEm0,5951 +pypdf/generic/_outline.py,sha256=qKbMX42OWfqnopIiE6BUy6EvdTLGe3ZtjaiWN85JpaY,1094 +pypdf/generic/_rectangle.py,sha256=h6DDP9fgtrMyGG1aouZ51n9XJ0J13dxhhqanJxSBNNU,3924 +pypdf/generic/_utils.py,sha256=vTDAesfG-cJNDKilz_kbgFodAITzd5ejppWHGjvConk,7258 +pypdf/generic/_viewerpref.py,sha256=JBYqL_Xz7mSaUzvCx9C4IX3oaQGO-TOPLEKavX0GH40,6811 +pypdf/pagerange.py,sha256=2bt21jQZm-9aq2bVf3TXuH8_wGVx7b9T6UrMFXCEJhQ,7108 +pypdf/papersizes.py,sha256=6Tz5sfNN_3JOUapY83U-lakohnpXYA0hSEQNmOVLFL8,1413 +pypdf/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pypdf/types.py,sha256=sJ7wHzk7ER_CJ7kP-s8u9axFnkCXnFpr8nzcj1AxTas,1915 +pypdf/xmp.py,sha256=1K8luaL9Sm-8cBs_B0TWBZn9DXljn6D70uanqRoRu_U,30305 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf-6.11.0.dist-info/REQUESTED b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf-6.11.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..793d4f104b76736b4656aed98d50cd5a9dc0f948 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__init__.py @@ -0,0 +1,48 @@ +""" +pypdf is a free and open-source pure-python PDF library capable of splitting, +merging, cropping, and transforming the pages of PDF files. It can also add +custom data, viewing options, and passwords to PDF files. pypdf can retrieve +text and metadata from PDFs as well. + +You can read the full docs at https://pypdf.readthedocs.io/. +""" + +from ._crypt_providers import crypt_provider +from ._doc_common import DocumentInformation +from ._encryption import PasswordType +from ._page import PageObject, Transformation +from ._reader import PdfReader +from ._text_extraction import mult +from ._version import __version__ +from ._writer import ObjectDeletionFlag, PdfWriter +from .constants import ImageType +from .pagerange import PageRange, parse_filename_page_ranges +from .papersizes import PaperSize + +try: + import PIL + + pil_version = PIL.__version__ +except ImportError: + pil_version = "none" + +_debug_versions = ( + f"pypdf=={__version__}, {crypt_provider=}, PIL={pil_version}" +) + +__all__ = [ + "DocumentInformation", + "ImageType", + "ObjectDeletionFlag", + "PageObject", + "PageRange", + "PaperSize", + "PasswordType", + "PdfReader", + "PdfWriter", + "Transformation", + "__version__", + "_debug_versions", + "mult", + "parse_filename_page_ranges", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d02a6568a912b09818f37f9e0e7fd2031ad6298 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/_font.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/_font.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a60652f7637cfdd6a85bec57b958322e3b733a20 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/_font.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/_page_labels.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/_page_labels.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8a209f744ed9023fd063dd87174690ea39f7562 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/_page_labels.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/_protocols.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/_protocols.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c689f9f6ffed0b24b00212ecdf686a1d32c81d94 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/_protocols.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/_reader.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/_reader.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ffe3c9fc4f0c21f01799cb74aeb4029fec181011 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/_reader.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2a89a6b0de412eda6101f76b4b635dd76213fe1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/_version.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/_version.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24bb7dc42c9d1148fbe3d90c076c28eed8bdfbe9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/_version.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_cmap.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_cmap.py new file mode 100644 index 0000000000000000000000000000000000000000..fb19541f2d45060e6cd980c714df38a74f8c2d63 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_cmap.py @@ -0,0 +1,358 @@ +import binascii +from binascii import Error as BinasciiError +from binascii import unhexlify +from math import ceil +from typing import Any, Union, cast + +from ._codecs import adobe_glyphs, charset_encoding +from ._utils import logger_error, logger_warning +from .errors import LimitReachedError +from .generic import ( + DecodedStreamObject, + DictionaryObject, + NullObject, + StreamObject, + is_null_or_none, +) + +_predefined_cmap: dict[str, str] = { + "/Identity-H": "utf-16-be", + "/Identity-V": "utf-16-be", + "/GB-EUC-H": "gbk", + "/GB-EUC-V": "gbk", + "/GBpc-EUC-H": "gb2312", + "/GBpc-EUC-V": "gb2312", + "/GBK-EUC-H": "gbk", + "/GBK-EUC-V": "gbk", + "/GBK2K-H": "gb18030", + "/GBK2K-V": "gb18030", + "/ETen-B5-H": "cp950", + "/ETen-B5-V": "cp950", + "/ETenms-B5-H": "cp950", + "/ETenms-B5-V": "cp950", + "/UniCNS-UTF16-H": "utf-16-be", + "/UniCNS-UTF16-V": "utf-16-be", + "/UniGB-UTF16-H": "gb18030", + "/UniGB-UTF16-V": "gb18030", + # UCS2 in code +} + + +def get_encoding( + ft: DictionaryObject +) -> tuple[Union[str, dict[int, str]], dict[Any, Any]]: + encoding = _parse_encoding(ft) + map_dict, int_entry = _parse_to_unicode(ft) + + # Apply rule from PDF ref 1.7 §5.9.1, 1st bullet: + # if cmap not empty encoding should be discarded + # (here transformed into identity for those characters) + # If encoding is a string, it is expected to be an identity translation. + if isinstance(encoding, dict): + for x in int_entry: + if x <= 255: + encoding[x] = chr(x) + + return encoding, map_dict + + +def _parse_encoding( + ft: DictionaryObject +) -> Union[str, dict[int, str]]: + encoding: Union[str, list[str], dict[int, str]] = [] + if "/Encoding" not in ft: + if "/BaseFont" in ft and cast(str, ft["/BaseFont"]) in charset_encoding: + encoding = dict( + zip(range(256), charset_encoding[cast(str, ft["/BaseFont"])]) + ) + else: + encoding = "charmap" + return encoding + enc: Union[str, DictionaryObject, NullObject] = cast( + Union[str, DictionaryObject, NullObject], ft["/Encoding"].get_object() + ) + if isinstance(enc, str): + try: + # already done : enc = NameObject.unnumber(enc.encode()).decode() + # for #xx decoding + if enc in charset_encoding: + encoding = charset_encoding[enc].copy() + elif enc in _predefined_cmap: + encoding = _predefined_cmap[enc] + elif "-UCS2-" in enc: + encoding = "utf-16-be" + else: + raise Exception("not found") + except Exception: + logger_error("Advanced encoding %(encoding)s not implemented yet", source=__name__, encoding=enc) + encoding = enc + elif isinstance(enc, DictionaryObject) and "/BaseEncoding" in enc: + try: + encoding = charset_encoding[cast(str, enc["/BaseEncoding"])].copy() + except Exception: + logger_error( + "Advanced encoding %(encoding)s not implemented yet", + source=__name__, encoding=encoding + ) + encoding = charset_encoding["/StandardEncoding"].copy() + else: + encoding = charset_encoding["/StandardEncoding"].copy() + if isinstance(enc, DictionaryObject) and "/Differences" in enc: + x: int = 0 + o: Union[int, str] + for o in cast(DictionaryObject, enc["/Differences"]): + if isinstance(o, int): + x = o + else: # isinstance(o, str): + try: + if x < len(encoding): + encoding[x] = adobe_glyphs[o] # type: ignore + except Exception: + encoding[x] = o # type: ignore + x += 1 + if isinstance(encoding, list): + encoding = dict(zip(range(256), encoding)) + return encoding + + +def _parse_to_unicode( + ft: DictionaryObject +) -> tuple[dict[Any, Any], list[int]]: + # will store all translation code + # and map_dict[-1] we will have the number of bytes to convert + map_dict: dict[Any, Any] = {} + + # will provide the list of cmap keys as int to correct encoding + int_entry: list[int] = [] + + if "/ToUnicode" not in ft: + if ft.get("/Subtype", "") == "/Type1": + return _type1_alternative(ft, map_dict, int_entry) + return {}, [] + process_rg: bool = False + process_char: bool = False + multiline_rg: Union[ + None, tuple[int, int] + ] = None # tuple = (current_char, remaining size) ; cf #1285 for example of file + cm = prepare_cm(ft) + for line in cm.split(b"\n"): + process_rg, process_char, multiline_rg = process_cm_line( + line.strip(b" \t"), + process_rg, + process_char, + multiline_rg, + map_dict, + int_entry, + ) + + return map_dict, int_entry + + +def prepare_cm(ft: DictionaryObject) -> bytes: + tu = ft["/ToUnicode"] + cm: bytes + if isinstance(tu, StreamObject): + cm = cast(DecodedStreamObject, ft["/ToUnicode"]).get_data() + else: # if (tu is None) or cast(str, tu).startswith("/Identity"): + # the full range 0000-FFFF will be processed + cm = b"beginbfrange\n<0000> <0001> <0000>\nendbfrange" + if isinstance(cm, str): + cm = cm.encode() + # we need to prepare cm before due to missing return line in pdf printed + # to pdf from word + cm = ( + cm.strip() + .replace(b"beginbfchar", b"\nbeginbfchar\n") + .replace(b"endbfchar", b"\nendbfchar\n") + .replace(b"beginbfrange", b"\nbeginbfrange\n") + .replace(b"endbfrange", b"\nendbfrange\n") + .replace(b"<<", b"\n{\n") # text between << and >> not used but + .replace(b">>", b"\n}\n") # some solution to find it back + ) + ll = cm.split(b"<") + for i in range(len(ll)): + j = ll[i].find(b">") + if j >= 0: + if j == 0: + # string is empty: stash a placeholder here (see below) + # see https://github.com/py-pdf/pypdf/issues/1111 + content = b"." + else: + content = ll[i][:j].replace(b" ", b"") + ll[i] = content + b" " + ll[i][j + 1 :] + cm = ( + (b" ".join(ll)) + .replace(b"[", b" [ ") + .replace(b"]", b" ]\n ") + .replace(b"\r", b"\n") + ) + return cm + + +def process_cm_line( + line: bytes, + process_rg: bool, + process_char: bool, + multiline_rg: Union[None, tuple[int, int]], + map_dict: dict[Any, Any], + int_entry: list[int], +) -> tuple[bool, bool, Union[None, tuple[int, int]]]: + if line == b"" or line[0] == 37: # 37 = % + return process_rg, process_char, multiline_rg + line = line.replace(b"\t", b" ") + if b"beginbfrange" in line: + process_rg = True + elif b"endbfrange" in line: + process_rg = False + elif b"beginbfchar" in line: + process_char = True + elif b"endbfchar" in line: + process_char = False + elif process_rg: + try: + multiline_rg = parse_bfrange(line, map_dict, int_entry, multiline_rg) + except binascii.Error as error: + logger_warning(f"Skipping broken line {line!r}: {error}", __name__) + elif process_char: + parse_bfchar(line, map_dict, int_entry) + return process_rg, process_char, multiline_rg + + +# Usual values should be up to 65_536. +MAPPING_DICTIONARY_SIZE_LIMIT = 100_000 + + +def _check_mapping_size(size: int) -> None: + if size > MAPPING_DICTIONARY_SIZE_LIMIT: + raise LimitReachedError(f"Maximum /ToUnicode size limit reached: {size} > {MAPPING_DICTIONARY_SIZE_LIMIT}.") + + +def parse_bfrange( + line: bytes, + map_dict: dict[Any, Any], + int_entry: list[int], + multiline_rg: Union[None, tuple[int, int]], +) -> Union[None, tuple[int, int]]: + lst = [x for x in line.split(b" ") if x] + closure_found = False + entry_count = len(int_entry) + _check_mapping_size(entry_count) + if multiline_rg is not None: + fmt = b"%%0%dX" % (map_dict[-1] * 2) + a = multiline_rg[0] # a, b not in the current line + b = multiline_rg[1] + for sq in lst: + if sq == b"]": + closure_found = True + break + entry_count += 1 + _check_mapping_size(entry_count) + map_dict[ + unhexlify(fmt % a).decode( + "charmap" if map_dict[-1] == 1 else "utf-16-be", + "surrogatepass", + ) + ] = unhexlify(sq).decode("utf-16-be", "surrogatepass") + int_entry.append(a) + a += 1 + else: + a = int(lst[0], 16) + b = int(lst[1], 16) + nbi = max(len(lst[0]), len(lst[1])) + map_dict[-1] = ceil(nbi / 2) + fmt = b"%%0%dX" % (map_dict[-1] * 2) + if lst[2] == b"[": + for sq in lst[3:]: + if sq == b"]": + closure_found = True + break + entry_count += 1 + _check_mapping_size(entry_count) + map_dict[ + unhexlify(fmt % a).decode( + "charmap" if map_dict[-1] == 1 else "utf-16-be", + "surrogatepass", + ) + ] = unhexlify(sq).decode("utf-16-be", "surrogatepass") + int_entry.append(a) + a += 1 + else: # case without list + c = int(lst[2], 16) + fmt2 = b"%%0%dX" % max(4, len(lst[2])) + closure_found = True + range_size = max(0, b - a + 1) + _check_mapping_size(entry_count + range_size) # This can be checked beforehand. + while a <= b: + map_dict[ + unhexlify(fmt % a).decode( + "charmap" if map_dict[-1] == 1 else "utf-16-be", + "surrogatepass", + ) + ] = unhexlify(fmt2 % c).decode("utf-16-be", "surrogatepass") + int_entry.append(a) + a += 1 + c += 1 + return None if closure_found else (a, b) + + +def parse_bfchar(line: bytes, map_dict: dict[Any, Any], int_entry: list[int]) -> None: + lst = [x for x in line.split(b" ") if x] + new_count = len(lst) // 2 + _check_mapping_size(len(int_entry) + new_count) # This can be checked beforehand. + map_dict[-1] = len(lst[0]) // 2 + while len(lst) > 1: + map_to = "" + # placeholder (see above) means empty string + if lst[1] != b".": + try: + map_to = unhexlify(lst[1]).decode( + "charmap" if len(lst[1]) < 4 else "utf-16-be", "surrogatepass" + ) # join is here as some cases where the code was split + except BinasciiError as exception: + logger_warning(f"Got invalid hex string: {exception!s} ({lst[1]!r})", __name__) + map_dict[ + unhexlify(lst[0]).decode( + "charmap" if map_dict[-1] == 1 else "utf-16-be", "surrogatepass" + ) + ] = map_to + int_entry.append(int(lst[0], 16)) + lst = lst[2:] + + +def _type1_alternative( + ft: DictionaryObject, + map_dict: dict[Any, Any], + int_entry: list[int], +) -> tuple[dict[Any, Any], list[int]]: + if "/FontDescriptor" not in ft: + return map_dict, int_entry + ft_desc = cast(DictionaryObject, ft["/FontDescriptor"]).get("/FontFile") + if is_null_or_none(ft_desc): + return map_dict, int_entry + assert ft_desc is not None, "mypy" + txt = ft_desc.get_object().get_data() + txt = txt.split(b"eexec\n")[0] # only clear part + txt = txt.split(b"/Encoding")[1] # to get the encoding part + lines = txt.replace(b"\r", b"\n").split(b"\n") + for li in lines: + if li.startswith(b"dup"): + words = [_w for _w in li.split(b" ") if _w != b""] + if len(words) > 3 and words[3] != b"put": + continue + try: + i = int(words[1]) + except ValueError: # pragma: no cover + continue + try: + v = adobe_glyphs[words[2].decode()] + except KeyError: + if words[2].startswith(b"/uni"): + try: + v = chr(int(words[2][4:], 16)) + except ValueError: # pragma: no cover + continue + else: + continue + map_dict[chr(i)] = v + int_entry.append(i) + return map_dict, int_entry diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_codecs/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_codecs/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..131b7653ba565f43478bd0f740d8568a3a7a6d66 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_codecs/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_codecs/__pycache__/_codecs.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_codecs/__pycache__/_codecs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd365fceabbb054593f0abff55f8bee42760eb9f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_codecs/__pycache__/_codecs.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_codecs/__pycache__/pdfdoc.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_codecs/__pycache__/pdfdoc.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab931d7a6ff8c5a0e4837ba23a55871ffcd50813 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_codecs/__pycache__/pdfdoc.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_codecs/__pycache__/std.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_codecs/__pycache__/std.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da5e6f7d1c83dad0282a8678826be47c699aacff Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_codecs/__pycache__/std.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_codecs/__pycache__/symbol.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_codecs/__pycache__/symbol.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8eca3ab4386f08174ebcdff9e8b55d4a115bc5de Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_codecs/__pycache__/symbol.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_codecs/__pycache__/zapfding.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_codecs/__pycache__/zapfding.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1477d26dbba3b43346922d82ad03dde525bd06b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_codecs/__pycache__/zapfding.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_crypt_providers/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_crypt_providers/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1298c6c0d965178bd7077d5d32eda55741960700 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_crypt_providers/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_crypt_providers/__pycache__/_base.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_crypt_providers/__pycache__/_base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c24f1492b8658f7e63f7ae20144673e1b6816f5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_crypt_providers/__pycache__/_base.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_crypt_providers/__pycache__/_cryptography.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_crypt_providers/__pycache__/_cryptography.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d40337ebd2e5b121ec1bbfcd889730198dbaf49 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_crypt_providers/__pycache__/_cryptography.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_crypt_providers/__pycache__/_fallback.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_crypt_providers/__pycache__/_fallback.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f393d98d47ce05639244e8b39949001360fcb27a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_crypt_providers/__pycache__/_fallback.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_crypt_providers/__pycache__/_pycryptodome.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_crypt_providers/__pycache__/_pycryptodome.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04a6674ca68447e243db5a67ffb945be8f5d3a40 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_crypt_providers/__pycache__/_pycryptodome.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_doc_common.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_doc_common.py new file mode 100644 index 0000000000000000000000000000000000000000..aef7b41502b4978dc663457d465cfdbaa74db62b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_doc_common.py @@ -0,0 +1,1491 @@ +# Copyright (c) 2006, Mathieu Fenniak +# Copyright (c) 2007, Ashish Kulkarni +# Copyright (c) 2024, Pubpub-ZZ +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * The name of the author may not be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +import struct +from abc import abstractmethod +from collections.abc import Generator, Iterable, Iterator, Mapping +from datetime import datetime +from typing import ( + Any, + Optional, + Union, + cast, +) + +from ._encryption import Encryption +from ._page import PageObject, _VirtualList +from ._page_labels import index2label as page_index2page_label +from ._utils import ( + deprecation_with_replacement, + logger_warning, + parse_iso8824_date, +) +from .constants import CatalogAttributes as CA +from .constants import CatalogDictionary as CD +from .constants import ( + CheckboxRadioButtonAttributes, + GoToActionArguments, + PagesAttributes, + UserAccessPermissions, +) +from .constants import Core as CO +from .constants import DocumentInformationAttributes as DI +from .constants import FieldDictionaryAttributes as FA +from .constants import PageAttributes as PG +from .errors import PdfReadError, PyPdfError +from .filters import _decompress_with_limit +from .generic import ( + ArrayObject, + BooleanObject, + ByteStringObject, + Destination, + DictionaryObject, + EncodedStreamObject, + Field, + Fit, + FloatObject, + IndirectObject, + NameObject, + NullObject, + NumberObject, + PdfObject, + TextStringObject, + TreeObject, + ViewerPreferences, + create_string_object, + is_null_or_none, +) +from .generic._files import EmbeddedFile +from .types import OutlineType, PagemodeType +from .xmp import XmpInformation + + +def convert_to_int(d: bytes, size: int) -> Union[int, tuple[Any, ...]]: + if size > 8: + raise PdfReadError("Invalid size in convert_to_int") + d = b"\x00\x00\x00\x00\x00\x00\x00\x00" + d + d = d[-8:] + return cast(int, struct.unpack(">q", d)[0]) + + +class DocumentInformation(DictionaryObject): + """ + A class representing the basic document metadata provided in a PDF File. + This class is accessible through + :py:class:`PdfReader.metadata`. + + All text properties of the document metadata have + *two* properties, e.g. author and author_raw. The non-raw property will + always return a ``TextStringObject``, making it ideal for a case where the + metadata is being displayed. The raw property can sometimes return a + ``ByteStringObject``, if pypdf was unable to decode the string's text + encoding; this requires additional safety in the caller and therefore is not + as commonly accessed. + """ + + def __init__(self) -> None: + DictionaryObject.__init__(self) + + def _get_text(self, key: str) -> Optional[str]: + retval = self.get(key, None) + if isinstance(retval, TextStringObject): + return retval + if isinstance(retval, ByteStringObject): + return str(retval) + return None + + @property + def title(self) -> Optional[str]: + """ + Read-only property accessing the document's title. + + Returns a ``TextStringObject`` or ``None`` if the title is not + specified. + """ + return ( + self._get_text(DI.TITLE) or self.get(DI.TITLE).get_object() # type: ignore + if self.get(DI.TITLE) + else None + ) + + @property + def title_raw(self) -> Optional[str]: + """The "raw" version of title; can return a ``ByteStringObject``.""" + return self.get(DI.TITLE) + + @property + def author(self) -> Optional[str]: + """ + Read-only property accessing the document's author. + + Returns a ``TextStringObject`` or ``None`` if the author is not + specified. + """ + return self._get_text(DI.AUTHOR) + + @property + def author_raw(self) -> Optional[str]: + """The "raw" version of author; can return a ``ByteStringObject``.""" + return self.get(DI.AUTHOR) + + @property + def subject(self) -> Optional[str]: + """ + Read-only property accessing the document's subject. + + Returns a ``TextStringObject`` or ``None`` if the subject is not + specified. + """ + return self._get_text(DI.SUBJECT) + + @property + def subject_raw(self) -> Optional[str]: + """The "raw" version of subject; can return a ``ByteStringObject``.""" + return self.get(DI.SUBJECT) + + @property + def creator(self) -> Optional[str]: + """ + Read-only property accessing the document's creator. + + If the document was converted to PDF from another format, this is the + name of the application (e.g. OpenOffice) that created the original + document from which it was converted. Returns a ``TextStringObject`` or + ``None`` if the creator is not specified. + """ + return self._get_text(DI.CREATOR) + + @property + def creator_raw(self) -> Optional[str]: + """The "raw" version of creator; can return a ``ByteStringObject``.""" + return self.get(DI.CREATOR) + + @property + def producer(self) -> Optional[str]: + """ + Read-only property accessing the document's producer. + + If the document was converted to PDF from another format, this is the + name of the application (for example, macOS Quartz) that converted it to + PDF. Returns a ``TextStringObject`` or ``None`` if the producer is not + specified. + """ + return self._get_text(DI.PRODUCER) + + @property + def producer_raw(self) -> Optional[str]: + """The "raw" version of producer; can return a ``ByteStringObject``.""" + return self.get(DI.PRODUCER) + + @property + def creation_date(self) -> Optional[datetime]: + """Read-only property accessing the document's creation date.""" + return parse_iso8824_date(self._get_text(DI.CREATION_DATE)) + + @property + def creation_date_raw(self) -> Optional[str]: + """ + The "raw" version of creation date; can return a ``ByteStringObject``. + + Typically in the format ``D:YYYYMMDDhhmmss[+Z-]hh'mm`` where the suffix + is the offset from UTC. + """ + return self.get(DI.CREATION_DATE) + + @property + def modification_date(self) -> Optional[datetime]: + """ + Read-only property accessing the document's modification date. + + The date and time the document was most recently modified. + """ + return parse_iso8824_date(self._get_text(DI.MOD_DATE)) + + @property + def modification_date_raw(self) -> Optional[str]: + """ + The "raw" version of modification date; can return a + ``ByteStringObject``. + + Typically in the format ``D:YYYYMMDDhhmmss[+Z-]hh'mm`` where the suffix + is the offset from UTC. + """ + return self.get(DI.MOD_DATE) + + @property + def keywords(self) -> Optional[str]: + """ + Read-only property accessing the document's keywords. + + Returns a ``TextStringObject`` or ``None`` if keywords are not + specified. + """ + return self._get_text(DI.KEYWORDS) + + @property + def keywords_raw(self) -> Optional[str]: + """The "raw" version of keywords; can return a ``ByteStringObject``.""" + return self.get(DI.KEYWORDS) + + +class PdfDocCommon: + """ + Common functions from PdfWriter and PdfReader objects. + + This root class is strongly abstracted. + """ + + strict: bool = False # default + + flattened_pages: Optional[list[PageObject]] = None + + _encryption: Optional[Encryption] = None + + _readonly: bool = False + + @property + @abstractmethod + def root_object(self) -> DictionaryObject: + ... # pragma: no cover + + @property + @abstractmethod + def pdf_header(self) -> str: + ... # pragma: no cover + + @abstractmethod + def get_object( + self, indirect_reference: Union[int, IndirectObject] + ) -> Optional[PdfObject]: + ... # pragma: no cover + + @abstractmethod + def _replace_object(self, indirect: IndirectObject, obj: PdfObject) -> PdfObject: + ... # pragma: no cover + + @property + @abstractmethod + def _info(self) -> Optional[DictionaryObject]: + ... # pragma: no cover + + @property + def metadata(self) -> Optional[DocumentInformation]: + """ + Retrieve the PDF file's document information dictionary, if it exists. + + Note that some PDF files use metadata streams instead of document + information dictionaries, and these metadata streams will not be + accessed by this function. + """ + retval = DocumentInformation() + if self._info is None: + return None + retval.update(self._info) + return retval + + @property + def xmp_metadata(self) -> Optional[XmpInformation]: + ... # pragma: no cover + + @property + def viewer_preferences(self) -> Optional[ViewerPreferences]: + """Returns the existing ViewerPreferences as an overloaded dictionary.""" + o = self.root_object.get(CD.VIEWER_PREFERENCES, None) + if o is None: + return None + o = o.get_object() + if not isinstance(o, ViewerPreferences): + o = ViewerPreferences(o) + if hasattr(o, "indirect_reference") and o.indirect_reference is not None: + self._replace_object(o.indirect_reference, o) + else: + self.root_object[NameObject(CD.VIEWER_PREFERENCES)] = o + return o + + def get_num_pages(self) -> int: + """ + Calculate the number of pages in this PDF file. + + Returns: + The number of pages of the parsed PDF file. + + Raises: + PdfReadError: If restrictions prevent this action. + + """ + # Flattened pages will not work on an encrypted PDF; + # the PDF file's page count is used in this case. Otherwise, + # the original method (flattened page count) is used. + if self.is_encrypted: + return self.root_object["/Pages"]["/Count"] # type: ignore + if self.flattened_pages is None: + self._flatten(self._readonly) + assert self.flattened_pages is not None + return len(self.flattened_pages) + + def get_page(self, page_number: int) -> PageObject: + """ + Retrieve a page by number from this PDF file. + Most of the time ``.pages[page_number]`` is preferred. + + Args: + page_number: The page number to retrieve + (pages begin at zero) + + Returns: + A :class:`PageObject` instance. + + """ + if self.flattened_pages is None: + self._flatten(self._readonly) + assert self.flattened_pages is not None, "hint for mypy" + return self.flattened_pages[page_number] + + def _get_page_in_node( + self, + page_number: int, + ) -> tuple[DictionaryObject, int]: + """ + Retrieve the node and position within the /Kids containing the page. + If page_number is greater than the number of pages, it returns the top node, -1. + """ + top = cast(DictionaryObject, self.root_object["/Pages"]) + + def recursive_call( + node: DictionaryObject, mi: int + ) -> tuple[Optional[PdfObject], int]: + ma = cast(int, node.get("/Count", 1)) # default 1 for /Page types + if node["/Type"] == "/Page": # type: ignore[comparison-overlap] + if page_number == mi: + return node, -1 + return None, mi + 1 + if (page_number - mi) >= ma: # not in nodes below + if node == top: + return top, -1 + return None, mi + ma + for idx, kid in enumerate(cast(ArrayObject, node["/Kids"])): + kid = cast(DictionaryObject, kid.get_object()) + n, i = recursive_call(kid, mi) + if n is not None: # page has just been found ... + if i < 0: # ... just below! + return node, idx + # ... at lower levels + return n, i + mi = i + raise PyPdfError("Unexpectedly cannot find the node.") + + node, idx = recursive_call(top, 0) + assert isinstance(node, DictionaryObject), "mypy" + return node, idx + + @property + def named_destinations(self) -> dict[str, Destination]: + """A read-only dictionary which maps names to destinations.""" + return self._get_named_destinations() + + def get_named_dest_root(self) -> ArrayObject: + named_dest = ArrayObject() + if CA.NAMES in self.root_object and isinstance( + self.root_object[CA.NAMES], DictionaryObject + ): + names = cast(DictionaryObject, self.root_object[CA.NAMES]) + if CA.DESTS in names and isinstance(names[CA.DESTS], DictionaryObject): + # §3.6.3 Name Dictionary (PDF spec 1.7) + dests = cast(DictionaryObject, names[CA.DESTS]) + dests_ref = dests.indirect_reference + if CA.NAMES in dests: + # §7.9.6, entries in a name tree node dictionary + named_dest = cast(ArrayObject, dests[CA.NAMES]) + else: + named_dest = ArrayObject() + dests[NameObject(CA.NAMES)] = named_dest + elif hasattr(self, "_add_object"): + dests = DictionaryObject() + dests_ref = self._add_object(dests) + names[NameObject(CA.DESTS)] = dests_ref + dests[NameObject(CA.NAMES)] = named_dest + + elif hasattr(self, "_add_object"): + names = DictionaryObject() + names_ref = self._add_object(names) + self.root_object[NameObject(CA.NAMES)] = names_ref + dests = DictionaryObject() + dests_ref = self._add_object(dests) + names[NameObject(CA.DESTS)] = dests_ref + dests[NameObject(CA.NAMES)] = named_dest + + return named_dest + + ## common + def _get_named_destinations( + self, + tree: Union[TreeObject, None] = None, + retval: Optional[dict[str, Destination]] = None, + ) -> dict[str, Destination]: + """ + Retrieve the named destinations present in the document. + + Args: + tree: The current tree. + retval: The previously retrieved destinations for nested calls. + + Returns: + A dictionary which maps names to destinations. + + """ + if retval is None: + retval = {} + catalog = self.root_object + + # get the name tree + if CA.DESTS in catalog: + tree = cast(TreeObject, catalog[CA.DESTS]) + elif CA.NAMES in catalog: + names = cast(DictionaryObject, catalog[CA.NAMES]) + if CA.DESTS in names: + tree = cast(TreeObject, names[CA.DESTS]) + + if is_null_or_none(tree): + return retval + assert tree is not None, "mypy" + + if PagesAttributes.KIDS in tree: + # recurse down the tree + for kid in cast(ArrayObject, tree[PagesAttributes.KIDS]): + self._get_named_destinations(kid.get_object(), retval) + # §7.9.6, entries in a name tree node dictionary + elif CA.NAMES in tree: # /Kids and /Names are exclusives (§7.9.6) + names = cast(DictionaryObject, tree[CA.NAMES]) + i = 0 + while i < len(names): + key = names[i].get_object() + i += 1 + if not isinstance(key, (bytes, str)): + continue + try: + value = names[i].get_object() + except IndexError: + break + i += 1 + if isinstance(value, DictionaryObject): + if "/D" in value: + value = value["/D"] + else: + continue + dest = self._build_destination(key, value) + if dest is not None: + retval[cast(str, dest["/Title"])] = dest + # Remain backwards-compatible. + retval[str(key)] = dest + else: # case where Dests is in root catalog (PDF 1.7 specs, §2 about PDF 1.1) + for k__, v__ in tree.items(): + val = v__.get_object() + if isinstance(val, DictionaryObject): + if "/D" in val: + val = val["/D"].get_object() + else: + continue + dest = self._build_destination(k__, val) + if dest is not None: + retval[k__] = dest + return retval + + # A select group of relevant field attributes. For the complete list, + # see §12.3.2 of the PDF 1.7 or PDF 2.0 specification. + + def get_fields( + self, + tree: Optional[TreeObject] = None, + retval: Optional[dict[Any, Any]] = None, + fileobj: Optional[Any] = None, + stack: Optional[list[PdfObject]] = None, + ) -> Optional[dict[str, Any]]: + """ + Extract field data if this PDF contains interactive form fields. + + The *tree*, *retval*, *stack* parameters are for recursive use. + + Args: + tree: Current object to parse. + retval: In-progress list of fields. + fileobj: A file object (usually a text file) to write + a report to on all interactive form fields found. + stack: List of already parsed objects. + + Returns: + A dictionary where each key is a field name, and each + value is a :class:`Field` object. By + default, the mapping name is used for keys. + ``None`` if form data could not be located. + + """ + field_attributes = FA.attributes_dict() + field_attributes.update(CheckboxRadioButtonAttributes.attributes_dict()) + if retval is None: + retval = {} + catalog = self.root_object + stack = [] + # get the AcroForm tree + if CD.ACRO_FORM in catalog: + tree = cast(Optional[TreeObject], catalog[CD.ACRO_FORM]) + else: + return None + if tree is None: + return retval + assert stack is not None + if "/Fields" in tree: + fields = cast(ArrayObject, tree["/Fields"]) + for f in fields: + field = f.get_object() + self._build_field(field, retval, fileobj, field_attributes, stack) + elif any(attr in tree for attr in field_attributes): + # Tree is a field + self._build_field(tree, retval, fileobj, field_attributes, stack) + return retval + + def _get_qualified_field_name(self, parent: DictionaryObject) -> str: + if "/TM" in parent: + return cast(str, parent["/TM"]) + if "/Parent" in parent: + return ( + self._get_qualified_field_name( + cast(DictionaryObject, parent["/Parent"]) + ) + + "." + + cast(str, parent.get("/T", "")) + ) + return cast(str, parent.get("/T", "")) + + def _build_field( + self, + field: Union[TreeObject, DictionaryObject], + retval: dict[Any, Any], + fileobj: Any, + field_attributes: Any, + stack: list[PdfObject], + ) -> None: + if all(attr not in field for attr in ("/T", "/TM")): + return + key = self._get_qualified_field_name(field) + if fileobj: + self._write_field(fileobj, field, field_attributes) + fileobj.write("\n") + retval[key] = Field(field) + obj = retval[key].indirect_reference.get_object() # to get the full object + if obj.get(FA.FT, "") == "/Ch" and obj.get(NameObject(FA.Opt)): + retval[key][NameObject("/_States_")] = obj[NameObject(FA.Opt)] + if obj.get(FA.FT, "") == "/Btn" and "/AP" in obj: + # Checkbox + retval[key][NameObject("/_States_")] = ArrayObject( + list(obj["/AP"]["/N"].keys()) + ) + if "/Off" not in retval[key]["/_States_"]: + retval[key][NameObject("/_States_")].append(NameObject("/Off")) + elif obj.get(FA.FT, "") == "/Btn" and obj.get(FA.Ff, 0) & FA.FfBits.Radio != 0: + states: list[str] = [] + retval[key][NameObject("/_States_")] = ArrayObject(states) + for k in obj.get(FA.Kids, {}): + k = k.get_object() + for s in list(k["/AP"]["/N"].keys()): + if s not in states: + states.append(s) + retval[key][NameObject("/_States_")] = ArrayObject(states) + if ( + obj.get(FA.Ff, 0) & FA.FfBits.NoToggleToOff != 0 + and "/Off" in retval[key]["/_States_"] + ): + del retval[key]["/_States_"][retval[key]["/_States_"].index("/Off")] + # at last for order + self._check_kids(field, retval, fileobj, stack) + + def _check_kids( + self, + tree: Union[TreeObject, DictionaryObject], + retval: Any, + fileobj: Any, + stack: list[PdfObject], + ) -> None: + if tree in stack: + logger_warning( + f"{self._get_qualified_field_name(tree)} already parsed", __name__ + ) + return + stack.append(tree) + if PagesAttributes.KIDS in tree: + # recurse down the tree + for kid in tree[PagesAttributes.KIDS]: # type: ignore + kid = kid.get_object() + self.get_fields(kid, retval, fileobj, stack) + + def _write_field(self, fileobj: Any, field: Any, field_attributes: Any) -> None: + field_attributes_tuple = FA.attributes() + field_attributes_tuple = ( + field_attributes_tuple + CheckboxRadioButtonAttributes.attributes() + ) + + for attr in field_attributes_tuple: + if attr in ( + FA.Kids, + FA.AA, + ): + continue + attr_name = field_attributes[attr] + try: + if attr == FA.FT: + # Make the field type value clearer + types = { + "/Btn": "Button", + "/Tx": "Text", + "/Ch": "Choice", + "/Sig": "Signature", + } + if field[attr] in types: + fileobj.write(f"{attr_name}: {types[field[attr]]}\n") + elif attr == FA.Parent: + # Let's just write the name of the parent + try: + name = field[attr][FA.TM] + except KeyError: + name = field[attr][FA.T] + fileobj.write(f"{attr_name}: {name}\n") + else: + fileobj.write(f"{attr_name}: {field[attr]}\n") + except KeyError: + # Field attribute is N/A or unknown, so don't write anything + pass + + def get_form_text_fields(self, full_qualified_name: bool = False) -> dict[str, Any]: + """ + Retrieve form fields from the document with textual data. + + Args: + full_qualified_name: to get full name + + Returns: + A dictionary. The key is the name of the form field, + the value is the content of the field. + + If the document contains multiple form fields with the same name, the + second and following will get the suffix .2, .3, ... + + """ + + def indexed_key(k: str, fields: dict[Any, Any]) -> str: + if k not in fields: + return k + return ( + k + + "." + + str(sum(1 for kk in fields if kk.startswith(k + ".")) + 2) + ) + + # Retrieve document form fields + formfields = self.get_fields() + if formfields is None: + return {} + ff = {} + for field, value in formfields.items(): + if value.get("/FT") == "/Tx": + if full_qualified_name: + ff[field] = value.get("/V") + else: + ff[indexed_key(cast(str, value["/T"]), ff)] = value.get("/V") + return ff + + def get_pages_showing_field( + self, field: Union[Field, PdfObject, IndirectObject] + ) -> list[PageObject]: + """ + Provides list of pages where the field is called. + + Args: + field: Field Object, PdfObject or IndirectObject referencing a Field + + Returns: + List of pages: + - Empty list: + The field has no widgets attached + (either hidden field or ancestor field). + - Single page list: + Page where the widget is present + (most common). + - Multi-page list: + Field with multiple kids widgets + (example: radio buttons, field repeated on multiple pages). + + """ + + def _get_inherited(obj: DictionaryObject, key: str) -> Any: + if key in obj: + return obj[key] + if "/Parent" in obj: + return _get_inherited( + cast(DictionaryObject, obj["/Parent"].get_object()), key + ) + return None + + try: + # to cope with all types + field = cast(DictionaryObject, field.indirect_reference.get_object()) # type: ignore + except Exception as exc: + raise ValueError("Field type is invalid") from exc + if is_null_or_none(_get_inherited(field, "/FT")): + raise ValueError("Field is not valid") + ret = [] + if field.get("/Subtype", "") == "/Widget": + if "/P" in field: + ret = [field["/P"].get_object()] + else: + ret = [ + p + for p in self.pages + if field.indirect_reference in p.get("/Annots", "") + ] + else: + kids = field.get("/Kids", ()) + for k in kids: + k = k.get_object() + if (k.get("/Subtype", "") == "/Widget") and ("/T" not in k): + # Kid that is just a widget, not a field: + if "/P" in k: + ret += [k["/P"].get_object()] + else: + ret += [ + p + for p in self.pages + if k.indirect_reference in p.get("/Annots", "") + ] + return [ + x + if isinstance(x, PageObject) + else (self.pages[self._get_page_number_by_indirect(x.indirect_reference)]) # type: ignore + for x in ret + ] + + @property + def open_destination( + self, + ) -> Union[None, Destination, TextStringObject, ByteStringObject]: + """ + Property to access the opening destination (``/OpenAction`` entry in + the PDF catalog). It returns ``None`` if the entry does not exist + or is not set. + + Raises: + Exception: If a destination is invalid. + + """ + if "/OpenAction" not in self.root_object: + return None + oa: Any = self.root_object["/OpenAction"] + if isinstance(oa, bytes): # pragma: no cover + oa = oa.decode() + if isinstance(oa, str): + return create_string_object(oa) + if isinstance(oa, ArrayObject): + try: + page, typ, *array = oa + fit = Fit(typ, tuple(array)) + return Destination("OpenAction", page, fit) + except Exception as exc: + raise Exception(f"Invalid Destination {oa}: {exc}") + else: + return None + + @open_destination.setter + def open_destination(self, dest: Union[None, str, Destination, PageObject]) -> None: + raise NotImplementedError("No setter for open_destination") + + @property + def outline(self) -> OutlineType: + """ + Read-only property for the outline present in the document + (i.e., a collection of 'outline items' which are also known as + 'bookmarks'). + """ + return self._get_outline() + + def _get_outline( + self, + node: Optional[DictionaryObject] = None, + outline: Optional[Any] = None, + visited: Optional[set[int]] = None, + ) -> OutlineType: + if outline is None: + outline = [] + catalog = self.root_object + + # get the outline dictionary and named destinations + if CO.OUTLINES in catalog: + lines = cast(DictionaryObject, catalog[CO.OUTLINES]) + + if isinstance(lines, NullObject): + return outline + + # §12.3.3 Document outline, entries in the outline dictionary + if not is_null_or_none(lines) and "/First" in lines: + node = cast(DictionaryObject, lines["/First"]) + self._named_destinations = self._get_named_destinations() + + if node is None: + return outline + + # see if there are any more outline items + if visited is None: + visited = set() + while True: + node_id = id(node) + if node_id in visited: + logger_warning(f"Detected cycle in outline structure for {node}", __name__) + break + visited.add(node_id) + + outline_obj = self._build_outline_item(node) + if outline_obj: + outline.append(outline_obj) + + # check for sub-outline + if "/First" in node: + sub_outline: list[Any] = [] + # Pass a copy to allow multiple outer entries to reference the same inner one. + inner_visited = visited.copy() + self._get_outline( + node=cast(DictionaryObject, node["/First"]), + outline=sub_outline, + visited=inner_visited, + ) + if sub_outline: + outline.append(sub_outline) + + if "/Next" not in node: + break + node = cast(DictionaryObject, node["/Next"]) + + return outline + + @property + def threads(self) -> Optional[ArrayObject]: + """ + Read-only property for the list of threads. + + See §12.4.3 from the PDF 1.7 or 2.0 specification. + + It is an array of dictionaries with "/F" (the first bead in the thread) + and "/I" (a thread information dictionary containing information about + the thread, such as its title, author, and creation date) properties or + None if there are no articles. + + Since PDF 2.0 it can also contain an indirect reference to a metadata + stream containing information about the thread, such as its title, + author, and creation date. + """ + catalog = self.root_object + if CO.THREADS in catalog: + return cast("ArrayObject", catalog[CO.THREADS]) + return None + + @abstractmethod + def _get_page_number_by_indirect( + self, indirect_reference: Union[None, int, NullObject, IndirectObject] + ) -> Optional[int]: + ... # pragma: no cover + + def get_page_number(self, page: PageObject) -> Optional[int]: + """ + Retrieve page number of a given PageObject. + + Args: + page: The page to get page number. Should be + an instance of :class:`PageObject` + + Returns: + The page number or None if page is not found + + """ + return self._get_page_number_by_indirect(page.indirect_reference) + + def get_destination_page_number(self, destination: Destination) -> Optional[int]: + """ + Retrieve page number of a given Destination object. + + Args: + destination: The destination to get page number. + + Returns: + The page number or None if page is not found + + """ + return self._get_page_number_by_indirect(destination.page) + + def _build_destination( + self, + title: Union[str, bytes], + array: Optional[ + list[ + Union[NumberObject, IndirectObject, None, NullObject, DictionaryObject] + ] + ], + ) -> Destination: + page, typ = None, None + # handle outline items with missing or invalid destination + if ( + isinstance(array, (NullObject, str)) + or (isinstance(array, ArrayObject) and len(array) == 0) + or array is None + ): + page = NullObject() + return Destination(title, page, Fit.fit()) + page, typ, *array = array # type: ignore + try: + return Destination(title, page, Fit(fit_type=typ, fit_args=array)) # type: ignore + except PdfReadError: + logger_warning(f"Unknown destination: {title!r} {array}", __name__) + if self.strict: + raise + # create a link to first Page + tmp = self.pages[0].indirect_reference + indirect_reference = NullObject() if tmp is None else tmp + return Destination(title, indirect_reference, Fit.fit()) + + def _build_outline_item(self, node: DictionaryObject) -> Optional[Destination]: + dest, title, outline_item = None, None, None + + # title required for valid outline + # §12.3.3, entries in an outline item dictionary + try: + title = cast("str", node["/Title"]) + except KeyError: + if self.strict: + raise PdfReadError(f"Outline Entry Missing /Title attribute: {node!r}") + title = "" + + if "/A" in node: + # Action, PDF 1.7 and PDF 2.0 §12.6 (only type GoTo supported) + action = cast(DictionaryObject, node["/A"]) + action_type = cast(NameObject, action[GoToActionArguments.S]) + if action_type == "/GoTo": + if GoToActionArguments.D in action: + dest = action[GoToActionArguments.D] + elif self.strict: + raise PdfReadError(f"Outline Action Missing /D attribute: {node!r}") + elif "/Dest" in node: + # Destination, PDF 1.7 and PDF 2.0 §12.3.2 + dest = node["/Dest"] + # if array was referenced in another object, will be a dict w/ key "/D" + if isinstance(dest, DictionaryObject) and "/D" in dest: + dest = dest["/D"] + + if isinstance(dest, ArrayObject): + outline_item = self._build_destination(title, dest) + elif isinstance(dest, str): + # named destination, addresses NameObject Issue #193 + # TODO: Keep named destination instead of replacing it? + try: + outline_item = self._build_destination( + title, self._named_destinations[dest].dest_array + ) + except KeyError: + # named destination not found in Name Dict + outline_item = self._build_destination(title, None) + elif dest is None: + # outline item not required to have destination or action + # PDFv1.7 Table 153 + outline_item = self._build_destination(title, dest) + else: + if self.strict: + raise PdfReadError(f"Unexpected destination {dest!r}") + logger_warning( + f"Removed unexpected destination {dest!r} from destination", + __name__, + ) + outline_item = self._build_destination(title, None) + + # if outline item created, add color, format, and child count if present + if outline_item: + if "/C" in node: + # Color of outline item font in (R, G, B) with values ranging 0.0-1.0 + outline_item[NameObject("/C")] = ArrayObject(FloatObject(c) for c in node["/C"]) # type: ignore + if "/F" in node: + # specifies style characteristics bold and/or italic + # with 1=italic, 2=bold, 3=both + outline_item[NameObject("/F")] = node["/F"] + if "/Count" in node: + # absolute value = num. visible children + # with positive = open/unfolded, negative = closed/folded + outline_item[NameObject("/Count")] = node["/Count"] + # if count is 0 we will consider it as open (to have available is_open) + outline_item[NameObject("/%is_open%")] = BooleanObject( + node.get("/Count", 0) >= 0 + ) + outline_item.node = node + try: + outline_item.indirect_reference = node.indirect_reference + except AttributeError: + pass + return outline_item + + @property + def pages(self) -> list[PageObject]: + """ + Property that emulates a list of :class:`PageObject`. + This property allows to get a page or a range of pages. + + Note: + For PdfWriter only: Provides the capability to remove a page/range of + page from the list (using the del operator). Remember: Only the page + entry is removed, as the objects beneath can be used elsewhere. A + solution to completely remove them - if they are not used anywhere - is + to write to a buffer/temporary file and then load it into a new + PdfWriter. + + """ + return _VirtualList(self.get_num_pages, self.get_page) # type: ignore + + @property + def page_labels(self) -> list[str]: + """ + A list of labels for the pages in this document. + + This property is read-only. The labels are in the order that the pages + appear in the document. + """ + return [page_index2page_label(self, i) for i in range(len(self.pages))] + + @property + def page_layout(self) -> Optional[str]: + """ + Get the page layout currently being used. + + .. list-table:: Valid ``layout`` values + :widths: 50 200 + + * - /NoLayout + - Layout explicitly not specified + * - /SinglePage + - Show one page at a time + * - /OneColumn + - Show one column at a time + * - /TwoColumnLeft + - Show pages in two columns, odd-numbered pages on the left + * - /TwoColumnRight + - Show pages in two columns, odd-numbered pages on the right + * - /TwoPageLeft + - Show two pages at a time, odd-numbered pages on the left + * - /TwoPageRight + - Show two pages at a time, odd-numbered pages on the right + """ + try: + return cast(NameObject, self.root_object[CD.PAGE_LAYOUT]) + except KeyError: + return None + + @property + def page_mode(self) -> Optional[PagemodeType]: + """ + Get the page mode currently being used. + + .. list-table:: Valid ``mode`` values + :widths: 50 200 + + * - /UseNone + - Do not show outline or thumbnails panels + * - /UseOutlines + - Show outline (aka bookmarks) panel + * - /UseThumbs + - Show page thumbnails panel + * - /FullScreen + - Fullscreen view + * - /UseOC + - Show Optional Content Group (OCG) panel + * - /UseAttachments + - Show attachments panel + """ + try: + return self.root_object["/PageMode"] # type: ignore + except KeyError: + return None + + def _flatten( + self, + list_only: bool = False, + pages: Union[None, DictionaryObject, PageObject] = None, + inherit: Optional[dict[str, Any]] = None, + indirect_reference: Optional[IndirectObject] = None, + ) -> None: + """ + Process the document pages to ease searching. + + Attributes of a page may inherit from ancestor nodes + in the page tree. Flattening means moving + any inheritance data into descendant nodes, + effectively removing the inheritance dependency. + + Note: It is distinct from another use of "flattening" applied to PDFs. + Flattening a PDF also means combining all the contents into one single layer + and making the file less editable. + + Args: + list_only: Will only list the pages within _flatten_pages. + pages: + inherit: + indirect_reference: Used recursively to flatten the /Pages object. + + """ + inheritable_page_attributes = ( + NameObject(PG.RESOURCES), + NameObject(PG.MEDIABOX), + NameObject(PG.CROPBOX), + NameObject(PG.ROTATE), + ) + if inherit is None: + inherit = {} + if is_null_or_none(pages): + # Fix issue 327: set flattened_pages attribute only for + # decrypted file + catalog = self.root_object + pages = catalog.get("/Pages").get_object() # type: ignore + if not isinstance(pages, DictionaryObject): + raise PdfReadError("Invalid object in /Pages") + self.flattened_pages = [] + assert pages is not None, "mypy" + + if PagesAttributes.TYPE in pages: + t = cast(str, pages[PagesAttributes.TYPE]) + # if the page tree node has no /Type, consider as a page if /Kids is also missing + elif PagesAttributes.KIDS not in pages: + t = "/Page" + else: + t = "/Pages" + + if t == "/Pages": + for attr in inheritable_page_attributes: + if attr in pages: + inherit[attr] = pages[attr] + pages_reference = getattr(pages, "indirect_reference", object()) + for page in cast(ArrayObject, pages[PagesAttributes.KIDS]): + if getattr(page, "indirect_reference", object()) == pages_reference: + raise PdfReadError("Detected cyclic page references.") + + addt = {} + if isinstance(page, IndirectObject): + addt["indirect_reference"] = page + obj = page.get_object() + if obj: + # damaged file may have invalid child in /Pages + try: + self._flatten(list_only, obj, inherit, **addt) + except RecursionError: + raise PdfReadError( + "Maximum recursion depth reached during page flattening." + ) + elif t == "/Page": + for attr_in, value in inherit.items(): + # if the page has its own value, it does not inherit the + # parent's value + if attr_in not in pages: + pages[attr_in] = value + page_obj = PageObject(self, indirect_reference) + if not list_only: + page_obj.update(pages) + + # TODO: Could flattened_pages be None at this point? + self.flattened_pages.append(page_obj) # type: ignore + + def remove_page( + self, + page: Union[int, PageObject, IndirectObject], + clean: bool = False, + ) -> None: + """ + Remove page from pages list. + + Args: + page: + * :class:`int`: Page number to be removed. + * :class:`~pypdf._page.PageObject`: page to be removed. If the page appears many times + only the first one will be removed. + * :class:`~pypdf.generic.IndirectObject`: Reference to page to be removed. + + clean: replace PageObject with NullObject to prevent annotations + or destinations to reference a detached page. + + """ + if self.flattened_pages is None: + self._flatten(self._readonly) + assert self.flattened_pages is not None + if isinstance(page, IndirectObject): + p = page.get_object() + if not isinstance(p, PageObject): + logger_warning("IndirectObject is not referencing a page", __name__) + return + page = p + + if not isinstance(page, int): + try: + page = self.flattened_pages.index(page) + except ValueError: + logger_warning("Cannot find page in pages", __name__) + return + if not (0 <= page < len(self.flattened_pages)): + logger_warning("Page number is out of range", __name__) + return + + ind = self.pages[page].indirect_reference + del self.pages[page] + if clean and ind is not None: + self._replace_object(ind, NullObject()) + + def _get_indirect_object(self, num: int, gen: int) -> Optional[PdfObject]: + """ + Used to ease development. + + This is equivalent to generic.IndirectObject(num,gen,self).get_object() + + Args: + num: The object number of the indirect object. + gen: The generation number of the indirect object. + + Returns: + A PdfObject + + """ + return IndirectObject(num, gen, self).get_object() + + def decode_permissions( + self, permissions_code: int + ) -> dict[str, bool]: # pragma: no cover + """Take the permissions as an integer, return the allowed access.""" + deprecation_with_replacement( + old_name="decode_permissions", + new_name="user_access_permissions", + removed_in="5.0.0", + ) + + permissions_mapping = { + "print": UserAccessPermissions.PRINT, + "modify": UserAccessPermissions.MODIFY, + "copy": UserAccessPermissions.EXTRACT, + "annotations": UserAccessPermissions.ADD_OR_MODIFY, + "forms": UserAccessPermissions.FILL_FORM_FIELDS, + # Do not fix typo, as part of official, but deprecated API. + "accessability": UserAccessPermissions.EXTRACT_TEXT_AND_GRAPHICS, + "assemble": UserAccessPermissions.ASSEMBLE_DOC, + "print_high_quality": UserAccessPermissions.PRINT_TO_REPRESENTATION, + } + + return { + key: permissions_code & flag != 0 + for key, flag in permissions_mapping.items() + } + + @property + def user_access_permissions(self) -> Optional[UserAccessPermissions]: + """ + Get the user access permissions for encrypted documents. + Returns None if not encrypted. + + .. warning:: + + For AES-256 encrypted documents (R=5/R=6), the returned + permissions are derived from the ``/P`` field, which is + only trustworthy if the ``/Perms`` integrity check passed. + Check :attr:`are_permissions_valid` to verify. + """ + if self._encryption is None: + return None + return UserAccessPermissions(self._encryption.P) + + @property + def are_permissions_valid(self) -> Optional[bool]: + """ + Whether the ``/Perms`` integrity check passed for this document. + + For AES-256 encrypted documents (R=5/R=6), the ``/Perms`` field + is an encrypted copy of the permissions that can be verified + independently. Returns ``False`` if this check fails (the ``/P`` + permissions may have been tampered with). + + Returns ``None`` if the document is not encrypted or has not yet + been decrypted via :meth:`decrypt()`. + Returns ``True`` for non-AES-256 encryption (no ``/Perms`` to check). + """ + if self._encryption is None: + return None + if not self._encryption.is_decrypted(): + return None + return self._encryption._are_permissions_valid + + @property + @abstractmethod + def is_encrypted(self) -> bool: + """ + Read-only boolean property showing whether this PDF file is encrypted. + + Note that this property, if true, will remain true even after the + :meth:`decrypt()` method is called. + """ + ... # pragma: no cover + + @property + def xfa(self) -> Optional[dict[str, Any]]: + retval: dict[str, Any] = {} + catalog = self.root_object + + if "/AcroForm" not in catalog or not catalog["/AcroForm"]: + return None + + tree = cast(TreeObject, catalog["/AcroForm"]) + + if "/XFA" in tree: + fields = cast(ArrayObject, tree["/XFA"]) + i = iter(fields) + for f in i: + tag = f + f = next(i) + if isinstance(f, IndirectObject): + field = cast(Optional[EncodedStreamObject], f.get_object()) + if field: + es = _decompress_with_limit(field._data) + retval[tag] = es + return retval + + @property + def attachments(self) -> Mapping[str, list[bytes]]: + """Mapping of attachment filenames to their content.""" + return LazyDict( + { + name: (self._get_attachment_list, name) + for name in self._list_attachments() + } + ) + + @property + def attachment_list(self) -> Generator[EmbeddedFile, None, None]: + """Iterable of attachment objects.""" + yield from EmbeddedFile._load(self.root_object) + + def _list_attachments(self) -> list[str]: + """ + Retrieves the list of filenames of file attachments. + + Returns: + list of filenames + + """ + names = [] + for entry in self.attachment_list: + names.append(entry.name) + if (name := entry.alternative_name) != entry.name and name: + names.append(name) + return names + + def _get_attachment_list(self, name: str) -> list[bytes]: + out = self._get_attachments(name)[name] + if isinstance(out, list): + return out + return [out] + + def _get_attachments( + self, filename: Optional[str] = None + ) -> dict[str, Union[bytes, list[bytes]]]: + """ + Retrieves all or selected file attachments of the PDF as a dictionary of file names + and the file data as a bytestring. + + Args: + filename: If filename is None, then a dictionary of all attachments + will be returned, where the key is the filename and the value + is the content. Otherwise, a dictionary with just a single key + - the filename - and its content will be returned. + + Returns: + dictionary of filename -> Union[bytestring or List[ByteString]] + If the filename exists multiple times a list of the different versions will be provided. + + """ + attachments: dict[str, Union[bytes, list[bytes]]] = {} + for entry in self.attachment_list: + names = set() + alternative_name = entry.alternative_name + if filename is not None: + if filename in {entry.name, alternative_name}: + name = entry.name if filename == entry.name else alternative_name + names.add(name) + else: + continue + else: + names = {entry.name, alternative_name} + + for name in names: + if name is None: + continue + if name in attachments: + if not isinstance(attachments[name], list): + attachments[name] = [attachments[name]] # type:ignore + attachments[name].append(entry.content) # type:ignore + else: + attachments[name] = entry.content + return attachments + + @abstractmethod + def _repr_mimebundle_( + self, + include: Union[None, Iterable[str]] = None, + exclude: Union[None, Iterable[str]] = None, + ) -> dict[str, Any]: + """ + Integration into Jupyter Notebooks. + + This method returns a dictionary that maps a mime-type to its + representation. + + .. seealso:: + + https://ipython.readthedocs.io/en/stable/config/integrating.html + """ + ... # pragma: no cover + + +class LazyDict(Mapping[Any, Any]): + def __init__(self, *args: Any, **kwargs: Any) -> None: + self._raw_dict = dict(*args, **kwargs) + + def __getitem__(self, key: str) -> Any: + func, arg = self._raw_dict.__getitem__(key) + return func(arg) + + def __iter__(self) -> Iterator[Any]: + return iter(self._raw_dict) + + def __len__(self) -> int: + return len(self._raw_dict) + + def __str__(self) -> str: + return f"LazyDict(keys={list(self.keys())})" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_encryption.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_encryption.py new file mode 100644 index 0000000000000000000000000000000000000000..5854aaf2ac00ff36bdee4d341ad846c8acaaec31 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_encryption.py @@ -0,0 +1,1194 @@ +# Copyright (c) 2022, exiledkingcc +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * The name of the author may not be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. +import hashlib +import secrets +import struct +from enum import Enum, IntEnum +from typing import Any, Optional, Union, cast + +from pypdf._crypt_providers import ( + CryptAES, + CryptBase, + CryptIdentity, + CryptRC4, + aes_cbc_decrypt, + aes_cbc_encrypt, + aes_ecb_decrypt, + aes_ecb_encrypt, + rc4_decrypt, + rc4_encrypt, +) + +from ._utils import logger_warning +from .generic import ( + ArrayObject, + ByteStringObject, + DictionaryObject, + NameObject, + NumberObject, + PdfObject, + StreamObject, + TextStringObject, + create_string_object, +) + + +class CryptFilter: + def __init__( + self, + stm_crypt: CryptBase, + str_crypt: CryptBase, + ef_crypt: CryptBase, + ) -> None: + self.stm_crypt = stm_crypt + self.str_crypt = str_crypt + self.ef_crypt = ef_crypt + + def encrypt_object(self, obj: PdfObject) -> PdfObject: + if isinstance(obj, ByteStringObject): + data = self.str_crypt.encrypt(obj.original_bytes) + obj = ByteStringObject(data) + elif isinstance(obj, TextStringObject): + data = self.str_crypt.encrypt(obj.get_encoded_bytes()) + obj = ByteStringObject(data) + elif isinstance(obj, StreamObject): + obj2 = StreamObject() + obj2.update(obj) + obj2.set_data(self.stm_crypt.encrypt(obj._data)) + for key, value in obj.items(): # Dont forget the Stream dict. + obj2[key] = self.encrypt_object(value) + obj = obj2 + elif isinstance(obj, DictionaryObject): + obj2 = DictionaryObject() # type: ignore + for key, value in obj.items(): + obj2[key] = self.encrypt_object(value) + obj = obj2 + elif isinstance(obj, ArrayObject): + obj = ArrayObject(self.encrypt_object(x) for x in obj) + return obj + + def decrypt_object(self, obj: PdfObject, *, strict: bool = True) -> PdfObject: + if isinstance(obj, (ByteStringObject, TextStringObject)): + data = self.str_crypt.decrypt(obj.original_bytes, strict=strict) + obj = create_string_object(data) + elif isinstance(obj, StreamObject): + obj._data = self.stm_crypt.decrypt(obj._data, strict=strict) + for key, value in obj.items(): # Dont forget the Stream dict. + obj[key] = self.decrypt_object(value, strict=strict) + elif isinstance(obj, DictionaryObject): + for key, value in obj.items(): + obj[key] = self.decrypt_object(value, strict=strict) + elif isinstance(obj, ArrayObject): + for i in range(len(obj)): + obj[i] = self.decrypt_object(obj[i], strict=strict) + return obj + + +_PADDING = ( + b"\x28\xbf\x4e\x5e\x4e\x75\x8a\x41\x64\x00\x4e\x56\xff\xfa\x01\x08" + b"\x2e\x2e\x00\xb6\xd0\x68\x3e\x80\x2f\x0c\xa9\xfe\x64\x53\x69\x7a" +) + + +def _padding(data: bytes) -> bytes: + return (data + _PADDING)[:32] + + +class AlgV4: + @staticmethod + def compute_key( + password: bytes, + rev: int, + key_size: int, + o_entry: bytes, + P: int, + id1_entry: bytes, + metadata_encrypted: bool, + ) -> bytes: + """ + Algorithm 2: Computing an encryption key. + + a) Pad or truncate the password string to exactly 32 bytes. If the + password string is more than 32 bytes long, + use only its first 32 bytes; if it is less than 32 bytes long, pad it + by appending the required number of + additional bytes from the beginning of the following padding string: + < 28 BF 4E 5E 4E 75 8A 41 64 00 4E 56 FF FA 01 08 + 2E 2E 00 B6 D0 68 3E 80 2F 0C A9 FE 64 53 69 7A > + That is, if the password string is n bytes long, append + the first 32 - n bytes of the padding string to the end + of the password string. If the password string is empty + (zero-length), meaning there is no user password, + substitute the entire padding string in its place. + + b) Initialize the MD5 hash function and pass the result of step (a) + as input to this function. + c) Pass the value of the encryption dictionary’s O entry to the + MD5 hash function. ("Algorithm 3: Computing + the encryption dictionary’s O (owner password) value" shows how the + O value is computed.) + d) Convert the integer value of the P entry to a 32-bit unsigned binary + number and pass these bytes to the + MD5 hash function, low-order byte first. + e) Pass the first element of the file’s file identifier array (the value + of the ID entry in the document’s trailer + dictionary; see Table 15) to the MD5 hash function. + f) (Security handlers of revision 4 or greater) If document metadata is + not being encrypted, pass 4 bytes with + the value 0xFFFFFFFF to the MD5 hash function. + g) Finish the hash. + h) (Security handlers of revision 3 or greater) Do the following + 50 times: Take the output from the previous + MD5 hash and pass the first n bytes of the output as input into a new + MD5 hash, where n is the number of + bytes of the encryption key as defined by the value of the encryption + dictionary’s Length entry. + i) Set the encryption key to the first n bytes of the output from the + final MD5 hash, where n shall always be 5 + for security handlers of revision 2 but, for security handlers of + revision 3 or greater, shall depend on the + value of the encryption dictionary’s Length entry. + + Args: + password: The encryption secret as a bytes-string + rev: The encryption revision (see PDF standard) + key_size: The size of the key in bytes + o_entry: The owner entry + P: A set of flags specifying which operations shall be permitted + when the document is opened with user access. If bit 2 is set to 1, + all other bits are ignored and all operations are permitted. + If bit 2 is set to 0, permission for operations are based on the + values of the remaining flags defined in Table 24. + id1_entry: + metadata_encrypted: A boolean indicating if the metadata is encrypted. + + Returns: + The u_hash digest of length key_size + + """ + a = _padding(password) + u_hash = hashlib.md5(a) + u_hash.update(o_entry) + u_hash.update(struct.pack("= 4 and not metadata_encrypted: + u_hash.update(b"\xff\xff\xff\xff") + u_hash_digest = u_hash.digest() + length = key_size // 8 + if rev >= 3: + for _ in range(50): + u_hash_digest = hashlib.md5(u_hash_digest[:length]).digest() + return u_hash_digest[:length] + + @staticmethod + def compute_O_value_key(owner_password: bytes, rev: int, key_size: int) -> bytes: + """ + Algorithm 3: Computing the encryption dictionary’s O (owner password) value. + + a) Pad or truncate the owner password string as described in step (a) + of "Algorithm 2: Computing an encryption key". + If there is no owner password, use the user password instead. + b) Initialize the MD5 hash function and pass the result of step (a) as + input to this function. + c) (Security handlers of revision 3 or greater) Do the following 50 times: + Take the output from the previous + MD5 hash and pass it as input into a new MD5 hash. + d) Create an RC4 encryption key using the first n bytes of the output + from the final MD5 hash, where n shall + always be 5 for security handlers of revision 2 but, for security + handlers of revision 3 or greater, shall + depend on the value of the encryption dictionary’s Length entry. + e) Pad or truncate the user password string as described in step (a) of + "Algorithm 2: Computing an encryption key". + f) Encrypt the result of step (e), using an RC4 encryption function with + the encryption key obtained in step (d). + g) (Security handlers of revision 3 or greater) Do the following 19 times: + Take the output from the previous + invocation of the RC4 function and pass it as input to a new + invocation of the function; use an encryption + key generated by taking each byte of the encryption key obtained in + step (d) and performing an XOR + (exclusive or) operation between that byte and the single-byte value + of the iteration counter (from 1 to 19). + h) Store the output from the final invocation of the RC4 function as + the value of the O entry in the encryption dictionary. + + Args: + owner_password: + rev: The encryption revision (see PDF standard) + key_size: The size of the key in bytes + + Returns: + The RC4 key + + """ + a = _padding(owner_password) + o_hash_digest = hashlib.md5(a).digest() + + if rev >= 3: + for _ in range(50): + o_hash_digest = hashlib.md5(o_hash_digest).digest() + + return o_hash_digest[: key_size // 8] + + @staticmethod + def compute_O_value(rc4_key: bytes, user_password: bytes, rev: int) -> bytes: + """ + See :func:`compute_O_value_key`. + + Args: + rc4_key: + user_password: + rev: The encryption revision (see PDF standard) + + Returns: + The RC4 encrypted + + """ + a = _padding(user_password) + rc4_enc = rc4_encrypt(rc4_key, a) + if rev >= 3: + for i in range(1, 20): + key = bytes(x ^ i for x in rc4_key) + rc4_enc = rc4_encrypt(key, rc4_enc) + return rc4_enc + + @staticmethod + def compute_U_value(key: bytes, rev: int, id1_entry: bytes) -> bytes: + """ + Algorithm 4: Computing the encryption dictionary’s U (user password) value. + + (Security handlers of revision 2) + + a) Create an encryption key based on the user password string, as + described in "Algorithm 2: Computing an encryption key". + b) Encrypt the 32-byte padding string shown in step (a) of + "Algorithm 2: Computing an encryption key", using an RC4 encryption + function with the encryption key from the preceding step. + c) Store the result of step (b) as the value of the U entry in the + encryption dictionary. + + Args: + key: + rev: The encryption revision (see PDF standard) + id1_entry: + + Returns: + The value + + """ + if rev <= 2: + return rc4_encrypt(key, _PADDING) + + """ + Algorithm 5: Computing the encryption dictionary’s U (user password) value. + + (Security handlers of revision 3 or greater) + + a) Create an encryption key based on the user password string, as + described in "Algorithm 2: Computing an encryption key". + b) Initialize the MD5 hash function and pass the 32-byte padding string + shown in step (a) of "Algorithm 2: + Computing an encryption key" as input to this function. + c) Pass the first element of the file’s file identifier array (the value + of the ID entry in the document’s trailer + dictionary; see Table 15) to the hash function and finish the hash. + d) Encrypt the 16-byte result of the hash, using an RC4 encryption + function with the encryption key from step (a). + e) Do the following 19 times: Take the output from the previous + invocation of the RC4 function and pass it as input to a new + invocation of the function; use an encryption key generated by + taking each byte of the original encryption key obtained in + step (a) and performing an XOR (exclusive or) operation between that + byte and the single-byte value of the iteration counter (from 1 to 19). + f) Append 16 bytes of arbitrary padding to the output from the final + invocation of the RC4 function and store the 32-byte result as the + value of the U entry in the encryption dictionary. + """ + u_hash = hashlib.md5(_PADDING) + u_hash.update(id1_entry) + rc4_enc = rc4_encrypt(key, u_hash.digest()) + for i in range(1, 20): + rc4_key = bytes(x ^ i for x in key) + rc4_enc = rc4_encrypt(rc4_key, rc4_enc) + return _padding(rc4_enc) + + @staticmethod + def verify_user_password( + user_password: bytes, + rev: int, + key_size: int, + o_entry: bytes, + u_entry: bytes, + P: int, + id1_entry: bytes, + metadata_encrypted: bool, + ) -> bytes: + """ + Algorithm 6: Authenticating the user password. + + a) Perform all but the last step of "Algorithm 4: Computing the + encryption dictionary’s U (user password) value (Security handlers of + revision 2)" or "Algorithm 5: Computing the encryption dictionary’s U + (user password) value (Security handlers of revision 3 or greater)" + using the supplied password string. + b) If the result of step (a) is equal to the value of the encryption + dictionary’s U entry (comparing on the first 16 bytes in the case of + security handlers of revision 3 or greater), the password supplied is + the correct user password. The key obtained in step (a) (that is, in + the first step of "Algorithm 4: Computing the encryption + dictionary’s U (user password) value + (Security handlers of revision 2)" or + "Algorithm 5: Computing the encryption dictionary’s U (user password) + value (Security handlers of revision 3 or greater)") shall be used + to decrypt the document. + + Args: + user_password: The user password as a bytes stream + rev: The encryption revision (see PDF standard) + key_size: The size of the key in bytes + o_entry: The owner entry + u_entry: The user entry + P: A set of flags specifying which operations shall be permitted + when the document is opened with user access. If bit 2 is set to 1, + all other bits are ignored and all operations are permitted. + If bit 2 is set to 0, permission for operations are based on the + values of the remaining flags defined in Table 24. + id1_entry: + metadata_encrypted: A boolean indicating if the metadata is encrypted. + + Returns: + The key + + """ + key = AlgV4.compute_key( + user_password, rev, key_size, o_entry, P, id1_entry, metadata_encrypted + ) + u_value = AlgV4.compute_U_value(key, rev, id1_entry) + if rev >= 3: + u_value = u_value[:16] + u_entry = u_entry[:16] + if u_value != u_entry: + key = b"" + return key + + @staticmethod + def verify_owner_password( + owner_password: bytes, + rev: int, + key_size: int, + o_entry: bytes, + u_entry: bytes, + P: int, + id1_entry: bytes, + metadata_encrypted: bool, + ) -> bytes: + """ + Algorithm 7: Authenticating the owner password. + + a) Compute an encryption key from the supplied password string, as + described in steps (a) to (d) of + "Algorithm 3: Computing the encryption dictionary’s O (owner password) + value". + b) (Security handlers of revision 2 only) Decrypt the value of the + encryption dictionary’s O entry, using an RC4 + encryption function with the encryption key computed in step (a). + (Security handlers of revision 3 or greater) Do the following 20 times: + Decrypt the value of the encryption dictionary’s O entry (first iteration) + or the output from the previous iteration (all subsequent iterations), + using an RC4 encryption function with a different encryption key at + each iteration. The key shall be generated by taking the original key + (obtained in step (a)) and performing an XOR (exclusive or) operation + between each byte of the key and the single-byte value of the + iteration counter (from 19 to 0). + c) The result of step (b) purports to be the user password. + Authenticate this user password using + "Algorithm 6: Authenticating the user password". + If it is correct, the password supplied is the correct owner password. + + Args: + owner_password: + rev: The encryption revision (see PDF standard) + key_size: The size of the key in bytes + o_entry: The owner entry + u_entry: The user entry + P: A set of flags specifying which operations shall be permitted + when the document is opened with user access. If bit 2 is set to 1, + all other bits are ignored and all operations are permitted. + If bit 2 is set to 0, permission for operations are based on the + values of the remaining flags defined in Table 24. + id1_entry: + metadata_encrypted: A boolean indicating if the metadata is encrypted. + + Returns: + bytes + + """ + rc4_key = AlgV4.compute_O_value_key(owner_password, rev, key_size) + + if rev <= 2: + user_password = rc4_decrypt(rc4_key, o_entry) + else: + user_password = o_entry + for i in range(19, -1, -1): + key = bytes(x ^ i for x in rc4_key) + user_password = rc4_decrypt(key, user_password) + return AlgV4.verify_user_password( + user_password, + rev, + key_size, + o_entry, + u_entry, + P, + id1_entry, + metadata_encrypted, + ) + + +class AlgV5: + @staticmethod + def verify_owner_password( + R: int, password: bytes, o_value: bytes, oe_value: bytes, u_value: bytes + ) -> bytes: + """ + Algorithm 3.2a Computing an encryption key. + + To understand the algorithm below, it is necessary to treat the O and U + strings in the Encrypt dictionary as made up of three sections. + The first 32 bytes are a hash value (explained below). The next 8 bytes + are called the Validation Salt. The final 8 bytes are called the Key Salt. + + 1. The password string is generated from Unicode input by processing the + input string with the SASLprep (IETF RFC 4013) profile of + stringprep (IETF RFC 3454), and then converting to a UTF-8 + representation. + 2. Truncate the UTF-8 representation to 127 bytes if it is longer than + 127 bytes. + 3. Test the password against the owner key by computing the SHA-256 hash + of the UTF-8 password concatenated with the 8 bytes of owner + Validation Salt, concatenated with the 48-byte U string. If the + 32-byte result matches the first 32 bytes of the O string, this is + the owner password. + Compute an intermediate owner key by computing the SHA-256 hash of + the UTF-8 password concatenated with the 8 bytes of owner Key Salt, + concatenated with the 48-byte U string. The 32-byte result is the + key used to decrypt the 32-byte OE string using AES-256 in CBC mode + with no padding and an initialization vector of zero. + The 32-byte result is the file encryption key. + 4. Test the password against the user key by computing the SHA-256 hash + of the UTF-8 password concatenated with the 8 bytes of user + Validation Salt. If the 32 byte result matches the first 32 bytes of + the U string, this is the user password. + Compute an intermediate user key by computing the SHA-256 hash of the + UTF-8 password concatenated with the 8 bytes of user Key Salt. + The 32-byte result is the key used to decrypt the 32-byte + UE string using AES-256 in CBC mode with no padding and an + initialization vector of zero. The 32-byte result is the file + encryption key. + 5. Decrypt the 16-byte Perms string using AES-256 in ECB mode with an + initialization vector of zero and the file encryption key as the key. + Verify that bytes 9-11 of the result are the characters ‘a’, ‘d’, ‘b’. + Bytes 0-3 of the decrypted Perms entry, treated as a little-endian + integer, are the user permissions. + They should match the value in the P key. + + Args: + R: A number specifying which revision of the standard security + handler shall be used to interpret this dictionary + password: The owner password + o_value: A 32-byte string, based on both the owner and user passwords, + that shall be used in computing the encryption key and in + determining whether a valid owner password was entered + oe_value: + u_value: A 32-byte string, based on the user password, that shall be + used in determining whether to prompt the user for a password and, + if so, whether a valid user or owner password was entered. + + Returns: + The key + + """ + password = password[:127] + if ( + AlgV5.calculate_hash(R, password, o_value[32:40], u_value[:48]) + != o_value[:32] + ): + return b"" + iv = bytes(0 for _ in range(16)) + tmp_key = AlgV5.calculate_hash(R, password, o_value[40:48], u_value[:48]) + return aes_cbc_decrypt(tmp_key, iv, oe_value) + + @staticmethod + def verify_user_password( + R: int, password: bytes, u_value: bytes, ue_value: bytes + ) -> bytes: + """ + See :func:`verify_owner_password`. + + Args: + R: A number specifying which revision of the standard security + handler shall be used to interpret this dictionary + password: The user password + u_value: A 32-byte string, based on the user password, that shall be + used in determining whether to prompt the user for a password + and, if so, whether a valid user or owner password was entered. + ue_value: + + Returns: + bytes + + """ + password = password[:127] + if AlgV5.calculate_hash(R, password, u_value[32:40], b"") != u_value[:32]: + return b"" + iv = bytes(0 for _ in range(16)) + tmp_key = AlgV5.calculate_hash(R, password, u_value[40:48], b"") + return aes_cbc_decrypt(tmp_key, iv, ue_value) + + @staticmethod + def calculate_hash(R: int, password: bytes, salt: bytes, udata: bytes) -> bytes: + # https://github.com/qpdf/qpdf/blob/main/libqpdf/QPDF_encryption.cc + k = hashlib.sha256(password + salt + udata).digest() + if R < 6: + return k + count = 0 + while True: + count += 1 + k1 = password + k + udata + e = aes_cbc_encrypt(k[:16], k[16:32], k1 * 64) + hash_fn = ( + hashlib.sha256, + hashlib.sha384, + hashlib.sha512, + )[sum(e[:16]) % 3] + k = hash_fn(e).digest() + if count >= 64 and e[-1] <= count - 32: + break + return k[:32] + + @staticmethod + def verify_perms( + key: bytes, perms: bytes, p: int, metadata_encrypted: bool + ) -> bool: + """ + See :func:`verify_owner_password` and :func:`compute_perms_value`. + + Args: + key: The owner password + perms: + p: A set of flags specifying which operations shall be permitted + when the document is opened with user access. + If bit 2 is set to 1, all other bits are ignored and all + operations are permitted. + If bit 2 is set to 0, permission for operations are based on + the values of the remaining flags defined in Table 24. + metadata_encrypted: + + Returns: + A boolean + + """ + b8 = b"T" if metadata_encrypted else b"F" + p1 = struct.pack(" dict[Any, Any]: + user_password = user_password[:127] + owner_password = owner_password[:127] + u_value, ue_value = AlgV5.compute_U_value(R, user_password, key) + o_value, oe_value = AlgV5.compute_O_value(R, owner_password, key, u_value) + perms = AlgV5.compute_Perms_value(key, p, metadata_encrypted) + return { + "/U": u_value, + "/UE": ue_value, + "/O": o_value, + "/OE": oe_value, + "/Perms": perms, + } + + @staticmethod + def compute_U_value(R: int, password: bytes, key: bytes) -> tuple[bytes, bytes]: + """ + Algorithm 3.8 Computing the encryption dictionary’s U (user password) + and UE (user encryption key) values. + + 1. Generate 16 random bytes of data using a strong random number generator. + The first 8 bytes are the User Validation Salt. The second 8 bytes + are the User Key Salt. Compute the 32-byte SHA-256 hash of the + password concatenated with the User Validation Salt. The 48-byte + string consisting of the 32-byte hash followed by the User + Validation Salt followed by the User Key Salt is stored as the U key. + 2. Compute the 32-byte SHA-256 hash of the password concatenated with + the User Key Salt. Using this hash as the key, encrypt the file + encryption key using AES-256 in CBC mode with no padding and an + initialization vector of zero. The resulting 32-byte string is stored + as the UE key. + + Args: + R: + password: + key: + + Returns: + A tuple (u-value, ue value) + + """ + random_bytes = secrets.token_bytes(16) + val_salt = random_bytes[:8] + key_salt = random_bytes[8:] + u_value = AlgV5.calculate_hash(R, password, val_salt, b"") + val_salt + key_salt + + tmp_key = AlgV5.calculate_hash(R, password, key_salt, b"") + iv = bytes(0 for _ in range(16)) + ue_value = aes_cbc_encrypt(tmp_key, iv, key) + return u_value, ue_value + + @staticmethod + def compute_O_value( + R: int, password: bytes, key: bytes, u_value: bytes + ) -> tuple[bytes, bytes]: + """ + Algorithm 3.9 Computing the encryption dictionary’s O (owner password) + and OE (owner encryption key) values. + + 1. Generate 16 random bytes of data using a strong random number + generator. The first 8 bytes are the Owner Validation Salt. The + second 8 bytes are the Owner Key Salt. Compute the 32-byte SHA-256 + hash of the password concatenated with the Owner Validation Salt and + then concatenated with the 48-byte U string as generated in + Algorithm 3.8. The 48-byte string consisting of the 32-byte hash + followed by the Owner Validation Salt followed by the Owner Key Salt + is stored as the O key. + 2. Compute the 32-byte SHA-256 hash of the password concatenated with + the Owner Key Salt and then concatenated with the 48-byte U string as + generated in Algorithm 3.8. Using this hash as the key, + encrypt the file encryption key using AES-256 in CBC mode with + no padding and an initialization vector of zero. + The resulting 32-byte string is stored as the OE key. + + Args: + R: + password: + key: + u_value: A 32-byte string, based on the user password, that shall be + used in determining whether to prompt the user for a password + and, if so, whether a valid user or owner password was entered. + + Returns: + A tuple (O value, OE value) + + """ + random_bytes = secrets.token_bytes(16) + val_salt = random_bytes[:8] + key_salt = random_bytes[8:] + o_value = ( + AlgV5.calculate_hash(R, password, val_salt, u_value) + val_salt + key_salt + ) + tmp_key = AlgV5.calculate_hash(R, password, key_salt, u_value[:48]) + iv = bytes(0 for _ in range(16)) + oe_value = aes_cbc_encrypt(tmp_key, iv, key) + return o_value, oe_value + + @staticmethod + def compute_Perms_value(key: bytes, p: int, metadata_encrypted: bool) -> bytes: + """ + Algorithm 3.10 Computing the encryption dictionary’s Perms + (permissions) value. + + 1. Extend the permissions (contents of the P integer) to 64 bits by + setting the upper 32 bits to all 1’s. + (This allows for future extension without changing the format.) + 2. Record the 8 bytes of permission in the bytes 0-7 of the block, + low order byte first. + 3. Set byte 8 to the ASCII value ' T ' or ' F ' according to the + EncryptMetadata Boolean. + 4. Set bytes 9-11 to the ASCII characters ' a ', ' d ', ' b '. + 5. Set bytes 12-15 to 4 bytes of random data, which will be ignored. + 6. Encrypt the 16-byte block using AES-256 in ECB mode with an + initialization vector of zero, using the file encryption key as the + key. The result (16 bytes) is stored as the Perms string, and checked + for validity when the file is opened. + + Args: + key: + p: A set of flags specifying which operations shall be permitted + when the document is opened with user access. If bit 2 is set to 1, + all other bits are ignored and all operations are permitted. + If bit 2 is set to 0, permission for operations are based on the + values of the remaining flags defined in Table 24. + metadata_encrypted: A boolean indicating if the metadata is encrypted. + + Returns: + The perms value + + """ + b8 = b"T" if metadata_encrypted else b"F" + rr = secrets.token_bytes(4) + data = struct.pack(" None: + # §7.6.2, entries common to all encryption dictionaries + # use same name as keys of encryption dictionaries entries + self.V = V + self.R = R + self.Length = Length # key_size + self.P = (P + 0x100000000) % 0x100000000 # maybe P < 0 + self.EncryptMetadata = EncryptMetadata + self.id1_entry = first_id_entry + self.StmF = StmF + self.StrF = StrF + self.EFF = EFF + self.values: EncryptionValues = values or EncryptionValues() + + self._password_type = PasswordType.NOT_DECRYPTED + self._key: Optional[bytes] = None + self._are_permissions_valid: bool = True + + def is_decrypted(self) -> bool: + return self._password_type != PasswordType.NOT_DECRYPTED + + def encrypt_object(self, obj: PdfObject, idnum: int, generation: int) -> PdfObject: + # skip calculate key + if not self._is_encryption_object(obj): + return obj + + cf = self._make_crypt_filter(idnum, generation) + return cf.encrypt_object(obj) + + def decrypt_object(self, obj: PdfObject, idnum: int, generation: int, *, strict: bool = True) -> PdfObject: + # skip calculate key + if not self._is_encryption_object(obj): + return obj + + cf = self._make_crypt_filter(idnum, generation) + return cf.decrypt_object(obj, strict=strict) + + @staticmethod + def _is_encryption_object(obj: PdfObject) -> bool: + return isinstance( + obj, + ( + ByteStringObject, + TextStringObject, + StreamObject, + ArrayObject, + DictionaryObject, + ), + ) + + def _make_crypt_filter(self, idnum: int, generation: int) -> CryptFilter: + """ + Algorithm 1: Encryption of data using the RC4 or AES algorithms. + + a) Obtain the object number and generation number from the object + identifier of the string or stream to be encrypted + (see 7.3.10, "Indirect Objects"). If the string is a direct object, + use the identifier of the indirect object containing it. + b) For all strings and streams without crypt filter specifier; treating + the object number and generation number as binary integers, extend + the original n-byte encryption key to n + 5 bytes by appending the + low-order 3 bytes of the object number and the low-order 2 bytes of + the generation number in that order, low-order byte first. + (n is 5 unless the value of V in the encryption dictionary is greater + than 1, in which case n is the value of Length divided by 8.) + If using the AES algorithm, extend the encryption key an additional + 4 bytes by adding the value “sAlT”, which corresponds to the + hexadecimal values 0x73, 0x41, 0x6C, 0x54. (This addition is done for + backward compatibility and is not intended to provide additional + security.) + c) Initialize the MD5 hash function and pass the result of step (b) as + input to this function. + d) Use the first (n + 5) bytes, up to a maximum of 16, of the output + from the MD5 hash as the key for the RC4 or AES symmetric key + algorithms, along with the string or stream data to be encrypted. + If using the AES algorithm, the Cipher Block Chaining (CBC) mode, + which requires an initialization vector, is used. The block size + parameter is set to 16 bytes, and the initialization vector is a + 16-byte random number that is stored as the first 16 bytes of the + encrypted stream or string. + + Algorithm 3.1a: Encryption of data using the AES-256 algorithm. + + Note: Algorithm 3.1a does not use MD5 key derivation, so AES-256 + encrypted files can be read on FIPS-enabled systems where MD5 is blocked. + + 1. Use the 32-byte file encryption key for the AES-256 symmetric key + algorithm, along with the string or stream data to be encrypted. + Use the AES algorithm in Cipher Block Chaining (CBC) mode, which + requires an initialization vector. The block size parameter is set to + 16 bytes, and the initialization vector is a 16-byte random number + that is stored as the first 16 bytes of the encrypted stream or string. + The output is the encrypted data to be stored in the PDF file. + """ + pack1 = struct.pack("= 5): key used directly. + if self.V <= 4: + n = 5 if self.V == 1 else self.Length // 8 + key_data = key[:n] + pack1 + pack2 + key_hash = hashlib.md5(key_data) + rc4_key = key_hash.digest()[: min(n + 5, 16)] + + # for AES-128 + key_hash.update(b"sAlT") + aes128_key = key_hash.digest()[: min(n + 5, 16)] + else: + rc4_key = b"" + aes128_key = b"" + + # for AES-256 + aes256_key = key + + stm_crypt = self._get_crypt(self.StmF, rc4_key, aes128_key, aes256_key) + str_crypt = self._get_crypt(self.StrF, rc4_key, aes128_key, aes256_key) + ef_crypt = self._get_crypt(self.EFF, rc4_key, aes128_key, aes256_key) + + return CryptFilter(stm_crypt, str_crypt, ef_crypt) + + @staticmethod + def _get_crypt( + method: str, rc4_key: bytes, aes128_key: bytes, aes256_key: bytes + ) -> CryptBase: + if method == "/AESV2": + return CryptAES(aes128_key) + if method == "/AESV3": + return CryptAES(aes256_key) + if method == "/Identity": + return CryptIdentity() + + return CryptRC4(rc4_key) + + @staticmethod + def _encode_password(password: Union[bytes, str]) -> bytes: + if isinstance(password, str): + try: + pwd = password.encode("latin-1") + except Exception: + pwd = password.encode("utf-8") + else: + pwd = password + return pwd + + def verify(self, password: Union[bytes, str]) -> PasswordType: + pwd = self._encode_password(password) + key, rc = self.verify_v4(pwd) if self.V <= 4 else self.verify_v5(pwd) + if rc != PasswordType.NOT_DECRYPTED: + self._password_type = rc + self._key = key + return rc + + def verify_v4(self, password: bytes) -> tuple[bytes, PasswordType]: + # verify owner password first + key = AlgV4.verify_owner_password( + password, + self.R, + self.Length, + self.values.O, + self.values.U, + self.P, + self.id1_entry, + self.EncryptMetadata, + ) + if key: + return key, PasswordType.OWNER_PASSWORD + key = AlgV4.verify_user_password( + password, + self.R, + self.Length, + self.values.O, + self.values.U, + self.P, + self.id1_entry, + self.EncryptMetadata, + ) + if key: + return key, PasswordType.USER_PASSWORD + return b"", PasswordType.NOT_DECRYPTED + + def verify_v5(self, password: bytes) -> tuple[bytes, PasswordType]: + # TODO: use SASLprep process + # verify owner password first + key = AlgV5.verify_owner_password( + self.R, password, self.values.O, self.values.OE, self.values.U + ) + rc = PasswordType.OWNER_PASSWORD + if not key: + key = AlgV5.verify_user_password( + self.R, password, self.values.U, self.values.UE + ) + rc = PasswordType.USER_PASSWORD + if not key: + return b"", PasswordType.NOT_DECRYPTED + + # verify Perms + self._are_permissions_valid = AlgV5.verify_perms(key, self.values.Perms, self.P, self.EncryptMetadata) + if not self._are_permissions_valid: + logger_warning("ignore '/Perms' verify failed", __name__) + return key, rc + + def write_entry( + self, user_password: str, owner_password: Optional[str] + ) -> DictionaryObject: + user_pwd = self._encode_password(user_password) + owner_pwd = self._encode_password(owner_password) if owner_password else None + if owner_pwd is None: + owner_pwd = user_pwd + + if self.V <= 4: + self.compute_values_v4(user_pwd, owner_pwd) + else: + self._key = secrets.token_bytes(self.Length // 8) + values = AlgV5.generate_values( + self.R, user_pwd, owner_pwd, self._key, self.P, self.EncryptMetadata + ) + self.values.O = values["/O"] + self.values.U = values["/U"] + self.values.OE = values["/OE"] + self.values.UE = values["/UE"] + self.values.Perms = values["/Perms"] + + dict_obj = DictionaryObject() + dict_obj[NameObject("/V")] = NumberObject(self.V) + dict_obj[NameObject("/R")] = NumberObject(self.R) + dict_obj[NameObject("/Length")] = NumberObject(self.Length) + dict_obj[NameObject("/P")] = NumberObject(self.P) + dict_obj[NameObject("/Filter")] = NameObject("/Standard") + # ignore /EncryptMetadata + + dict_obj[NameObject("/O")] = ByteStringObject(self.values.O) + dict_obj[NameObject("/U")] = ByteStringObject(self.values.U) + + if self.V >= 4: + # TODO: allow different method + std_cf = DictionaryObject() + std_cf[NameObject("/AuthEvent")] = NameObject("/DocOpen") + std_cf[NameObject("/CFM")] = NameObject(self.StmF) + std_cf[NameObject("/Length")] = NumberObject(self.Length // 8) + cf = DictionaryObject() + cf[NameObject("/StdCF")] = std_cf + dict_obj[NameObject("/CF")] = cf + dict_obj[NameObject("/StmF")] = NameObject("/StdCF") + dict_obj[NameObject("/StrF")] = NameObject("/StdCF") + # ignore EFF + # dict_obj[NameObject("/EFF")] = NameObject("/StdCF") + + if self.V >= 5: + dict_obj[NameObject("/OE")] = ByteStringObject(self.values.OE) + dict_obj[NameObject("/UE")] = ByteStringObject(self.values.UE) + dict_obj[NameObject("/Perms")] = ByteStringObject(self.values.Perms) + return dict_obj + + def compute_values_v4(self, user_password: bytes, owner_password: bytes) -> None: + rc4_key = AlgV4.compute_O_value_key(owner_password, self.R, self.Length) + o_value = AlgV4.compute_O_value(rc4_key, user_password, self.R) + + key = AlgV4.compute_key( + user_password, + self.R, + self.Length, + o_value, + self.P, + self.id1_entry, + self.EncryptMetadata, + ) + u_value = AlgV4.compute_U_value(key, self.R, self.id1_entry) + + self._key = key + self.values.O = o_value + self.values.U = u_value + + @staticmethod + def read(encryption_entry: DictionaryObject, first_id_entry: bytes) -> "Encryption": + if encryption_entry.get("/Filter") != "/Standard": + raise NotImplementedError( + "only Standard PDF encryption handler is available" + ) + if "/SubFilter" in encryption_entry: + raise NotImplementedError("/SubFilter NOT supported") + + stm_filter = "/V2" + str_filter = "/V2" + ef_filter = "/V2" + + alg_ver = encryption_entry.get("/V", 0) + if alg_ver not in (1, 2, 3, 4, 5): + raise NotImplementedError(f"Encryption V={alg_ver} NOT supported") + if alg_ver >= 4: + filters = encryption_entry["/CF"] + + stm_filter = encryption_entry.get("/StmF", "/Identity") + str_filter = encryption_entry.get("/StrF", "/Identity") + ef_filter = encryption_entry.get("/EFF", stm_filter) + + if stm_filter != "/Identity": + stm_filter = filters[stm_filter]["/CFM"] # type: ignore + if str_filter != "/Identity": + str_filter = filters[str_filter]["/CFM"] # type: ignore + if ef_filter != "/Identity": + ef_filter = filters[ef_filter]["/CFM"] # type: ignore + + allowed_methods = ("/Identity", "/V2", "/AESV2", "/AESV3") + if stm_filter not in allowed_methods: + raise NotImplementedError(f"StmF Method {stm_filter} NOT supported!") + if str_filter not in allowed_methods: + raise NotImplementedError(f"StrF Method {str_filter} NOT supported!") + if ef_filter not in allowed_methods: + raise NotImplementedError(f"EFF Method {ef_filter} NOT supported!") + + alg_rev = cast(int, encryption_entry["/R"]) + perm_flags = cast(int, encryption_entry["/P"]) + key_bits = encryption_entry.get("/Length", 40) + if alg_ver == 4 and stm_filter == "/AESV2": + cf_dict = cast(DictionaryObject, filters[encryption_entry["/StmF"]]) # type: ignore[index] + # CF /Length is in bytes (default 16 for AES-128), convert to bits + key_bits = cast(int, cf_dict.get("/Length", 16)) * 8 + encrypt_metadata = encryption_entry.get("/EncryptMetadata") + encrypt_metadata = ( + encrypt_metadata.value if encrypt_metadata is not None else True + ) + values = EncryptionValues() + values.O = cast(ByteStringObject, encryption_entry["/O"]).original_bytes + values.U = cast(ByteStringObject, encryption_entry["/U"]).original_bytes + values.OE = encryption_entry.get("/OE", ByteStringObject()).original_bytes + values.UE = encryption_entry.get("/UE", ByteStringObject()).original_bytes + values.Perms = encryption_entry.get("/Perms", ByteStringObject()).original_bytes + return Encryption( + V=alg_ver, + R=alg_rev, + Length=key_bits, + P=perm_flags, + EncryptMetadata=encrypt_metadata, + first_id_entry=first_id_entry, + values=values, + StrF=str_filter, + StmF=stm_filter, + EFF=ef_filter, + entry=encryption_entry, # Dummy entry for the moment; will get removed + ) + + @staticmethod + def make( + alg: EncryptAlgorithm, permissions: int, first_id_entry: bytes + ) -> "Encryption": + alg_ver, alg_rev, key_bits = alg + + stm_filter, str_filter, ef_filter = "/V2", "/V2", "/V2" + + if alg == EncryptAlgorithm.AES_128: + stm_filter, str_filter, ef_filter = "/AESV2", "/AESV2", "/AESV2" + elif alg in (EncryptAlgorithm.AES_256_R5, EncryptAlgorithm.AES_256): + stm_filter, str_filter, ef_filter = "/AESV3", "/AESV3", "/AESV3" + + return Encryption( + V=alg_ver, + R=alg_rev, + Length=key_bits, + P=permissions, + EncryptMetadata=True, + first_id_entry=first_id_entry, + values=None, + StrF=str_filter, + StmF=stm_filter, + EFF=ef_filter, + entry=DictionaryObject(), # Dummy entry for the moment; will get removed + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_font.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_font.py new file mode 100644 index 0000000000000000000000000000000000000000..c66403ebafdbe0d8cee0646fbc8827340d849fb1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_font.py @@ -0,0 +1,513 @@ +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any, cast + +from pypdf.generic import ArrayObject, DictionaryObject, NameObject, NumberObject, StreamObject + +from ._cmap import get_encoding +from ._codecs.adobe_glyphs import adobe_glyphs +from ._utils import logger_warning +from .constants import FontFlags +from .errors import PdfReadError + +if TYPE_CHECKING: + from io import BytesIO + + from fontTools.ttLib.tables._h_e_a_d import table__h_e_a_d + from fontTools.ttLib.tables._p_o_s_t import table__p_o_s_t + from fontTools.ttLib.tables.O_S_2f_2 import table_O_S_2f_2 + +try: + from fontTools.ttLib import TTFont + HAS_FONTTOOLS = True +except ImportError: + HAS_FONTTOOLS = False + + +# Some constants from truetype font tables that we use: +HEADER_MACSTYLE_ITALIC = 0x02 +OS2_FSSELECTION_ITALIC = 0x01 +OS2_PANOSE_BFAMILYTYPE_SCRIPT = 3 +OS2_PANOSE_BFAMILYTYPE_DECORATIVE = 4 +OS2_PANOSE_BFAMILYTYPE_PICTORIAL = 5 +OS2_PANOSE_BPROPORTION_MONOSPACED = 9 +OS2_SFAMILYSCLASS_SCRIPTS = 10 +OS2_SFAMILYSCLASS_SYMBOLIC = 12 + + +@dataclass(frozen=True) +class FontDescriptor: + """ + Represents the FontDescriptor dictionary as defined in the PDF specification. + This contains both descriptive and metric information. + + The defaults are derived from the mean values of the 14 core fonts, rounded + to 100. + """ + + name: str = "Unknown" + family: str = "Unknown" + weight: str = "Unknown" + + ascent: float = 700.0 + descent: float = -200.0 + cap_height: float = 600.0 + x_height: float = 500.0 + italic_angle: float = 0.0 # Non-italic + flags: int = 32 # Non-serif, non-symbolic, not fixed width + bbox: tuple[float, float, float, float] = field(default_factory=lambda: (-100.0, -200.0, 1000.0, 900.0)) + font_file: StreamObject | None = None + + +@dataclass(frozen=True) +class CoreFontMetrics: + font_descriptor: FontDescriptor + character_widths: dict[str, int] + + +@dataclass +class Font: + """ + A font object for use during text extraction and for producing + text appearance streams. + + Attributes: + name: Font name, derived from font["/BaseFont"] + character_map: The font's character map + encoding: Font encoding + sub_type: The font type, such as Type1, TrueType, or Type3. + font_descriptor: Font metrics, including a mapping of characters to widths + character_widths: A mapping of characters to widths + space_width: The width of a space, or an approximation + interpretable: Default True. If False, the font glyphs cannot + be translated to characters, e.g. Type3 fonts that do not define + a '/ToUnicode' mapping. + + """ + + name: str + encoding: str | dict[int, str] + character_map: dict[Any, Any] = field(default_factory=dict) + sub_type: str = "Unknown" + font_descriptor: FontDescriptor = field(default_factory=FontDescriptor) + character_widths: dict[str, int] = field(default_factory=lambda: {"default": 500}) + space_width: float | int = 250 + interpretable: bool = True + + @staticmethod + def _collect_tt_t1_character_widths( + pdf_font_dict: DictionaryObject, + char_map: dict[Any, Any], + encoding: str | dict[int, str], + current_widths: dict[str, int] + ) -> None: + """Parses a TrueType or Type1 font's /Widths array from a font dictionary and updates character widths""" + widths_array = cast(ArrayObject, pdf_font_dict["/Widths"]) + first_char = pdf_font_dict.get("/FirstChar", 0) + if not isinstance(encoding, str): + # This means that encoding is a dict + current_widths.update({ + encoding.get(idx + first_char, chr(idx + first_char)): width + for idx, width in enumerate(widths_array) + }) + return + + # We map the character code directly to the character + # using the string encoding + for idx, width in enumerate(widths_array): + # Often "idx == 0" will denote the .notdef character, but we add it anyway + char_code = idx + first_char # This is a raw code + # Get the "raw" character or byte representation + raw_char = bytes([char_code]).decode(encoding, "surrogatepass") + # Translate raw_char to the REAL Unicode character using the char_map + unicode_char = char_map.get(raw_char) + if unicode_char: + current_widths[unicode_char] = int(width) + else: + current_widths[raw_char] = int(width) + + @staticmethod + def _collect_cid_character_widths( + d_font: DictionaryObject, char_map: dict[Any, Any], current_widths: dict[str, int] + ) -> None: + """Parses the /W array from a DescendantFont dictionary and updates character widths.""" + ord_map = { + ord(_target): _surrogate + for _target, _surrogate in char_map.items() + if isinstance(_target, str) + } + # /W width definitions have two valid formats which can be mixed and matched: + # (1) A character start index followed by a list of widths, e.g. + # `45 [500 600 700]` applies widths 500, 600, 700 to characters 45-47. + # (2) A character start index, a character stop index, and a width, e.g. + # `45 65 500` applies width 500 to characters 45-65. + skip_count = 0 + _w = d_font.get("/W", []) + for idx, w_entry in enumerate(_w): + w_entry = w_entry.get_object() + if skip_count: + skip_count -= 1 + continue + if not isinstance(w_entry, (int, float)): + # We should never get here due to skip_count above. But + # sometimes we do. + logger_warning(f"Expected numeric value for width, got {w_entry}. Ignoring it.", __name__) + continue + # check for format (1): `int [int int int int ...]` + w_next_entry = _w[idx + 1].get_object() + if isinstance(w_next_entry, Sequence): + start_idx, width_list = w_entry, w_next_entry + current_widths.update( + { + ord_map[_cidx]: _width + for _cidx, _width in zip( + range( + cast(int, start_idx), + cast(int, start_idx) + len(width_list), + 1, + ), + width_list, + ) + if _cidx in ord_map + } + ) + skip_count = 1 + # check for format (2): `int int int` + elif isinstance(w_next_entry, (int, float)) and isinstance( + _w[idx + 2].get_object(), (int, float) + ): + start_idx, stop_idx, const_width = ( + w_entry, + w_next_entry, + _w[idx + 2].get_object(), + ) + current_widths.update( + { + ord_map[_cidx]: const_width + for _cidx in range( + cast(int, start_idx), cast(int, stop_idx + 1), 1 + ) + if _cidx in ord_map + } + ) + skip_count = 2 + else: + # This handles the case of out of bounds (reaching the end of the width definitions + # while expecting more elements). + logger_warning( + f"Invalid font width definition. Last element: {w_entry}.", + __name__ + ) + + @staticmethod + def _add_default_width(current_widths: dict[str, int], flags: int) -> None: + if not current_widths: + current_widths["default"] = 500 + return + + if " " in current_widths and current_widths[" "] != 0: + # Setting default to once or twice the space width, depending on fixed pitch + if (flags & FontFlags.FIXED_PITCH) == FontFlags.FIXED_PITCH: + current_widths["default"] = current_widths[" "] + return + + current_widths["default"] = int(2 * current_widths[" "]) + return + + # Use the average width of existing glyph widths + valid_widths = [w for w in current_widths.values() if w > 0] + current_widths["default"] = sum(valid_widths) // len(valid_widths) if valid_widths else 500 + + @staticmethod + def _add_space_width(character_widths: dict[str, int], flags: int) -> int: + space_width = character_widths.get(" ", 0) + if space_width != 0: + return space_width + + if (flags & FontFlags.FIXED_PITCH) == FontFlags.FIXED_PITCH: + return character_widths["default"] + + return character_widths["default"] // 2 + + @staticmethod + def _parse_font_descriptor(font_descriptor_obj: DictionaryObject) -> dict[str, Any]: + font_descriptor_kwargs: dict[Any, Any] = {} + for source_key, target_key in [ + ("/FontName", "name"), + ("/FontFamily", "family"), + ("/FontWeight", "weight"), + ("/Ascent", "ascent"), + ("/Descent", "descent"), + ("/CapHeight", "cap_height"), + ("/XHeight", "x_height"), + ("/ItalicAngle", "italic_angle"), + ("/Flags", "flags"), + ("/FontBBox", "bbox") + ]: + if source_key in font_descriptor_obj: + font_descriptor_kwargs[target_key] = font_descriptor_obj[source_key] + # Handle missing bbox gracefully - PDFs may have fonts without valid bounding boxes + if "bbox" in font_descriptor_kwargs: + bbox_tuple = tuple(map(float, font_descriptor_kwargs["bbox"])) + assert len(bbox_tuple) == 4, bbox_tuple + font_descriptor_kwargs["bbox"] = bbox_tuple + + # Find the binary stream for this font if there is one + for source_key in ["/FontFile", "/FontFile2", "/FontFile3"]: + if source_key in font_descriptor_obj: + if "font_file" in font_descriptor_kwargs: + raise PdfReadError(f"More than one /FontFile found in {font_descriptor_obj}") + + try: + font_file = font_descriptor_obj[source_key].get_object() + font_descriptor_kwargs["font_file"] = font_file + except PdfReadError as e: + logger_warning(f"Failed to get {source_key!r} in {font_descriptor_obj}: {e}", __name__) + return font_descriptor_kwargs + + @classmethod + def from_font_resource( + cls, + pdf_font_dict: DictionaryObject, + ) -> Font: + from pypdf._codecs.core_font_metrics import CORE_FONT_METRICS # noqa: PLC0415 + + # Can collect base_font, name and encoding directly from font resource + name = pdf_font_dict.get("/BaseFont", "Unknown").removeprefix("/") + sub_type = pdf_font_dict.get("/Subtype", "Unknown").removeprefix("/") + encoding, character_map = get_encoding(pdf_font_dict) + font_descriptor = None + character_widths: dict[str, int] = {} + interpretable = True + + # Deal with fonts by type; Type1, TrueType and certain Type3 + if pdf_font_dict.get("/Subtype") in ("/Type1", "/MMType1", "/TrueType", "/Type3"): + # Type3 fonts that do not specify a "/ToUnicode" mapping cannot be + # reliably converted into character codes unless all named chars + # in /CharProcs map to a standard adobe glyph. See §9.10.2 of the + # PDF 1.7 standard. + if sub_type == "Type3" and "/ToUnicode" not in pdf_font_dict: + interpretable = all( + cname in adobe_glyphs + for cname in pdf_font_dict.get("/CharProcs") or [] + ) + if interpretable: # Save some overhead if font is not interpretable + if "/Widths" in pdf_font_dict: + cls._collect_tt_t1_character_widths( + pdf_font_dict, character_map, encoding, character_widths + ) + elif name in CORE_FONT_METRICS: + font_descriptor = CORE_FONT_METRICS[name].font_descriptor + character_widths = CORE_FONT_METRICS[name].character_widths + if "/FontDescriptor" in pdf_font_dict: + font_descriptor_obj = pdf_font_dict.get("/FontDescriptor", DictionaryObject()).get_object() + if "/MissingWidth" in font_descriptor_obj: + character_widths["default"] = cast(int, font_descriptor_obj["/MissingWidth"].get_object()) + font_descriptor = FontDescriptor(**cls._parse_font_descriptor(font_descriptor_obj)) + elif "/FontBBox" in pdf_font_dict: + # For Type3 without Font Descriptor but with FontBBox, see Table 110 in the PDF specification 2.0 + bbox_tuple = tuple(map(float, cast(ArrayObject, pdf_font_dict["/FontBBox"]))) + assert len(bbox_tuple) == 4, bbox_tuple + font_descriptor = FontDescriptor(name=name, bbox=bbox_tuple) + + else: + # Composite font or CID font - CID fonts have a /W array mapping character codes + # to widths stashed in /DescendantFonts. No need to test for /DescendantFonts though, + # because all other fonts have already been dealt with. + d_font: DictionaryObject + for d_font_idx, d_font in enumerate( + cast(ArrayObject, pdf_font_dict["/DescendantFonts"]) + ): + d_font = cast(DictionaryObject, d_font.get_object()) + cast(ArrayObject, pdf_font_dict["/DescendantFonts"])[d_font_idx] = d_font + cls._collect_cid_character_widths( + d_font, character_map, character_widths + ) + if "/DW" in d_font: + character_widths["default"] = cast(int, d_font["/DW"].get_object()) + font_descriptor_obj = d_font.get("/FontDescriptor", DictionaryObject()).get_object() + font_descriptor = FontDescriptor(**cls._parse_font_descriptor(font_descriptor_obj)) + + if not font_descriptor: + font_descriptor = FontDescriptor(name=name) + + if character_widths.get("default", 0) == 0: + cls._add_default_width(character_widths, font_descriptor.flags) + + space_width = cls._add_space_width(character_widths, font_descriptor.flags) + + return cls( + name=name, + sub_type=sub_type, + encoding=encoding, + font_descriptor=font_descriptor, + character_map=character_map, + character_widths=character_widths, + space_width=space_width, + interpretable=interpretable + ) + + @staticmethod + def _font_flags_from_truetype_font_tables( + header: table__h_e_a_d, + postscript: table__p_o_s_t, + os2: table_O_S_2f_2 + ) -> int: + # Get the font flags + if os2: + panose = os2.panose + # sFamilyClass is a two-byte field. The high byte describes the family class, whereas the low + # byte only describes the subclass. We only need the high byte, hence the bit shift below: + family_class = os2.sFamilyClass >> 8 + flags: int = 0 + + # ITALIC + if header.macStyle & HEADER_MACSTYLE_ITALIC or (os2 and os2.fsSelection & OS2_FSSELECTION_ITALIC): + flags |= FontFlags.ITALIC + if postscript: + italic_angle = postscript.italicAngle + if italic_angle != 0.0: + flags |= FontFlags.ITALIC + + # FIXED_PITCH + if ( + (os2 and panose.bProportion == OS2_PANOSE_BPROPORTION_MONOSPACED) or + (postscript and postscript.isFixedPitch > 0) # Actually 1, but originally (older versions of the TTF + ): # specification) any non-zero value signified monospace. + flags |= FontFlags.FIXED_PITCH + + # SCRIPT + if os2 and ( + family_class == OS2_SFAMILYSCLASS_SCRIPTS or panose.bFamilyType == OS2_PANOSE_BFAMILYTYPE_SCRIPT + ): + flags |= FontFlags.SCRIPT + + # SERIF + if os2 and ( + 2 <= panose.bSerifStyle <= 10 + or 1 <= family_class <= 5 or family_class == 7 # 6 is reserved, all 8 and above are not serif + ): + flags |= FontFlags.SERIF + + # SYMBOLIC + if os2 and ( + family_class == OS2_SFAMILYSCLASS_SYMBOLIC or + panose.bFamilyType in {OS2_PANOSE_BFAMILYTYPE_DECORATIVE, OS2_PANOSE_BFAMILYTYPE_PICTORIAL} + ): + flags |= FontFlags.SYMBOLIC + else: + flags |= FontFlags.NONSYMBOLIC + + return flags + + @classmethod + def from_truetype_font_file(cls, font_file: BytesIO) -> Font: + if not HAS_FONTTOOLS: + raise ImportError("The 'fontTools' library is required to use 'from_truetype_font_file'") + with TTFont(font_file) as tt_font_object: + # See Chapter 6 of the TrueType reference manual for the definition of the head, OS/2 and post tables: + # https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6head.html + # https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6OS2.html + # https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6post.html + header = tt_font_object["head"] + horizontal_header = tt_font_object["hhea"] + metrics = tt_font_object["hmtx"].metrics + + # Collect additional font tables to derive font information + postscript = tt_font_object.get("post", None) + os2 = tt_font_object.get("OS/2", None) + + # Get the scaling factor to convert font file's units per em to PDF's 1000 units per em + units_per_em = header.unitsPerEm + scale_factor = 1000.0 / units_per_em + + # Get the font descriptor + font_descriptor_kwargs: dict[Any, Any] = {} + names = tt_font_object.get("name", None) + if names: + font_descriptor_kwargs["name"] = names.getBestFullName() + font_descriptor_kwargs["family"] = names.getBestFamilyName() + font_descriptor_kwargs["weight"] = names.getBestSubFamilyName() + font_descriptor_kwargs["ascent"] = int(round(horizontal_header.ascent * scale_factor, 0)) + font_descriptor_kwargs["descent"] = int(round(horizontal_header.descent * scale_factor, 0)) + if os2: + try: + font_descriptor_kwargs["cap_height"] = int(round(os2.sCapHeight * scale_factor, 0)) + font_descriptor_kwargs["x_height"] = int(round(os2.sxHeight * scale_factor, 0)) + except AttributeError: + pass + + font_descriptor_kwargs["flags"] = cls._font_flags_from_truetype_font_tables(header, postscript, os2) + + font_descriptor_kwargs["bbox"] = ( + round(header.xMin * scale_factor, 0), + round(header.yMin * scale_factor, 0), + round(header.xMax * scale_factor, 0), + round(header.yMax * scale_factor, 0) + ) + + font_file_data = StreamObject() + font_file_raw_bytes = font_file.getvalue() + font_file_data.set_data(font_file_raw_bytes) + font_file_data.update({NameObject("/Length1"): NumberObject(len(font_file_raw_bytes))}) + font_descriptor_kwargs["font_file"] = font_file_data + + font_descriptor = FontDescriptor(**font_descriptor_kwargs) + encoding = "utf_16_be" # Assume unicode + + character_widths: dict[str, int] = {} + character_map: dict[str, str] = {} + + glyph_order = tt_font_object.getGlyphOrder() + # Note that one glyph can be mapped to multiple unicode code points. However, buildReversedMin() + # creates a dictionary mapping glyphs to the minimum Unicode codepoint. + tt_font_cmap_table = tt_font_object.get("cmap") + if tt_font_cmap_table: + reverse_cmap = tt_font_cmap_table.buildReversedMin() + for gid, glyph in enumerate(glyph_order): + char_code = reverse_cmap.get(glyph) + if char_code is None: + continue + char = chr(char_code) + gid = tt_font_object.getGlyphID(glyph) + # The following is to comply with how font_glyph_byte_map works in _appearance_stream.py + gid_bytes = gid.to_bytes(2, "big") + gid_key_string = gid_bytes.decode("utf-16-be", "surrogatepass") + character_map[gid_key_string] = char + character_widths[gid_key_string] = int(round(metrics[glyph][0] * scale_factor, 0)) + else: + raise PdfReadError("Font file does not have a cmap table") + + cls._add_default_width(character_widths, font_descriptor_kwargs["flags"]) + space_width = cls._add_space_width(character_widths, font_descriptor_kwargs["flags"]) + + return cls( + name=font_descriptor.name, + sub_type="TrueType", + encoding=encoding, + font_descriptor=font_descriptor, + character_map=character_map, + character_widths=character_widths, + space_width=space_width, + interpretable=True + ) + + def as_font_resource(self) -> DictionaryObject: + # For now, this returns a font resource that only works with the 14 Adobe Core fonts. + return ( + DictionaryObject({ + NameObject("/Subtype"): NameObject("/Type1"), + NameObject("/Name"): NameObject(f"/{self.name}"), + NameObject("/Type"): NameObject("/Font"), + NameObject("/BaseFont"): NameObject(f"/{self.name}"), + NameObject("/Encoding"): NameObject("/WinAnsiEncoding") + }) + ) + + def text_width(self, text: str = "") -> float: + """Sum of character widths specified in PDF font for the supplied text.""" + return sum( + [self.character_widths.get(char, self.character_widths["default"]) for char in text], 0.0 + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_page.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_page.py new file mode 100644 index 0000000000000000000000000000000000000000..10171cd17bc10de11618b6df01a285cb03effefd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_page.py @@ -0,0 +1,2356 @@ +# Copyright (c) 2006, Mathieu Fenniak +# Copyright (c) 2007, Ashish Kulkarni +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * The name of the author may not be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +import math +from collections.abc import Iterable, Iterator, Sequence +from copy import deepcopy +from dataclasses import asdict, dataclass +from decimal import Decimal +from io import BytesIO +from pathlib import Path +from typing import ( + Any, + Callable, + Literal, + Optional, + Union, + cast, + overload, +) + +from ._font import Font +from ._protocols import PdfCommonDocProtocol +from ._text_extraction import ( + _layout_mode, +) +from ._text_extraction._text_extractor import TextExtraction +from ._utils import ( + CompressedTransformationMatrix, + TransformationMatrixType, + _human_readable_bytes, + deprecate, + logger_warning, + matrix_multiply, +) +from .constants import ( + _INLINE_IMAGE_KEY_MAPPING, + _INLINE_IMAGE_VALUE_MAPPING, + AnnotationDictionaryAttributes, + ImageAttributes, +) +from .constants import PageAttributes as PG +from .constants import Resources as RES +from .errors import PageSizeNotDefinedError, PdfReadError +from .generic import ( + ArrayObject, + ContentStream, + DictionaryObject, + EncodedStreamObject, + FloatObject, + IndirectObject, + NameObject, + NullObject, + NumberObject, + PdfObject, + RectangleObject, + StreamObject, + is_null_or_none, +) + +try: + from PIL.Image import Image + + pil_not_imported = False +except ImportError: + Image = object # type: ignore[assignment,misc,unused-ignore] # TODO: Remove unused-ignore on Python 3.10 + pil_not_imported = True # error will be raised only when using images + +MERGE_CROP_BOX = "cropbox" # pypdf <= 3.4.0 used "trimbox" + + +def _get_rectangle(self: Any, name: str, defaults: Iterable[str]) -> RectangleObject: + retval: Union[None, RectangleObject, ArrayObject, IndirectObject] = self.get(name) + if isinstance(retval, RectangleObject): + return retval + if is_null_or_none(retval): + for d in defaults: + retval = self.get(d) + if retval is not None: + break + if isinstance(retval, IndirectObject): + retval = self.pdf.get_object(retval) + if isinstance(retval, ArrayObject) and (length := len(retval)) > 4: + logger_warning(f"Expected four values, got {length}: {retval}", __name__) + retval = RectangleObject(tuple(retval[:4])) + else: + retval = RectangleObject(retval) # type: ignore + _set_rectangle(self, name, retval) + return retval + + +def _set_rectangle(self: Any, name: str, value: Union[RectangleObject, float]) -> None: + self[NameObject(name)] = value + + +def _delete_rectangle(self: Any, name: str) -> None: + del self[name] + + +def _create_rectangle_accessor(name: str, fallback: Iterable[str]) -> property: + return property( + lambda self: _get_rectangle(self, name, fallback), + lambda self, value: _set_rectangle(self, name, value), + lambda self: _delete_rectangle(self, name), + ) + + +class Transformation: + """ + Represent a 2D transformation. + + The transformation between two coordinate systems is represented by a 3-by-3 + transformation matrix with the following form:: + + a b 0 + c d 0 + e f 1 + + Because a transformation matrix has only six elements that can be changed, + it is usually specified in PDF as the six-element array [ a b c d e f ]. + + Coordinate transformations are expressed as matrix multiplications:: + + a b 0 + [ x′ y′ 1 ] = [ x y 1 ] × c d 0 + e f 1 + + + Example: + >>> from pypdf import PdfWriter, Transformation + >>> page = PdfWriter().add_blank_page(800, 600) + >>> op = Transformation().scale(sx=2, sy=3).translate(tx=10, ty=20) + >>> page.add_transformation(op) + + """ + + def __init__(self, ctm: CompressedTransformationMatrix = (1, 0, 0, 1, 0, 0)) -> None: + self.ctm = ctm + + @property + def matrix(self) -> TransformationMatrixType: + """ + Return the transformation matrix as a tuple of tuples in the form: + + ((a, b, 0), (c, d, 0), (e, f, 1)) + """ + return ( + (self.ctm[0], self.ctm[1], 0), + (self.ctm[2], self.ctm[3], 0), + (self.ctm[4], self.ctm[5], 1), + ) + + @staticmethod + def compress(matrix: TransformationMatrixType) -> CompressedTransformationMatrix: + """ + Compresses the transformation matrix into a tuple of (a, b, c, d, e, f). + + Args: + matrix: The transformation matrix as a tuple of tuples. + + Returns: + A tuple representing the transformation matrix as (a, b, c, d, e, f) + + """ + return ( + matrix[0][0], + matrix[0][1], + matrix[1][0], + matrix[1][1], + matrix[2][0], + matrix[2][1], + ) + + def _to_cm(self) -> str: + # Returns the cm operation string for the given transformation matrix + return ( + f"{self.ctm[0]:.4f} {self.ctm[1]:.4f} {self.ctm[2]:.4f} " + f"{self.ctm[3]:.4f} {self.ctm[4]:.4f} {self.ctm[5]:.4f} cm" + ) + + def transform(self, m: "Transformation") -> "Transformation": + """ + Apply one transformation to another. + + Args: + m: a Transformation to apply. + + Returns: + A new ``Transformation`` instance + + Example: + >>> from pypdf import PdfWriter, Transformation + >>> height, width = 40, 50 + >>> page = PdfWriter().add_blank_page(800, 600) + >>> op = Transformation((1, 0, 0, -1, 0, height)) # vertical mirror + >>> op = Transformation().transform(Transformation((-1, 0, 0, 1, width, 0))) # horizontal mirror + >>> page.add_transformation(op) + + """ + ctm = Transformation.compress(matrix_multiply(self.matrix, m.matrix)) + return Transformation(ctm) + + def translate(self, tx: float = 0, ty: float = 0) -> "Transformation": + """ + Translate the contents of a page. + + Args: + tx: The translation along the x-axis. + ty: The translation along the y-axis. + + Returns: + A new ``Transformation`` instance + + """ + m = self.ctm + return Transformation(ctm=(m[0], m[1], m[2], m[3], m[4] + tx, m[5] + ty)) + + def scale( + self, sx: Optional[float] = None, sy: Optional[float] = None + ) -> "Transformation": + """ + Scale the contents of a page towards the origin of the coordinate system. + + Typically, that is the lower-left corner of the page. That can be + changed by translating the contents / the page boxes. + + Args: + sx: The scale factor along the x-axis. + sy: The scale factor along the y-axis. + + Returns: + A new Transformation instance with the scaled matrix. + + """ + if sx is None and sy is None: + raise ValueError("Either sx or sy must be specified") + if sx is None: + sx = sy + if sy is None: + sy = sx + assert sx is not None + assert sy is not None + op: TransformationMatrixType = ((sx, 0, 0), (0, sy, 0), (0, 0, 1)) + ctm = Transformation.compress(matrix_multiply(self.matrix, op)) + return Transformation(ctm) + + def rotate(self, rotation: float) -> "Transformation": + """ + Rotate the contents of a page. + + Args: + rotation: The angle of rotation in degrees. + + Returns: + A new ``Transformation`` instance with the rotated matrix. + + """ + rotation = math.radians(rotation) + op: TransformationMatrixType = ( + (math.cos(rotation), math.sin(rotation), 0), + (-math.sin(rotation), math.cos(rotation), 0), + (0, 0, 1), + ) + ctm = Transformation.compress(matrix_multiply(self.matrix, op)) + return Transformation(ctm) + + def __repr__(self) -> str: + return f"Transformation(ctm={self.ctm})" + + @overload + def apply_on(self, pt: list[float], as_object: bool = False) -> list[float]: + ... + + @overload + def apply_on( + self, pt: tuple[float, float], as_object: bool = False + ) -> tuple[float, float]: + ... + + def apply_on( + self, + pt: Union[tuple[float, float], list[float]], + as_object: bool = False, + ) -> Union[tuple[float, float], list[float]]: + """ + Apply the transformation matrix on the given point. + + Args: + pt: A tuple or list representing the point in the form (x, y). + as_object: If True, return items as FloatObject, otherwise as plain floats. + + Returns: + A tuple or list representing the transformed point in the form (x', y') + + """ + typ = FloatObject if as_object else float + pt1 = ( + typ(float(pt[0]) * self.ctm[0] + float(pt[1]) * self.ctm[2] + self.ctm[4]), + typ(float(pt[0]) * self.ctm[1] + float(pt[1]) * self.ctm[3] + self.ctm[5]), + ) + return list(pt1) if isinstance(pt, list) else pt1 + + +@dataclass +class ImageFile: + """ + Image within the PDF file. *This object is not designed to be built.* + + This object should not be modified except using :func:`ImageFile.replace` to replace the image with a new one. + """ + + name: str = "" + """ + Filename as identified within the PDF file. + """ + + data: bytes = b"" + """ + Data as bytes. + """ + + image: Optional[Image] = None + """ + Data as PIL image. + """ + + indirect_reference: Optional[IndirectObject] = None + """ + Reference to the object storing the stream. + """ + + def replace(self, new_image: Image, **kwargs: Any) -> None: + """ + Replace the image with a new PIL image. + + Args: + new_image (PIL.Image.Image): The new PIL image to replace the existing image. + **kwargs: Additional keyword arguments to pass to `Image.save()`. + + Raises: + TypeError: If the image is inline or in a PdfReader. + TypeError: If the image does not belong to a PdfWriter. + TypeError: If `new_image` is not a PIL Image. + + Note: + This method replaces the existing image with a new image. + It is not allowed for inline images or images within a PdfReader. + The `kwargs` parameter allows passing additional parameters + to `Image.save()`, such as quality. + + """ + if pil_not_imported: + raise ImportError( + "pillow is required to do image extraction. " + "It can be installed via 'pip install pypdf[image]'" + ) + + from ._reader import PdfReader # noqa: PLC0415 + from .generic import DictionaryObject, PdfObject # noqa: PLC0415 + from .generic._image_xobject import _xobj_to_image # noqa: PLC0415 + + if self.indirect_reference is None: + raise TypeError("Cannot update an inline image.") + if not hasattr(self.indirect_reference.pdf, "_id_translated"): + raise TypeError("Cannot update an image not belonging to a PdfWriter.") + if not isinstance(new_image, Image): + raise TypeError("new_image shall be a PIL Image") + b = BytesIO() + new_image.save(b, "PDF", **kwargs) + reader = PdfReader(b) + page_image = reader.pages[0].images[0] + assert page_image.indirect_reference is not None + self.indirect_reference.pdf._objects[self.indirect_reference.idnum - 1] = ( + page_image.indirect_reference.get_object() + ) + cast( + PdfObject, self.indirect_reference.get_object() + ).indirect_reference = self.indirect_reference + # change the object attributes + extension, byte_stream, img = _xobj_to_image( + cast(DictionaryObject, self.indirect_reference.get_object()), + pillow_parameters=kwargs, + ) + assert extension is not None + self.name = self.name[: self.name.rfind(".")] + extension + self.data = byte_stream + self.image = img + + def __str__(self) -> str: + return f"{self.__class__.__name__}(name={self.name}, data: {_human_readable_bytes(len(self.data))})" + + def __repr__(self) -> str: + return self.__str__()[:-1] + f", hash: {hash(self.data)})" + + +class VirtualListImages(Sequence[ImageFile]): + """ + Provides access to images referenced within a page. + Only one copy will be returned if the usage is used on the same page multiple times. + See :func:`PageObject.images` for more details. + """ + + def __init__( + self, + ids_function: Callable[[], list[Union[str, list[str]]]], + get_function: Callable[[Union[str, list[str], tuple[str]]], ImageFile], + ) -> None: + self.ids_function = ids_function + self.get_function = get_function + self.current = -1 + + def __len__(self) -> int: + return len(self.ids_function()) + + def keys(self) -> list[Union[str, list[str]]]: + return self.ids_function() + + def items(self) -> list[tuple[Union[str, list[str]], ImageFile]]: + return [(x, self[x]) for x in self.ids_function()] + + @overload + def __getitem__(self, index: Union[int, str, list[str]]) -> ImageFile: + ... + + @overload + def __getitem__(self, index: slice) -> Sequence[ImageFile]: + ... + + def __getitem__( + self, index: Union[int, slice, str, list[str], tuple[str]] + ) -> Union[ImageFile, Sequence[ImageFile]]: + lst = self.ids_function() + if isinstance(index, slice): + indices = range(*index.indices(len(self))) + lst = [lst[x] for x in indices] + cls = type(self) + return cls((lambda: lst), self.get_function) + if isinstance(index, (str, list, tuple)): + return self.get_function(index) + if not isinstance(index, int): + raise TypeError("Invalid sequence indices type") + len_self = len(lst) + if index < 0: + # support negative indexes + index += len_self + if not (0 <= index < len_self): + raise IndexError("Sequence index out of range") + return self.get_function(lst[index]) + + def __iter__(self) -> Iterator[ImageFile]: + for i in range(len(self)): + yield self[i] + + def __str__(self) -> str: + p = [f"Image_{i}={n}" for i, n in enumerate(self.ids_function())] + return f"[{', '.join(p)}]" + + +class PageObject(DictionaryObject): + """ + PageObject represents a single page within a PDF file. + + Typically these objects will be created by accessing the + :attr:`pages` property of the + :class:`PdfReader` class, but it is + also possible to create an empty page with the + :meth:`create_blank_page()` static method. + + Args: + pdf: PDF file the page belongs to. + indirect_reference: Stores the original indirect reference to + this object in its source PDF + + """ + + original_page: "PageObject" # very local use in writer when appending + + def __init__( + self, + pdf: Optional[PdfCommonDocProtocol] = None, + indirect_reference: Optional[IndirectObject] = None, + ) -> None: + DictionaryObject.__init__(self) + self.pdf = pdf + self.inline_images: Optional[dict[str, ImageFile]] = None + self.indirect_reference = indirect_reference + if not is_null_or_none(indirect_reference): + assert indirect_reference is not None, "mypy" + self.update(cast(DictionaryObject, indirect_reference.get_object())) + self._font_width_maps: dict[str, tuple[dict[str, float], str, float]] = {} + + def hash_bin(self) -> int: + """ + Used to detect modified object. + + Note: this function is overloaded to return the same results + as a DictionaryObject. + + Returns: + Hash considering type and value. + + """ + return hash( + (DictionaryObject, tuple(((k, v.hash_bin()) for k, v in self.items()))) + ) + + def hash_value_data(self) -> bytes: + data = super().hash_value_data() + data += f"{id(self)}".encode() + return data + + @property + def user_unit(self) -> float: + """ + A read-only positive number giving the size of user space units. + + It is in multiples of 1/72 inch. Hence a value of 1 means a user + space unit is 1/72 inch, and a value of 3 means that a user + space unit is 3/72 inch. + """ + return cast(float, self.get(PG.USER_UNIT, 1)) + + @staticmethod + def create_blank_page( + pdf: Optional[PdfCommonDocProtocol] = None, + width: Union[float, Decimal, None] = None, + height: Union[float, Decimal, None] = None, + ) -> "PageObject": + """ + Return a new blank page. + + If ``width`` or ``height`` is ``None``, try to get the page size + from the last page of *pdf*. + + Args: + pdf: PDF file the page is within. + width: The width of the new page expressed in default user + space units. + height: The height of the new page expressed in default user + space units. + + Returns: + The new blank page + + Raises: + PageSizeNotDefinedError: if ``pdf`` is ``None`` or contains + no page + + """ + page = PageObject(pdf) + + # Creates a new page (cf PDF Reference §7.7.3.3) + page.__setitem__(NameObject(PG.TYPE), NameObject("/Page")) + page.__setitem__(NameObject(PG.PARENT), NullObject()) + page.__setitem__(NameObject(PG.RESOURCES), DictionaryObject()) + if width is None or height is None: + if pdf is not None and len(pdf.pages) > 0: + lastpage = pdf.pages[len(pdf.pages) - 1] + width = lastpage.mediabox.width + height = lastpage.mediabox.height + else: + raise PageSizeNotDefinedError + page.__setitem__( + NameObject(PG.MEDIABOX), RectangleObject((0, 0, width, height)) # type: ignore + ) + + return page + + def _get_ids_image( + self, + obj: Optional[DictionaryObject] = None, + ancest: Optional[list[str]] = None, + call_stack: Optional[list[Any]] = None, + ) -> list[Union[str, list[str]]]: + if call_stack is None: + call_stack = [] + _i = getattr(obj, "indirect_reference", None) + if _i in call_stack: + return [] + call_stack.append(_i) + if self.inline_images is None: + self.inline_images = self._get_inline_images() + if obj is None: + obj = self + if ancest is None: + ancest = [] + lst: list[Union[str, list[str]]] = [] + if ( + PG.RESOURCES not in obj or + is_null_or_none(resources := obj[PG.RESOURCES]) or + RES.XOBJECT not in cast(DictionaryObject, resources) + ): + return [] if self.inline_images is None else list(self.inline_images.keys()) + + x_object = resources[RES.XOBJECT].get_object() # type: ignore + for o in x_object: + if not isinstance(x_object[o], StreamObject): + continue + if x_object[o][ImageAttributes.SUBTYPE] == "/Image": + lst.append(o if len(ancest) == 0 else [*ancest, o]) + else: # is a form with possible images inside + lst.extend(self._get_ids_image(x_object[o], [*ancest, o], call_stack)) + assert self.inline_images is not None + lst.extend(list(self.inline_images.keys())) + return lst + + def _get_image( + self, + id: Union[str, list[str], tuple[str]], + obj: Optional[DictionaryObject] = None, + ) -> ImageFile: + if obj is None: + obj = cast(DictionaryObject, self) + if isinstance(id, tuple): + id = list(id) + if isinstance(id, list) and len(id) == 1: + id = id[0] + xobjs: Optional[DictionaryObject] = None + try: + xobjs = cast( + DictionaryObject, cast(DictionaryObject, obj[PG.RESOURCES])[RES.XOBJECT] + ) + except KeyError as exc: + if not (id[0] == "~" and id[-1] == "~"): + raise KeyError( + f"Cannot access image object {id} without XObject resources" + ) from exc + if isinstance(id, str): + if id[0] == "~" and id[-1] == "~": + if self.inline_images is None: + self.inline_images = self._get_inline_images() + if self.inline_images is None: + raise KeyError("No inline image can be found") + return self.inline_images[id] + + assert xobjs is not None + from .generic._image_xobject import _xobj_to_image # noqa: PLC0415 + imgd = _xobj_to_image(cast(DictionaryObject, xobjs[id])) + extension, byte_stream = imgd[:2] + return ImageFile( + name=f"{id[1:]}{extension}", + data=byte_stream, + image=imgd[2], + indirect_reference=xobjs[id].indirect_reference, + ) + # in a subobject + assert xobjs is not None + ids = id[1:] + return self._get_image(ids, cast(DictionaryObject, xobjs[id[0]])) + + @property + def images(self) -> VirtualListImages: + """ + Read-only property emulating a list of images on a page. + + Get a list of all images on the page. The key can be: + - A string (for the top object) + - A tuple (for images within XObject forms) + - An integer + + Examples: + * `reader.pages[0].images[0]` # return first image + * `reader.pages[0].images['/I0']` # return image '/I0' + * `reader.pages[0].images['/TP1','/Image1']` # return image '/Image1' within '/TP1' XObject form + * `for img in reader.pages[0].images:` # loops through all objects + + images.keys() and images.items() can be used. + + The ImageFile has the following properties: + + * `.name` : name of the object + * `.data` : bytes of the object + * `.image` : PIL Image Object + * `.indirect_reference` : object reference + + and the following methods: + `.replace(new_image: PIL.Image.Image, **kwargs)` : + replace the image in the pdf with the new image + applying the saving parameters indicated (such as quality) + + Example usage: + + reader.pages[0].images[0].replace(Image.open("new_image.jpg"), quality=20) + + Inline images are extracted and named ~0~, ~1~, ..., with the + indirect_reference set to None. + + """ + return VirtualListImages(self._get_ids_image, self._get_image) + + def _translate_value_inline_image(self, k: str, v: PdfObject) -> PdfObject: + """Translate values used in inline image""" + try: + v = NameObject(_INLINE_IMAGE_VALUE_MAPPING[cast(str, v)]) + except (TypeError, KeyError): + if isinstance(v, NameObject): + # It is a custom name, thus we have to look in resources. + # The only applicable case is for ColorSpace. + try: + res = cast(DictionaryObject, self["/Resources"])["/ColorSpace"] + v = cast(DictionaryObject, res)[v] + except KeyError: # for res and v + raise PdfReadError(f"Cannot find resource entry {v} for {k}") + return v + + def _get_inline_images(self) -> dict[str, ImageFile]: + """Load inline images. Entries will be identified as `~1~`.""" + content = self.get_contents() + if is_null_or_none(content): + return {} + imgs_data = [] + assert content is not None, "mypy" + for param, ope in content.operations: + if ope == b"INLINE IMAGE": + imgs_data.append( + {"settings": param["settings"], "__streamdata__": param["data"]} + ) + elif ope in (b"BI", b"EI", b"ID"): # pragma: no cover + raise PdfReadError( + f"{ope!r} operator met whereas not expected, " + "please share use case with pypdf dev team" + ) + files = {} + for num, ii in enumerate(imgs_data): + init = { + "__streamdata__": ii["__streamdata__"], + "/Length": len(ii["__streamdata__"]), + } + for k, v in ii["settings"].items(): + if k in {"/Length", "/L"}: # no length is expected + continue + if isinstance(v, list): + v = ArrayObject( + [self._translate_value_inline_image(k, x) for x in v] + ) + else: + v = self._translate_value_inline_image(k, v) + k = NameObject(_INLINE_IMAGE_KEY_MAPPING[k]) + if k not in init: + init[k] = v + ii["object"] = EncodedStreamObject.initialize_from_dictionary(init) + from .generic._image_xobject import _xobj_to_image # noqa: PLC0415 + extension, byte_stream, img = _xobj_to_image(ii["object"]) + files[f"~{num}~"] = ImageFile( + name=f"~{num}~{extension}", + data=byte_stream, + image=img, + indirect_reference=None, + ) + return files + + @property + def rotation(self) -> int: + """ + The visual rotation of the page. + + This number has to be a multiple of 90 degrees: 0, 90, 180, or 270 are + valid values. This property does not affect ``/Contents``. + """ + rotate_obj = self.get(PG.ROTATE, 0) + return rotate_obj if isinstance(rotate_obj, int) else rotate_obj.get_object() + + @rotation.setter + def rotation(self, r: float) -> None: + self[NameObject(PG.ROTATE)] = NumberObject((((int(r) + 45) // 90) * 90) % 360) + + def transfer_rotation_to_content(self) -> None: + """ + Apply the rotation of the page to the content and the media/crop/... + boxes. + + It is recommended to apply this function before page merging. + """ + r = -self.rotation # rotation to apply is in the otherway + self.rotation = 0 + mb = RectangleObject(self.mediabox) + trsf = ( + Transformation() + .translate( + -float(mb.left + mb.width / 2), -float(mb.bottom + mb.height / 2) + ) + .rotate(r) + ) + pt1 = trsf.apply_on(mb.lower_left) + pt2 = trsf.apply_on(mb.upper_right) + trsf = trsf.translate(-min(pt1[0], pt2[0]), -min(pt1[1], pt2[1])) + self.add_transformation(trsf, False) + for b in ["/MediaBox", "/CropBox", "/BleedBox", "/TrimBox", "/ArtBox"]: + if b in self: + rr = RectangleObject(self[b]) # type: ignore + pt1 = trsf.apply_on(rr.lower_left) + pt2 = trsf.apply_on(rr.upper_right) + self[NameObject(b)] = RectangleObject( + ( + min(pt1[0], pt2[0]), + min(pt1[1], pt2[1]), + max(pt1[0], pt2[0]), + max(pt1[1], pt2[1]), + ) + ) + + def rotate(self, angle: int) -> "PageObject": + """ + Rotate a page clockwise by increments of 90 degrees. + + Args: + angle: Angle to rotate the page. Must be an increment of 90 deg. + + Returns: + The rotated PageObject + + """ + if angle % 90 != 0: + raise ValueError("Rotation angle must be a multiple of 90") + self[NameObject(PG.ROTATE)] = NumberObject(self.rotation + angle) + return self + + def _merge_resources( + self, + res1: DictionaryObject, + res2: DictionaryObject, + resource: Any, + new_res1: bool = True, + ) -> tuple[dict[str, Any], dict[str, Any]]: + try: + assert isinstance(self.indirect_reference, IndirectObject) + pdf = self.indirect_reference.pdf + is_pdf_writer = hasattr( + pdf, "_add_object" + ) # expect isinstance(pdf, PdfWriter) + except (AssertionError, AttributeError): + pdf = None + is_pdf_writer = False + + def compute_unique_key(base_key: str) -> tuple[str, bool]: + """ + Find a key that either doesn't already exist or has the same value + (indicated by the bool) + + Args: + base_key: An index is added to this to get the computed key + + Returns: + A tuple (computed key, bool) where the boolean indicates + if there is a resource of the given computed_key with the same + value. + + """ + value = page2res.raw_get(base_key) + # TODO: a possible improvement for writer, the indirect_reference + # cannot be found because translated + + # try the current key first (e.g. "foo"), but otherwise iterate + # through "foo-0", "foo-1", etc. new_res can contain only finitely + # many keys, thus this'll eventually end, even if it's been crafted + # to be maximally annoying. + computed_key = base_key + idx = 0 + while computed_key in new_res: + if new_res.raw_get(computed_key) == value: + # there's already a resource of this name, with the exact + # same value + return computed_key, True + computed_key = f"{base_key}-{idx}" + idx += 1 + return computed_key, False + + if new_res1: + new_res = DictionaryObject() + new_res.update(res1.get(resource, DictionaryObject()).get_object()) + else: + new_res = cast(DictionaryObject, res1[resource]) + page2res = cast( + DictionaryObject, res2.get(resource, DictionaryObject()).get_object() + ) + rename_res = {} + for key in page2res: + unique_key, same_value = compute_unique_key(key) + newname = NameObject(unique_key) + if key != unique_key: + # we have to use a different name for this + rename_res[key] = newname + + if not same_value: + if is_pdf_writer: + new_res[newname] = page2res.raw_get(key).clone(pdf) + try: + new_res[newname] = new_res[newname].indirect_reference + except AttributeError: + pass + else: + new_res[newname] = page2res.raw_get(key) + lst = sorted(new_res.items()) + new_res.clear() + for el in lst: + new_res[el[0]] = el[1] + return new_res, rename_res + + @staticmethod + def _content_stream_rename( + stream: ContentStream, + rename: dict[Any, Any], + pdf: Optional[PdfCommonDocProtocol], + ) -> ContentStream: + if not rename: + return stream + stream = ContentStream(stream, pdf) + for operands, _operator in stream.operations: + if isinstance(operands, list): + for i, op in enumerate(operands): + if isinstance(op, NameObject): + operands[i] = rename.get(op, op) + elif isinstance(operands, dict): + for i, op in operands.items(): + if isinstance(op, NameObject): + operands[i] = rename.get(op, op) + else: + raise KeyError(f"Type of operands is {type(operands)}") + return stream + + @staticmethod + def _add_transformation_matrix( + contents: Any, + pdf: Optional[PdfCommonDocProtocol], + ctm: CompressedTransformationMatrix, + ) -> ContentStream: + """Add transformation matrix at the beginning of the given contents stream.""" + content_stream = ContentStream(contents, pdf) + content_stream.operations.insert( + 0, + ( + [FloatObject(x) for x in ctm], + b"cm", + ), + ) + return content_stream + + def _get_contents_as_bytes(self) -> Optional[bytes]: + """ + Return the page contents as bytes. + + Returns: + The ``/Contents`` object as bytes, or ``None`` if it doesn't exist. + + """ + if PG.CONTENTS in self: + obj = self[PG.CONTENTS].get_object() + if isinstance(obj, list): + return b"".join(x.get_object().get_data() for x in obj) + return cast(EncodedStreamObject, obj).get_data() + return None + + def get_contents(self) -> Optional[ContentStream]: + """ + Access the page contents. + + Returns: + The ``/Contents`` object, or ``None`` if it does not exist. + ``/Contents`` is optional, as described in §7.7.3.3 of the PDF Reference. + + """ + if PG.CONTENTS in self: + try: + pdf = cast(IndirectObject, self.indirect_reference).pdf + except AttributeError: + pdf = None + obj = self[PG.CONTENTS] + if is_null_or_none(obj): + return None + resolved_object = obj.get_object() + return ContentStream(resolved_object, pdf) + return None + + def replace_contents( + self, content: Union[None, ContentStream, EncodedStreamObject, ArrayObject] + ) -> None: + """ + Replace the page contents with the new content and nullify old objects + Args: + content: new content; if None delete the content field. + """ + if not hasattr(self, "indirect_reference") or self.indirect_reference is None: + # the page is not attached : the content is directly attached. + self[NameObject(PG.CONTENTS)] = content + return + + from pypdf._writer import PdfWriter # noqa: PLC0415 + if not isinstance(self.indirect_reference.pdf, PdfWriter): + deprecate( + "Calling `PageObject.replace_contents()` for pages not assigned to a writer is deprecated " + "and will be removed in pypdf 7.0.0. Attach the page to the writer first or use " + "`PdfWriter(clone_from=...)` directly. The existing approach has proved being unreliable." + ) + + writer = self.indirect_reference.pdf + if isinstance(self.get(PG.CONTENTS, None), ArrayObject): + content_array = cast(ArrayObject, self[PG.CONTENTS]) + for reference in content_array: + try: + writer._replace_object(indirect_reference=reference.indirect_reference, obj=NullObject()) + except ValueError: + # Occurs when called on PdfReader. + pass + + if isinstance(content, ArrayObject): + content = ArrayObject(writer._add_object(obj) for obj in content) + + if is_null_or_none(content): + if PG.CONTENTS not in self: + return + assert self[PG.CONTENTS].indirect_reference is not None + writer._replace_object(indirect_reference=self[PG.CONTENTS].indirect_reference, obj=NullObject()) + del self[PG.CONTENTS] + elif not hasattr(self.get(PG.CONTENTS, None), "indirect_reference"): + try: + self[NameObject(PG.CONTENTS)] = writer._add_object(content) + except AttributeError: + # applies at least for page not in writer + # as a backup solution, we put content as an object although not in accordance with pdf ref + # this will be fixed with the _add_object + self[NameObject(PG.CONTENTS)] = content + else: + assert content is not None, "mypy" + content.indirect_reference = self[ + PG.CONTENTS + ].indirect_reference # TODO: in the future may require generation management + try: + writer._replace_object(indirect_reference=content.indirect_reference, obj=content) + except AttributeError: + # applies at least for page not in writer + # as a backup solution, we put content as an object although not in accordance with pdf ref + # this will be fixed with the _add_object + self[NameObject(PG.CONTENTS)] = content + # forces recalculation of inline_images + self.inline_images = None + + def merge_page( + self, page2: "PageObject", expand: bool = False, over: bool = True + ) -> None: + """ + Merge the content streams of two pages into one. + + Resource references (e.g. fonts) are maintained from both pages. + The mediabox, cropbox, etc of this page are not altered. + The parameter page's content stream will + be added to the end of this page's content stream, + meaning that it will be drawn after, or "on top" of this page. + + Args: + page2: The page to be merged into this one. Should be + an instance of :class:`PageObject`. + over: set the page2 content over page1 if True (default) else under + expand: If True, the current page dimensions will be + expanded to accommodate the dimensions of the page to be merged. + + """ + self._merge_page(page2, over=over, expand=expand) + + def _merge_page( + self, + page2: "PageObject", + page2_transformation: Optional[Callable[[Any], ContentStream]] = None, + ctm: Optional[CompressedTransformationMatrix] = None, + over: bool = True, + expand: bool = False, + ) -> None: + # First we work on merging the resource dictionaries. This allows us + # to find out what symbols in the content streams we might need to + # rename. + try: + assert isinstance(self.indirect_reference, IndirectObject) + if hasattr(self.indirect_reference.pdf, "_add_object"): # to detect PdfWriter + return self._merge_page_writer( + page2, page2_transformation, ctm, over, expand + ) + except (AssertionError, AttributeError): + pass + + new_resources = DictionaryObject() + rename: dict[str, Any] = {} + original_resources = cast(DictionaryObject, self.get(PG.RESOURCES, DictionaryObject()).get_object()) + page2_resources = cast(DictionaryObject, page2.get(PG.RESOURCES, DictionaryObject()).get_object()) + new_annots = ArrayObject() + + for page in (self, page2): + if PG.ANNOTS in page: + annots = page[PG.ANNOTS] + if isinstance(annots, ArrayObject): + new_annots.extend(annots) + self[NameObject(PG.ANNOTS)] = new_annots + + for res in ( + RES.EXT_G_STATE, + RES.COLOR_SPACE, + RES.PATTERN, + RES.SHADING, + RES.XOBJECT, + RES.FONT, + RES.PROPERTIES, + ): + new, new_resource_name = self._merge_resources( + original_resources, page2_resources, res + ) + if new: + new_resources[NameObject(res)] = new + rename.update(new_resource_name) + + # Combine /ProcSet sets, making sure there is a consistent order + new_resources[NameObject(RES.PROC_SET)] = ArrayObject( + sorted( + set( + original_resources.get(RES.PROC_SET, ArrayObject()).get_object() + ).union( + set(page2_resources.get(RES.PROC_SET, ArrayObject()).get_object()) + ) + ) + ) + + new_content_array = ArrayObject() + original_content = self.get_contents() + if original_content is not None: + original_content.isolate_graphics_state() + new_content_array.append(original_content) + + page2_content = page2.get_contents() + if page2_content is not None: + rect = getattr(page2, MERGE_CROP_BOX) + page2_content.operations.insert( + 0, + ( + map( + FloatObject, + [ + rect.left, + rect.bottom, + rect.width, + rect.height, + ], + ), + b"re", + ), + ) + page2_content.operations.insert(1, ([], b"W")) + page2_content.operations.insert(2, ([], b"n")) + if page2_transformation is not None: + page2_content = page2_transformation(page2_content) + page2_content = PageObject._content_stream_rename( + page2_content, rename, self.pdf + ) + page2_content.isolate_graphics_state() + if over: + new_content_array.append(page2_content) + else: + new_content_array.insert(0, page2_content) + + # if expanding the page to fit a new page, calculate the new media box size + if expand: + self._expand_mediabox(page2, ctm) + + self.replace_contents(ContentStream(new_content_array, self.pdf)) + self[NameObject(PG.RESOURCES)] = new_resources + + return None + + def _merge_page_writer( + self, + page2: "PageObject", + page2transformation: Optional[Callable[[Any], ContentStream]] = None, + ctm: Optional[CompressedTransformationMatrix] = None, + over: bool = True, + expand: bool = False, + ) -> None: + # First we work on merging the resource dictionaries. This allows us + # to find which symbols in the content streams we might need to + # rename. + assert isinstance(self.indirect_reference, IndirectObject) + pdf = self.indirect_reference.pdf + + if PG.RESOURCES not in self: + self[NameObject(PG.RESOURCES)] = DictionaryObject() + original_resources = cast(DictionaryObject, self[PG.RESOURCES].get_object()) + if PG.RESOURCES not in page2: + page2resources = DictionaryObject() + else: + page2resources = cast(DictionaryObject, page2[PG.RESOURCES].get_object()) + + rename = {} + for res in ( + RES.EXT_G_STATE, + RES.COLOR_SPACE, + RES.PATTERN, + RES.SHADING, + RES.XOBJECT, + RES.FONT, + RES.PROPERTIES, + ): + if res in page2resources: + if res not in original_resources: + original_resources[NameObject(res)] = DictionaryObject() + _, newrename = self._merge_resources( + original_resources, page2resources, res, False + ) + rename.update(newrename) + # Combine /ProcSet sets + if RES.PROC_SET in page2resources: + if RES.PROC_SET not in original_resources: + original_resources[NameObject(RES.PROC_SET)] = ArrayObject() + arr = cast(ArrayObject, original_resources[RES.PROC_SET]) + for x in cast(ArrayObject, page2resources[RES.PROC_SET]): + if x not in arr: + arr.append(x) + arr.sort() + + if not is_null_or_none(page2.get(PG.ANNOTS, None)): + if PG.ANNOTS not in self: + self[NameObject(PG.ANNOTS)] = ArrayObject() + annots = cast(ArrayObject, self[PG.ANNOTS].get_object()) + if ctm is None: + trsf = Transformation() + else: + trsf = Transformation(ctm) + # Ensure we are working on a copy of the list. Otherwise, if both pages + # are the same object, we might run into an infinite loop. + for a in cast(ArrayObject, deepcopy(page2[PG.ANNOTS])): + a = a.get_object() + aa = a.clone( + pdf, + ignore_fields=("/P", "/StructParent", "/Parent"), + force_duplicate=True, + ) + r = cast(ArrayObject, a["/Rect"]) + pt1 = trsf.apply_on((r[0], r[1]), True) + pt2 = trsf.apply_on((r[2], r[3]), True) + aa[NameObject("/Rect")] = ArrayObject( + ( + min(pt1[0], pt2[0]), + min(pt1[1], pt2[1]), + max(pt1[0], pt2[0]), + max(pt1[1], pt2[1]), + ) + ) + if "/QuadPoints" in a: + q = cast(ArrayObject, a["/QuadPoints"]) + aa[NameObject("/QuadPoints")] = ArrayObject( + trsf.apply_on((q[0], q[1]), True) + + trsf.apply_on((q[2], q[3]), True) + + trsf.apply_on((q[4], q[5]), True) + + trsf.apply_on((q[6], q[7]), True) + ) + try: + aa["/Popup"][NameObject("/Parent")] = aa.indirect_reference + except KeyError: + pass + try: + aa[NameObject("/P")] = self.indirect_reference + annots.append(aa.indirect_reference) + except AttributeError: + pass + + new_content_array = ArrayObject() + original_content = self.get_contents() + if original_content is not None: + original_content.isolate_graphics_state() + new_content_array.append(original_content) + + page2content = page2.get_contents() + if page2content is not None: + rect = getattr(page2, MERGE_CROP_BOX) + page2content.operations.insert( + 0, + ( + map( + FloatObject, + [ + rect.left, + rect.bottom, + rect.width, + rect.height, + ], + ), + b"re", + ), + ) + page2content.operations.insert(1, ([], b"W")) + page2content.operations.insert(2, ([], b"n")) + if page2transformation is not None: + page2content = page2transformation(page2content) + page2content = PageObject._content_stream_rename( + page2content, rename, self.pdf + ) + page2content.isolate_graphics_state() + if over: + new_content_array.append(page2content) + else: + new_content_array.insert(0, page2content) + + # if expanding the page to fit a new page, calculate the new media box size + if expand: + self._expand_mediabox(page2, ctm) + + self.replace_contents(new_content_array) + + def _expand_mediabox( + self, page2: "PageObject", ctm: Optional[CompressedTransformationMatrix] + ) -> None: + corners1 = ( + self.mediabox.left.as_numeric(), + self.mediabox.bottom.as_numeric(), + self.mediabox.right.as_numeric(), + self.mediabox.top.as_numeric(), + ) + corners2 = ( + page2.mediabox.left.as_numeric(), + page2.mediabox.bottom.as_numeric(), + page2.mediabox.left.as_numeric(), + page2.mediabox.top.as_numeric(), + page2.mediabox.right.as_numeric(), + page2.mediabox.top.as_numeric(), + page2.mediabox.right.as_numeric(), + page2.mediabox.bottom.as_numeric(), + ) + if ctm is not None: + ctm = tuple(float(x) for x in ctm) # type: ignore[assignment] + new_x = tuple( + ctm[0] * corners2[i] + ctm[2] * corners2[i + 1] + ctm[4] + for i in range(0, 8, 2) + ) + new_y = tuple( + ctm[1] * corners2[i] + ctm[3] * corners2[i + 1] + ctm[5] + for i in range(0, 8, 2) + ) + else: + new_x = corners2[0:8:2] + new_y = corners2[1:8:2] + lowerleft = (min(new_x), min(new_y)) + upperright = (max(new_x), max(new_y)) + lowerleft = (min(corners1[0], lowerleft[0]), min(corners1[1], lowerleft[1])) + upperright = ( + max(corners1[2], upperright[0]), + max(corners1[3], upperright[1]), + ) + + self.mediabox.lower_left = lowerleft + self.mediabox.upper_right = upperright + + def merge_transformed_page( + self, + page2: "PageObject", + ctm: Union[CompressedTransformationMatrix, Transformation], + over: bool = True, + expand: bool = False, + ) -> None: + """ + Similar to :meth:`~pypdf._page.PageObject.merge_page`, but a transformation + matrix is applied to the merged stream. + + Args: + page2: The page to be merged into this one. + ctm: a 6-element tuple containing the operands of the + transformation matrix + over: set the page2 content over page1 if True (default) else under + expand: Whether the page should be expanded to fit the dimensions + of the page to be merged. + + """ + if isinstance(ctm, Transformation): + ctm = ctm.ctm + self._merge_page( + page2, + lambda page2_content: PageObject._add_transformation_matrix( + page2_content, page2.pdf, ctm + ), + ctm, + over, + expand, + ) + + def merge_scaled_page( + self, page2: "PageObject", scale: float, over: bool = True, expand: bool = False + ) -> None: + """ + Similar to :meth:`~pypdf._page.PageObject.merge_page`, but the stream to be merged + is scaled by applying a transformation matrix. + + Args: + page2: The page to be merged into this one. + scale: The scaling factor + over: set the page2 content over page1 if True (default) else under + expand: Whether the page should be expanded to fit the + dimensions of the page to be merged. + + """ + op = Transformation().scale(scale, scale) + self.merge_transformed_page(page2, op, over, expand) + + def merge_rotated_page( + self, + page2: "PageObject", + rotation: float, + over: bool = True, + expand: bool = False, + ) -> None: + """ + Similar to :meth:`~pypdf._page.PageObject.merge_page`, but the stream to be merged + is rotated by applying a transformation matrix. + + Args: + page2: The page to be merged into this one. + rotation: The angle of the rotation, in degrees + over: set the page2 content over page1 if True (default) else under + expand: Whether the page should be expanded to fit the + dimensions of the page to be merged. + + """ + op = Transformation().rotate(rotation) + self.merge_transformed_page(page2, op, over, expand) + + def merge_translated_page( + self, + page2: "PageObject", + tx: float, + ty: float, + over: bool = True, + expand: bool = False, + ) -> None: + """ + Similar to :meth:`~pypdf._page.PageObject.merge_page`, but the stream to be + merged is translated by applying a transformation matrix. + + Args: + page2: the page to be merged into this one. + tx: The translation on X axis + ty: The translation on Y axis + over: set the page2 content over page1 if True (default) else under + expand: Whether the page should be expanded to fit the + dimensions of the page to be merged. + + """ + op = Transformation().translate(tx, ty) + self.merge_transformed_page(page2, op, over, expand) + + def add_transformation( + self, + ctm: Union[Transformation, CompressedTransformationMatrix], + expand: bool = False, + ) -> None: + """ + Apply a transformation matrix to the page. + + Args: + ctm: A 6-element tuple containing the operands of the + transformation matrix. Alternatively, a + :py:class:`Transformation` + object can be passed. + + See :doc:`/user/cropping-and-transforming`. + + """ + if isinstance(ctm, Transformation): + ctm = ctm.ctm + content = self.get_contents() + if content is not None: + content = PageObject._add_transformation_matrix(content, self.pdf, ctm) + content.isolate_graphics_state() + self.replace_contents(content) + # if expanding the page to fit a new page, calculate the new media box size + if expand: + corners = [ + self.mediabox.left.as_numeric(), + self.mediabox.bottom.as_numeric(), + self.mediabox.left.as_numeric(), + self.mediabox.top.as_numeric(), + self.mediabox.right.as_numeric(), + self.mediabox.top.as_numeric(), + self.mediabox.right.as_numeric(), + self.mediabox.bottom.as_numeric(), + ] + + ctm = tuple(float(x) for x in ctm) # type: ignore[assignment] + new_x = [ + ctm[0] * corners[i] + ctm[2] * corners[i + 1] + ctm[4] + for i in range(0, 8, 2) + ] + new_y = [ + ctm[1] * corners[i] + ctm[3] * corners[i + 1] + ctm[5] + for i in range(0, 8, 2) + ] + + self.mediabox.lower_left = (min(new_x), min(new_y)) + self.mediabox.upper_right = (max(new_x), max(new_y)) + + def scale(self, sx: float, sy: float) -> None: + """ + Scale a page by the given factors by applying a transformation matrix + to its content and updating the page size. + + This updates the various page boundaries (bleedbox, trimbox, etc.) + and the contents of the page. + + Args: + sx: The scaling factor on horizontal axis. + sy: The scaling factor on vertical axis. + + """ + self.add_transformation((sx, 0, 0, sy, 0, 0)) + self.bleedbox = self.bleedbox.scale(sx, sy) + self.trimbox = self.trimbox.scale(sx, sy) + self.artbox = self.artbox.scale(sx, sy) + self.cropbox = self.cropbox.scale(sx, sy) + self.mediabox = self.mediabox.scale(sx, sy) + + if PG.ANNOTS in self: + annotations = self[PG.ANNOTS] + if isinstance(annotations, ArrayObject): + for annotation in annotations: + annotation_obj = annotation.get_object() + if AnnotationDictionaryAttributes.Rect in annotation_obj: + rectangle = annotation_obj[AnnotationDictionaryAttributes.Rect] + if isinstance(rectangle, ArrayObject): + rectangle[0] = FloatObject(float(rectangle[0]) * sx) + rectangle[1] = FloatObject(float(rectangle[1]) * sy) + rectangle[2] = FloatObject(float(rectangle[2]) * sx) + rectangle[3] = FloatObject(float(rectangle[3]) * sy) + + if PG.VP in self: + viewport = self[PG.VP] + if isinstance(viewport, ArrayObject): + bbox = viewport[0]["/BBox"] + else: + bbox = viewport["/BBox"] # type: ignore + scaled_bbox = RectangleObject( + ( + float(bbox[0]) * sx, + float(bbox[1]) * sy, + float(bbox[2]) * sx, + float(bbox[3]) * sy, + ) + ) + if isinstance(viewport, ArrayObject): + self[NameObject(PG.VP)][NumberObject(0)][ # type: ignore + NameObject("/BBox") + ] = scaled_bbox + else: + self[NameObject(PG.VP)][NameObject("/BBox")] = scaled_bbox # type: ignore + + def scale_by(self, factor: float) -> None: + """ + Scale a page by the given factor by applying a transformation matrix to + its content and updating the page size. + + Args: + factor: The scaling factor (for both X and Y axis). + + """ + self.scale(factor, factor) + + def scale_to(self, width: float, height: float) -> None: + """ + Scale a page to the specified dimensions by applying a transformation + matrix to its content and updating the page size. + + Args: + width: The new width. + height: The new height. + + """ + sx = width / float(self.mediabox.width) + sy = height / float(self.mediabox.height) + self.scale(sx, sy) + + def compress_content_streams(self, level: int = -1) -> None: + """ + Compress the size of this page by joining all content streams and + applying a FlateDecode filter. + + However, it is possible that this function will perform no action if + content stream compression becomes "automatic". + """ + content = self.get_contents() + if content is not None: + content_obj = content.flate_encode(level) + try: + content.indirect_reference.pdf._objects[ # type: ignore + content.indirect_reference.idnum - 1 # type: ignore + ] = content_obj + except AttributeError: + if self.indirect_reference is not None and hasattr( + self.indirect_reference.pdf, "_add_object" + ): + self.replace_contents(content_obj) + else: + raise ValueError("Page must be part of a PdfWriter") + + @property + def page_number(self) -> Optional[int]: + """ + Read-only property which returns the page number within the PDF file. + + Returns: + Page number; None if the page is not attached to a PDF. + + """ + if self.indirect_reference is None: + return None + try: + lst = self.indirect_reference.pdf.pages + return int(lst.index(self)) + except ValueError: + return None + + def _debug_for_extract(self) -> str: # pragma: no cover + out = "" + for ope, op in ContentStream( + self["/Contents"].get_object(), self.pdf, "bytes" + ).operations: + if op == b"TJ": + s = [x for x in ope[0] if isinstance(x, str)] + else: + s = [] + out += op.decode("utf-8") + " " + "".join(s) + ope.__repr__() + "\n" + out += "\n=============================\n" + try: + for fo in self[PG.RESOURCES]["/Font"]: # type:ignore + out += fo + "\n" + out += self[PG.RESOURCES]["/Font"][fo].__repr__() + "\n" # type:ignore + try: + enc_repr = self[PG.RESOURCES]["/Font"][fo][ # type:ignore + "/Encoding" + ].__repr__() + out += enc_repr + "\n" + except Exception: + pass + try: + out += ( + self[PG.RESOURCES]["/Font"][fo][ # type:ignore + "/ToUnicode" + ] + .get_data() + .decode() + + "\n" + ) + except Exception: + pass + + except KeyError: + out += "No Font\n" + return out + + def _extract_text( + self, + obj: Any, + pdf: Any, + orientations: tuple[int, ...] = (0, 90, 180, 270), + space_width: float = 200.0, + content_key: Optional[str] = PG.CONTENTS, + visitor_operand_before: Optional[Callable[[Any, Any, Any, Any], None]] = None, + visitor_operand_after: Optional[Callable[[Any, Any, Any, Any], None]] = None, + visitor_text: Optional[Callable[[Any, Any, Any, Any, Any], None]] = None, + ) -> str: + """ + See extract_text for most arguments. + + Args: + content_key: indicate the default key where to extract data + None = the object; this allows reusing the function on an XObject + default = "/Content" + + """ + extractor = TextExtraction() + font_resources: dict[str, DictionaryObject] = {} + fonts: dict[str, Font] = {} + + try: + objr = obj + while NameObject(PG.RESOURCES) not in objr: + # /Resources can be inherited so we look to parents + objr = objr["/Parent"].get_object() + # If no parents then no /Resources will be available, + # so an exception will be raised + resources_dict = cast(DictionaryObject, objr[PG.RESOURCES]) + except Exception: + # No resources means no text is possible (no font); we consider the + # file as not damaged, no need to check for TJ or Tj + return "" + + if ( + not is_null_or_none(resources_dict) + and "/Font" in resources_dict + and (font_resources_dict := cast(DictionaryObject, resources_dict["/Font"])) + ): + for font_resource in font_resources_dict: + try: + font_resource_object = cast(DictionaryObject, font_resources_dict[font_resource].get_object()) + font_resources[font_resource] = font_resource_object + fonts[font_resource] = Font.from_font_resource(font_resource_object) + # Override space width, if applicable + if fonts[font_resource].character_widths.get(" ", 0) == 0: + fonts[font_resource].space_width = space_width + except (AttributeError, TypeError): + pass + + try: + content = ( + obj[content_key].get_object() if isinstance(content_key, str) else obj + ) + if not isinstance(content, ContentStream): + content = ContentStream(content, pdf, "bytes") + except (AttributeError, KeyError): # no content can be extracted (certainly empty page) + return "" + # We check all strings are TextStringObjects. ByteStringObjects + # are strings where the byte->string encoding was unknown, so adding + # them to the text here would be gibberish. + + # Initialize the extractor with the necessary parameters + extractor.initialize_extraction(orientations, visitor_text, font_resources, fonts) + + for operands, operator in content.operations: + if visitor_operand_before is not None: + visitor_operand_before(operator, operands, extractor.cm_matrix, extractor.tm_matrix) + # Multiple operators are handled here + if operator == b"'": + extractor.process_operation(b"T*", []) + extractor.process_operation(b"Tj", operands) + elif operator == b'"': + extractor.process_operation(b"Tw", [operands[0]]) + extractor.process_operation(b"Tc", [operands[1]]) + extractor.process_operation(b"T*", []) + extractor.process_operation(b"Tj", operands[2:]) + elif operator == b"TJ": + # The space width may be smaller than the font width, so the width should be 95%. + _confirm_space_width = extractor._space_width * 0.95 + if operands: + for op in operands[0]: + if isinstance(op, (str, bytes)): + extractor.process_operation(b"Tj", [op]) + if isinstance(op, (int, float, NumberObject, FloatObject)) and ( + abs(float(op)) >= _confirm_space_width + and extractor.text + and extractor.text[-1] != " " + ): + extractor.process_operation(b"Tj", [" "]) + elif operator == b"TD": + extractor.process_operation(b"TL", [-operands[1]]) + extractor.process_operation(b"Td", operands) + elif operator == b"Do": + extractor.output += extractor.text + if visitor_text is not None: + visitor_text( + extractor.text, + extractor.memo_cm, + extractor.memo_tm, + extractor.font_resource, + extractor.font_size, + ) + try: + if extractor.output[-1] != "\n": + extractor.output += "\n" + if visitor_text is not None: + visitor_text( + "\n", + extractor.memo_cm, + extractor.memo_tm, + extractor.font_resource, + extractor.font_size, + ) + except IndexError: + pass + try: + xobj = resources_dict["/XObject"] + if xobj[operands[0]]["/Subtype"] != "/Image": # type: ignore + text = self.extract_xform_text( + xobj[operands[0]], # type: ignore + orientations, + space_width, + visitor_operand_before, + visitor_operand_after, + visitor_text, + ) + extractor.output += text + if visitor_text is not None: + visitor_text( + text, + extractor.memo_cm, + extractor.memo_tm, + extractor.font_resource, + extractor.font_size, + ) + except Exception as exception: + logger_warning( + f"Impossible to decode XFormObject {operands[0]}: {exception}", + __name__, + ) + finally: + extractor.text = "" + extractor.memo_cm = extractor.cm_matrix.copy() + extractor.memo_tm = extractor.tm_matrix.copy() + else: + extractor.process_operation(operator, operands) + if visitor_operand_after is not None: + visitor_operand_after(operator, operands, extractor.cm_matrix, extractor.tm_matrix) + extractor.output += extractor.text # just in case + if extractor.text != "" and visitor_text is not None: + visitor_text( + extractor.text, + extractor.memo_cm, + extractor.memo_tm, + extractor.font_resource, + extractor.font_size, + ) + return extractor.output + + def _layout_mode_fonts(self) -> dict[str, Font]: + """ + Get fonts formatted for "layout" mode text extraction. + + Returns: + Dict[str, Font]: dictionary of Font instances keyed by font name + + """ + # Font retrieval logic adapted from pypdf.PageObject._extract_text() + objr: Any = self + fonts: dict[str, Font] = {} + while objr is not None: + try: + resources_dict: Any = objr[PG.RESOURCES] + except KeyError: + resources_dict = {} + if "/Font" in resources_dict and self.pdf is not None: + for font_name in resources_dict["/Font"]: + fonts[font_name] = Font.from_font_resource(resources_dict["/Font"][font_name]) + try: + objr = objr["/Parent"].get_object() + except KeyError: + objr = None + + return fonts + + def _layout_mode_text( + self, + space_vertically: bool = True, + scale_weight: float = 1.25, + strip_rotated: bool = True, + debug_path: Optional[Path] = None, + font_height_weight: float = 1, + ) -> str: + """ + Get text preserving fidelity to source PDF text layout. + + Args: + space_vertically: include blank lines inferred from y distance + font + height. Defaults to True. + scale_weight: multiplier for string length when calculating weighted + average character width. Defaults to 1.25. + strip_rotated: Removes text that is rotated w.r.t. to the page from + layout mode output. Defaults to True. + debug_path (Path | None): if supplied, must target a directory. + creates the following files with debug information for layout mode + functions if supplied: + - fonts.json: output of self._layout_mode_fonts + - tjs.json: individual text render ops with corresponding transform matrices + - bts.json: text render ops left justified and grouped by BT/ET operators + - bt_groups.json: BT/ET operations grouped by rendered y-coord (aka lines) + Defaults to None. + font_height_weight: multiplier for font height when calculating + blank lines. Defaults to 1. + + Returns: + str: multiline string containing page text in a fixed width format that + closely adheres to the rendered layout in the source pdf. + + """ + fonts = self._layout_mode_fonts() + if debug_path: # pragma: no cover + import json # noqa: PLC0415 + + debug_path.joinpath("fonts.json").write_text( + json.dumps(fonts, indent=2, default=asdict), + "utf-8" + ) + + ops = iter( + ContentStream(self["/Contents"].get_object(), self.pdf, "bytes").operations + ) + bt_groups = _layout_mode.text_show_operations( + ops, fonts, strip_rotated, debug_path + ) + + if not bt_groups: + return "" + + ty_groups = _layout_mode.y_coordinate_groups(bt_groups, debug_path) + + char_width = _layout_mode.fixed_char_width(bt_groups, scale_weight) + + return _layout_mode.fixed_width_page(ty_groups, char_width, space_vertically, font_height_weight) + + def extract_text( + self, + *args: Any, + orientations: Union[int, tuple[int, ...]] = (0, 90, 180, 270), + space_width: float = 200.0, + visitor_operand_before: Optional[Callable[[Any, Any, Any, Any], None]] = None, + visitor_operand_after: Optional[Callable[[Any, Any, Any, Any], None]] = None, + visitor_text: Optional[Callable[[Any, Any, Any, Any, Any], None]] = None, + extraction_mode: Literal["plain", "layout"] = "plain", + **kwargs: Any, + ) -> str: + """ + Locate all text drawing commands, in the order they are provided in the + content stream, and extract the text. + + This works well for some PDF files, but poorly for others, depending on + the generator used. This will be refined in the future. + + Do not rely on the order of text coming out of this function, as it + will change if this function is made more sophisticated. + + Arabic and Hebrew are extracted in the correct order. + If required a custom RTL range of characters can be defined; + see function set_custom_rtl. + + Additionally you can provide visitor methods to get informed on all + operations and all text objects. + For example in some PDF files this can be useful to parse tables. + + Args: + orientations: list of orientations extract_text will look for + default = (0, 90, 180, 270) + note: currently only 0 (up),90 (turned left), 180 (upside down), + 270 (turned right) + Silently ignored in "layout" mode. + space_width: force default space width + if not extracted from font (default: 200) + Silently ignored in "layout" mode. + visitor_operand_before: function to be called before processing an operation. + It has four arguments: operator, operand-arguments, + current transformation matrix and text matrix. + Ignored with a warning in "layout" mode. + visitor_operand_after: function to be called after processing an operation. + It has four arguments: operator, operand-arguments, + current transformation matrix and text matrix. + Ignored with a warning in "layout" mode. + visitor_text: function to be called when extracting some text at some position. + It has five arguments: text, current transformation matrix, + text matrix, font-dictionary and font-size. + The font-dictionary may be None in case of unknown fonts. + If not None it may e.g. contain key "/BaseFont" with value "/Arial,Bold". + Ignored with a warning in "layout" mode. + extraction_mode (Literal["plain", "layout"]): "plain" for legacy functionality, + "layout" for experimental layout mode functionality. + NOTE: orientations, space_width, and visitor_* parameters are NOT respected + in "layout" mode. + + kwargs: + layout_mode_space_vertically (bool): include blank lines inferred from + y distance + font height. Defaults to True. + layout_mode_scale_weight (float): multiplier for string length when calculating + weighted average character width. Defaults to 1.25. + layout_mode_strip_rotated (bool): layout mode does not support rotated text. + Set to False to include rotated text anyway. If rotated text is discovered, + layout will be degraded and a warning will result. Defaults to True. + layout_mode_debug_path (Path | None): if supplied, must target a directory. + creates the following files with debug information for layout mode + functions if supplied: + + - fonts.json: output of self._layout_mode_fonts + - tjs.json: individual text render ops with corresponding transform matrices + - bts.json: text render ops left justified and grouped by BT/ET operators + - bt_groups.json: BT/ET operations grouped by rendered y-coord (aka lines) + layout_mode_font_height_weight (float): multiplier for font height when calculating + blank lines. Defaults to 1. + + Returns: + The extracted text + + """ + if extraction_mode not in ["plain", "layout"]: + raise ValueError(f"Invalid text extraction mode '{extraction_mode}'") + if extraction_mode == "layout": + for visitor in ( + "visitor_operand_before", + "visitor_operand_after", + "visitor_text", + ): + if locals()[visitor]: + logger_warning( + f"Argument {visitor} is ignored in layout mode", + __name__, + ) + return self._layout_mode_text( + space_vertically=kwargs.get("layout_mode_space_vertically", True), + scale_weight=kwargs.get("layout_mode_scale_weight", 1.25), + strip_rotated=kwargs.get("layout_mode_strip_rotated", True), + debug_path=kwargs.get("layout_mode_debug_path"), + font_height_weight=kwargs.get("layout_mode_font_height_weight", 1) + ) + if len(args) >= 1: + if isinstance(args[0], str): + if len(args) >= 3: + if isinstance(args[2], (tuple, int)): + orientations = args[2] + else: + raise TypeError(f"Invalid positional parameter {args[2]}") + if len(args) >= 4: + if isinstance(args[3], (float, int)): + space_width = args[3] + else: + raise TypeError(f"Invalid positional parameter {args[3]}") + elif isinstance(args[0], (tuple, int)): + orientations = args[0] + if len(args) >= 2: + if isinstance(args[1], (float, int)): + space_width = args[1] + else: + raise TypeError(f"Invalid positional parameter {args[1]}") + else: + raise TypeError(f"Invalid positional parameter {args[0]}") + + if isinstance(orientations, int): + orientations = (orientations,) + + return self._extract_text( + self, + self.pdf, + orientations, + space_width, + PG.CONTENTS, + visitor_operand_before, + visitor_operand_after, + visitor_text, + ) + + def extract_xform_text( + self, + xform: EncodedStreamObject, + orientations: tuple[int, ...] = (0, 90, 270, 360), + space_width: float = 200.0, + visitor_operand_before: Optional[Callable[[Any, Any, Any, Any], None]] = None, + visitor_operand_after: Optional[Callable[[Any, Any, Any, Any], None]] = None, + visitor_text: Optional[Callable[[Any, Any, Any, Any, Any], None]] = None, + ) -> str: + """ + Extract text from an XObject. + + Args: + xform: + orientations: + space_width: force default space width (if not extracted from font (default 200) + visitor_operand_before: + visitor_operand_after: + visitor_text: + + Returns: + The extracted text + + """ + return self._extract_text( + xform, + self.pdf, + orientations, + space_width, + None, + visitor_operand_before, + visitor_operand_after, + visitor_text, + ) + + def _get_fonts(self) -> tuple[set[str], set[str]]: + """ + Get the names of embedded fonts and unembedded fonts. + + Returns: + A tuple (set of embedded fonts, set of unembedded fonts) + + """ + obj = self.get_object() + assert isinstance(obj, DictionaryObject) + fonts: set[str] = set() + embedded: set[str] = set() + fonts, embedded = _get_fonts_walk(obj, fonts, embedded) + unembedded = fonts - embedded + return embedded, unembedded + + mediabox = _create_rectangle_accessor(PG.MEDIABOX, ()) + """A :class:`RectangleObject`, expressed in + default user space units, defining the boundaries of the physical medium on + which the page is intended to be displayed or printed.""" + + cropbox = _create_rectangle_accessor("/CropBox", (PG.MEDIABOX,)) + """ + A :class:`RectangleObject`, expressed in + default user space units, defining the visible region of default user + space. + + When the page is displayed or printed, its contents are to be clipped + (cropped) to this rectangle and then imposed on the output medium in some + implementation-defined manner. Default value: same as + :attr:`mediabox`. + """ + + bleedbox = _create_rectangle_accessor("/BleedBox", ("/CropBox", PG.MEDIABOX)) + """A :class:`RectangleObject`, expressed in + default user space units, defining the region to which the contents of the + page should be clipped when output in a production environment.""" + + trimbox = _create_rectangle_accessor("/TrimBox", ("/CropBox", PG.MEDIABOX)) + """A :class:`RectangleObject`, expressed in + default user space units, defining the intended dimensions of the finished + page after trimming.""" + + artbox = _create_rectangle_accessor("/ArtBox", ("/CropBox", PG.MEDIABOX)) + """A :class:`RectangleObject`, expressed in + default user space units, defining the extent of the page's meaningful + content as intended by the page's creator.""" + + @property + def annotations(self) -> Optional[ArrayObject]: + if "/Annots" not in self: + return None + return cast(ArrayObject, self["/Annots"]) + + @annotations.setter + def annotations(self, value: Optional[ArrayObject]) -> None: + """ + Set the annotations array of the page. + + Typically you do not want to set this value, but append to it. + If you append to it, remember to add the object first to the writer + and only add the indirect object. + """ + if value is None: + if "/Annots" not in self: + return + del self[NameObject("/Annots")] + else: + self[NameObject("/Annots")] = value + + +class _VirtualList(Sequence[PageObject]): + def __init__( + self, + length_function: Callable[[], int], + get_function: Callable[[int], PageObject], + ) -> None: + self.length_function = length_function + self.get_function = get_function + self.current = -1 + + def __len__(self) -> int: + return self.length_function() + + @overload + def __getitem__(self, index: int) -> PageObject: + ... + + @overload + def __getitem__(self, index: slice) -> Sequence[PageObject]: + ... + + def __getitem__( + self, index: Union[int, slice] + ) -> Union[PageObject, Sequence[PageObject]]: + if isinstance(index, slice): + indices = range(*index.indices(len(self))) + cls = type(self) + return cls(indices.__len__, lambda idx: self[indices[idx]]) + if not isinstance(index, int): + raise TypeError("Sequence indices must be integers") + len_self = len(self) + if index < 0: + # support negative indexes + index += len_self + if not (0 <= index < len_self): + raise IndexError("Sequence index out of range") + return self.get_function(index) + + def __delitem__(self, index: Union[int, slice]) -> None: + if isinstance(index, slice): + r = list(range(*index.indices(len(self)))) + # pages have to be deleted from last to first + r.sort() + r.reverse() + for p in r: + del self[p] # recursive call + return + if not isinstance(index, int): + raise TypeError("Index must be integers") + len_self = len(self) + if index < 0: + # support negative indexes + index += len_self + if not (0 <= index < len_self): + raise IndexError("Index out of range") + ind = self[index].indirect_reference + assert ind is not None + parent: Optional[PdfObject] = cast(DictionaryObject, ind.get_object()).get( + "/Parent", None + ) + first = True + while parent is not None: + parent = cast(DictionaryObject, parent.get_object()) + try: + i = cast(ArrayObject, parent["/Kids"]).index(ind) + del cast(ArrayObject, parent["/Kids"])[i] + first = False + try: + assert ind is not None + del ind.pdf.flattened_pages[index] # case of page in a Reader + except Exception: # pragma: no cover + pass + if "/Count" in parent: + parent[NameObject("/Count")] = NumberObject( + cast(int, parent["/Count"]) - 1 + ) + if len(cast(ArrayObject, parent["/Kids"])) == 0: + # No more objects in this part of this subtree + ind = parent.indirect_reference + parent = parent.get("/Parent", None) + except ValueError: # from index + if first: + raise PdfReadError(f"Page not found in page tree: {ind}") + break + + def __iter__(self) -> Iterator[PageObject]: + for i in range(len(self)): + yield self[i] + + def __str__(self) -> str: + p = [f"PageObject({i})" for i in range(self.length_function())] + return f"[{', '.join(p)}]" + + +def _get_fonts_walk( + obj: DictionaryObject, + fnt: set[str], + emb: set[str], +) -> tuple[set[str], set[str]]: + """ + Get the set of all fonts and all embedded fonts. + + Args: + obj: Page resources dictionary + fnt: font + emb: embedded fonts + + Returns: + A tuple (fnt, emb) + + If there is a key called 'BaseFont', that is a font that is used in the document. + If there is a key called 'FontName' and another key in the same dictionary object + that is called 'FontFilex' (where x is null, 2, or 3), then that fontname is + embedded. + + We create and add to two sets, fnt = fonts used and emb = fonts embedded. + + """ + fontkeys = ("/FontFile", "/FontFile2", "/FontFile3") + + def process_font(f: DictionaryObject) -> None: + nonlocal fnt, emb + f = cast(DictionaryObject, f.get_object()) # to be sure + if "/BaseFont" in f: + fnt.add(cast(str, f["/BaseFont"])) + + if ( + ("/CharProcs" in f) + or ( + "/FontDescriptor" in f + and any( + x in cast(DictionaryObject, f["/FontDescriptor"]) for x in fontkeys + ) + ) + or ( + "/DescendantFonts" in f + and "/FontDescriptor" + in cast( + DictionaryObject, + cast(ArrayObject, f["/DescendantFonts"])[0].get_object(), + ) + and any( + x + in cast( + DictionaryObject, + cast( + DictionaryObject, + cast(ArrayObject, f["/DescendantFonts"])[0].get_object(), + )["/FontDescriptor"], + ) + for x in fontkeys + ) + ) + ): + # the list comprehension ensures there is FontFile + try: + emb.add(cast(str, f["/BaseFont"])) + except KeyError: + emb.add("(" + cast(str, f["/Subtype"]) + ")") + + if "/DR" in obj and "/Font" in cast(DictionaryObject, obj["/DR"]): + for f in cast(DictionaryObject, cast(DictionaryObject, obj["/DR"])["/Font"]): + process_font(f) + if "/Resources" in obj: + if "/Font" in cast(DictionaryObject, obj["/Resources"]): + for f in cast( + DictionaryObject, cast(DictionaryObject, obj["/Resources"])["/Font"] + ).values(): + process_font(f) + if "/XObject" in cast(DictionaryObject, obj["/Resources"]): + for x in cast( + DictionaryObject, cast(DictionaryObject, obj["/Resources"])["/XObject"] + ).values(): + _get_fonts_walk(cast(DictionaryObject, x.get_object()), fnt, emb) + if "/Annots" in obj: + for a in cast(ArrayObject, obj["/Annots"]): + _get_fonts_walk(cast(DictionaryObject, a.get_object()), fnt, emb) + if "/AP" in obj: + if ( + cast(DictionaryObject, cast(DictionaryObject, obj["/AP"])["/N"]).get( + "/Type" + ) + == "/XObject" + ): + _get_fonts_walk( + cast(DictionaryObject, cast(DictionaryObject, obj["/AP"])["/N"]), + fnt, + emb, + ) + else: + for a in cast(DictionaryObject, cast(DictionaryObject, obj["/AP"])["/N"]): + _get_fonts_walk(cast(DictionaryObject, a), fnt, emb) + return fnt, emb # return the sets for each page diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_page_labels.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_page_labels.py new file mode 100644 index 0000000000000000000000000000000000000000..d47313f42d614a8e7ca2b7a2dc3604fc3b4a8beb --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_page_labels.py @@ -0,0 +1,290 @@ +""" +Page labels are shown by PDF viewers as "the page number". + +A page has a numeric index, starting at 0. Additionally, the page +has a label. In the most simple case: + + label = index + 1 + +However, the title page and the table of contents might have Roman numerals as +page labels. This makes things more complicated. + +Example 1 +--------- + +>>> reader.root_object["/PageLabels"]["/Nums"] +[0, IndirectObject(18, 0, 139929798197504), + 8, IndirectObject(19, 0, 139929798197504)] +>>> reader.get_object(reader.root_object["/PageLabels"]["/Nums"][1]) +{'/S': '/r'} +>>> reader.get_object(reader.root_object["/PageLabels"]["/Nums"][3]) +{'/S': '/D'} + +Example 2 +--------- +The following is a document with pages labeled +i, ii, iii, iv, 1, 2, 3, A-8, A-9, ... + +1 0 obj + << /Type /Catalog + /PageLabels << /Nums [ + 0 << /S /r >> + 4 << /S /D >> + 7 << /S /D + /P ( A- ) + /St 8 + >> + % A number tree containing + % three page label dictionaries + ] + >> + ... + >> +endobj + + +§12.4.2 PDF Specification 1.7 and 2.0 +===================================== + +Entries in a page label dictionary +---------------------------------- +The /S key: +D Decimal Arabic numerals +R Uppercase Roman numerals +r Lowercase Roman numerals +A Uppercase letters (A to Z for the first 26 pages, + AA to ZZ for the next 26, and so on) +a Lowercase letters (a to z for the first 26 pages, + aa to zz for the next 26, and so on) +""" + +from collections.abc import Callable, Iterator +from typing import Optional, cast + +from ._protocols import PdfCommonDocProtocol +from ._utils import logger_warning +from .generic import ( + ArrayObject, + DictionaryObject, + NullObject, + NumberObject, + is_null_or_none, +) + + +def number2uppercase_roman_numeral(num: int) -> str: + roman = [ + (1000, "M"), + (900, "CM"), + (500, "D"), + (400, "CD"), + (100, "C"), + (90, "XC"), + (50, "L"), + (40, "XL"), + (10, "X"), + (9, "IX"), + (5, "V"), + (4, "IV"), + (1, "I"), + ] + + def roman_num(num: int) -> Iterator[str]: + for decimal, roman_repr in roman: + x, _ = divmod(num, decimal) + yield roman_repr * x + num -= decimal * x + if num <= 0: + break + + return "".join(list(roman_num(num))) + + +def number2lowercase_roman_numeral(number: int) -> str: + return number2uppercase_roman_numeral(number).lower() + + +def number2uppercase_letter(number: int) -> str: + if number <= 0: + raise ValueError("Expecting a positive number") + alphabet = [chr(i) for i in range(ord("A"), ord("Z") + 1)] + rep = "" + while number > 0: + remainder = number % 26 + if remainder == 0: + remainder = 26 + rep = alphabet[remainder - 1] + rep + # update + number -= remainder + number = number // 26 + return rep + + +def number2lowercase_letter(number: int) -> str: + return number2uppercase_letter(number).lower() + + +def get_label_from_nums(dictionary_object: DictionaryObject, index: int) -> str: + # [Nums] shall be an array of the form + # [ key_1 value_1 key_2 value_2 ... key_n value_n ] + # where each key_i is an integer and the corresponding + # value_i shall be the object associated with that key. + # The keys shall be sorted in numerical order, + # analogously to the arrangement of keys in a name tree + # as described in 7.9.6, "Name Trees." + nums = cast(ArrayObject, dictionary_object["/Nums"]) + i = 0 + value = None + start_index = 0 + while i < len(nums): + start_index = nums[i] + value = nums[i + 1].get_object() + if i + 2 == len(nums): + break + if nums[i + 2] > index: + break + i += 2 + m: dict[Optional[str], Callable[[int], str]] = { + None: lambda _: "", + "/D": str, + "/R": number2uppercase_roman_numeral, + "/r": number2lowercase_roman_numeral, + "/A": number2uppercase_letter, + "/a": number2lowercase_letter, + } + # if /Nums array is not following the specification or if /Nums is empty + if not isinstance(value, dict): + return str(index + 1) # Fallback + start = value.get("/St", 1) + prefix = cast(str, value.get("/P", "")) + mapping_function = m[value.get("/S")] + return prefix + mapping_function(index - start_index + start) + + +def index2label(reader: PdfCommonDocProtocol, index: int) -> str: + """ + See 7.9.7 "Number Trees". + + Args: + reader: The PdfReader + index: The index of the page + + Returns: + The label of the page, e.g. "iv" or "4". + + """ + root = cast(DictionaryObject, reader.root_object) + if "/PageLabels" not in root: + return str(index + 1) # Fallback + number_tree = cast(DictionaryObject, root["/PageLabels"].get_object()) + if "/Nums" in number_tree: + return get_label_from_nums(number_tree, index) + if "/Kids" in number_tree and not isinstance(number_tree["/Kids"], NullObject): + # number_tree = {'/Kids': [IndirectObject(7333, 0, 140132998195856), ...]} + # Limit maximum depth. + level = 0 + while level < 100: + kids = cast(list[DictionaryObject], number_tree["/Kids"]) + for kid in kids: + # kid = {'/Limits': [0, 63], '/Nums': [0, {'/P': 'C1'}, ...]} + limits = cast(list[int], kid["/Limits"]) + if limits[0] <= index <= limits[1]: + if not is_null_or_none(kid.get("/Kids", None)): + # Recursive definition. + level += 1 + if level == 100: # pragma: no cover + raise NotImplementedError( + "Too deep nesting is not supported." + ) + number_tree = kid + # Exit the inner `for` loop and continue at the next level with the + # next iteration of the `while` loop. + break + return get_label_from_nums(kid, index) + else: + # When there are no kids, make sure to exit the `while` loop directly + # and continue with the fallback. + break + + logger_warning(f"Could not reliably determine page label for {index}.", __name__) + return str(index + 1) # Fallback if neither /Nums nor /Kids is in the number_tree + + +def nums_insert( + key: NumberObject, + value: DictionaryObject, + nums: ArrayObject, +) -> None: + """ + Insert a key, value pair in a Nums array. + + See 7.9.7 "Number Trees". + + Args: + key: number key of the entry + value: value of the entry + nums: Nums array to modify + + """ + if len(nums) % 2 != 0: + raise ValueError("A nums like array must have an even number of elements") + + i = len(nums) + while i != 0 and key <= nums[i - 2]: + i = i - 2 + + if i < len(nums) and key == nums[i]: + nums[i + 1] = value + else: + nums.insert(i, key) + nums.insert(i + 1, value) + + +def nums_clear_range( + key: NumberObject, + page_index_to: int, + nums: ArrayObject, +) -> None: + """ + Remove all entries in a number tree in a range after an entry. + + See 7.9.7 "Number Trees". + + Args: + key: number key of the entry before the range + page_index_to: The page index of the upper limit of the range + nums: Nums array to modify + + """ + if len(nums) % 2 != 0: + raise ValueError("A nums like array must have an even number of elements") + if page_index_to < key: + raise ValueError("page_index_to must be greater or equal than key") + + i = nums.index(key) + 2 + while i < len(nums) and nums[i] <= page_index_to: + nums.pop(i) + nums.pop(i) + + +def nums_next( + key: NumberObject, + nums: ArrayObject, +) -> tuple[Optional[NumberObject], Optional[DictionaryObject]]: + """ + Return the (key, value) pair of the entry after the given one. + + See 7.9.7 "Number Trees". + + Args: + key: number key of the entry + nums: Nums array + + """ + if len(nums) % 2 != 0: + raise ValueError("A nums like array must have an even number of elements") + + i = nums.index(key) + 2 + if i < len(nums): + return (nums[i], nums[i + 1]) + return (None, None) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_protocols.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_protocols.py new file mode 100644 index 0000000000000000000000000000000000000000..ac24abbbe200c4ffd201d04d73196eb7a8c419bf --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_protocols.py @@ -0,0 +1,86 @@ +"""Helpers for working with PDF types.""" + +from abc import abstractmethod +from pathlib import Path +from typing import IO, Any, Optional, Protocol, Union + +from ._utils import StrByteType, StreamType + + +class PdfObjectProtocol(Protocol): + indirect_reference: Any + + def clone( + self, + pdf_dest: Any, + force_duplicate: bool = False, + ignore_fields: Union[tuple[str, ...], list[str], None] = (), + ) -> Any: + ... # pragma: no cover + + def _reference_clone(self, clone: Any, pdf_dest: Any) -> Any: + ... # pragma: no cover + + def get_object(self) -> Optional["PdfObjectProtocol"]: + ... # pragma: no cover + + def hash_value(self) -> bytes: + ... # pragma: no cover + + def write_to_stream( + self, stream: StreamType, encryption_key: Union[None, str, bytes] = None + ) -> None: + ... # pragma: no cover + + +class XmpInformationProtocol(PdfObjectProtocol): + pass + + +class PdfCommonDocProtocol(Protocol): + @property + def pdf_header(self) -> str: + ... # pragma: no cover + + @property + def pages(self) -> list[Any]: + ... # pragma: no cover + + @property + def root_object(self) -> PdfObjectProtocol: + ... # pragma: no cover + + def get_object(self, indirect_reference: Any) -> Optional[PdfObjectProtocol]: + ... # pragma: no cover + + @property + def strict(self) -> bool: + ... # pragma: no cover + + +class PdfReaderProtocol(PdfCommonDocProtocol, Protocol): + @property + @abstractmethod + def xref(self) -> dict[int, dict[int, Any]]: + ... # pragma: no cover + + @property + @abstractmethod + def trailer(self) -> dict[str, Any]: + ... # pragma: no cover + + +class PdfWriterProtocol(PdfCommonDocProtocol, Protocol): + _objects: list[Any] + _id_translated: dict[int, dict[int, int]] + + incremental: bool + _reader: Any # PdfReader + + @abstractmethod + def write(self, stream: Union[Path, StrByteType]) -> tuple[bool, IO[Any]]: + ... # pragma: no cover + + @abstractmethod + def _add_object(self, obj: Any) -> Any: + ... # pragma: no cover diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_reader.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_reader.py new file mode 100644 index 0000000000000000000000000000000000000000..db9279f40554b27bb428d372f845b096139451c1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_reader.py @@ -0,0 +1,1464 @@ +# Copyright (c) 2006, Mathieu Fenniak +# Copyright (c) 2007, Ashish Kulkarni +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * The name of the author may not be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +import os +import re +import sys +from collections.abc import Iterable +from io import BytesIO, UnsupportedOperation +from pathlib import Path +from types import TracebackType +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Optional, + Union, + cast, +) + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + +from ._doc_common import PdfDocCommon, convert_to_int +from ._encryption import Encryption, PasswordType +from ._utils import ( + WHITESPACES_AS_BYTES, + StrByteType, + StreamType, + logger_warning, + read_non_whitespace, + read_previous_line, + read_until_whitespace, + skip_over_comment, + skip_over_whitespace, +) +from .constants import TrailerKeys as TK +from .errors import ( + EmptyFileError, + FileNotDecryptedError, + LimitReachedError, + PdfReadError, + PdfStreamError, + WrongPasswordError, +) +from .generic import ( + ArrayObject, + ContentStream, + DecodedStreamObject, + DictionaryObject, + EncodedStreamObject, + IndirectObject, + NameObject, + NullObject, + NumberObject, + PdfObject, + StreamObject, + TextStringObject, + is_null_or_none, + read_object, +) +from .xmp import XmpInformation + +if TYPE_CHECKING: + from ._page import PageObject + + +class PdfReader(PdfDocCommon): + """ + Initialize a PdfReader object. + + This operation can take some time, as the PDF stream's cross-reference + tables are read into memory. + + Args: + stream: A File object or an object that supports the standard read + and seek methods similar to a File object. Could also be a + string representing a path to a PDF file. + strict: Determines whether user should be warned of all + problems and also causes some correctable problems to be fatal. + Defaults to ``False``. + password: Decrypt PDF file at initialization. If the + password is None, the file will not be decrypted. + Defaults to ``None``. + root_object_recovery_limit: The maximum number of objects to query + for recovering the Root object in non-strict mode. To disable + this security measure, pass ``None``. + + """ + + def __init__( + self, + stream: Union[StrByteType, Path], + strict: bool = False, + password: Union[None, str, bytes] = None, + *, + root_object_recovery_limit: Optional[int] = 10_000, + ) -> None: + self.strict = strict + self.flattened_pages: Optional[list[PageObject]] = None + + #: Storage of parsed PDF objects. + self.resolved_objects: dict[tuple[Any, Any], Optional[PdfObject]] = {} + + self._startxref: int = 0 + self.xref_index = 0 + self.xref: dict[int, dict[Any, Any]] = {} + self.xref_free_entry: dict[int, dict[Any, Any]] = {} + self.xref_objStm: dict[int, tuple[Any, Any]] = {} + self.trailer = DictionaryObject() + + # Security parameters. + self._root_object_recovery_limit = ( + root_object_recovery_limit if isinstance(root_object_recovery_limit, int) else sys.maxsize + ) + + # Map page indirect_reference number to page number + self._page_id2num: Optional[dict[Any, Any]] = None + + self._validated_root: Optional[DictionaryObject] = None + + self._initialize_stream(stream) + self._known_objects: set[tuple[int, int]] = set() + + self._override_encryption = False + self._encryption: Optional[Encryption] = None + if self.is_encrypted: + self._handle_encryption(password) + elif password is not None: + raise PdfReadError("Not an encrypted file") + + def _initialize_stream(self, stream: Union[StrByteType, Path]) -> None: + if hasattr(stream, "mode") and "b" not in stream.mode: + logger_warning( + "PdfReader stream/file object is not in binary mode. " + "It may not be read correctly.", + __name__, + ) + self._stream_opened = False + if isinstance(stream, (str, Path)): + with open(stream, "rb") as fh: + stream = BytesIO(fh.read()) + self._stream_opened = True + self.read(stream) + self.stream = stream + + def _handle_encryption(self, password: Optional[Union[str, bytes]]) -> None: + self._override_encryption = True + # Some documents may not have a /ID, use two empty + # byte strings instead. Solves + # https://github.com/py-pdf/pypdf/issues/608 + id_entry = self.trailer.get(TK.ID) + id1_entry = id_entry[0].get_object().original_bytes if id_entry else b"" + encrypt_entry = cast(DictionaryObject, self.trailer[TK.ENCRYPT].get_object()) + self._encryption = Encryption.read(encrypt_entry, id1_entry) + + # try empty password if no password provided + pwd = password if password is not None else b"" + if ( + self._encryption.verify(pwd) == PasswordType.NOT_DECRYPTED + and password is not None + ): + # raise if password provided + raise WrongPasswordError("Wrong password") + self._override_encryption = False + + def __enter__(self) -> Self: + return self + + def __exit__( + self, + exc_type: Optional[type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: + self.close() + + def close(self) -> None: + """Close the stream if opened in __init__ and clear memory.""" + if self._stream_opened: + self.stream.close() + self.flattened_pages = [] + self.resolved_objects = {} + self.trailer = DictionaryObject() + self.xref = {} + self.xref_free_entry = {} + self.xref_objStm = {} + + @property + def root_object(self) -> DictionaryObject: + """Provide access to "/Root". Standardized with PdfWriter.""" + if self._validated_root: + return self._validated_root + root = self.trailer.get(TK.ROOT) + if is_null_or_none(root): + logger_warning('Cannot find "/Root" key in trailer', __name__) + elif ( + cast(DictionaryObject, cast(PdfObject, root).get_object()).get("/Type") + == "/Catalog" + ): + self._validated_root = cast( + DictionaryObject, cast(PdfObject, root).get_object() + ) + else: + logger_warning("Invalid Root object in trailer", __name__) + if self._validated_root is None: + logger_warning('Searching object with "/Catalog" key', __name__) + number_of_objects = cast(int, self.trailer.get("/Size", 0)) + for i in range(number_of_objects): + if i >= self._root_object_recovery_limit: + raise LimitReachedError("Maximum Root object recovery limit reached.") + try: + obj = self.get_object(i + 1) + except Exception: # to be sure to capture all errors + obj = None + if isinstance(obj, DictionaryObject) and obj.get("/Type") == "/Catalog": + self._validated_root = obj + logger_warning(f"Root found at {obj.indirect_reference!r}", __name__) + break + if self._validated_root is None: + if not is_null_or_none(root) and "/Pages" in cast(DictionaryObject, cast(PdfObject, root).get_object()): + logger_warning( + f"Possible root found at {cast(PdfObject, root).indirect_reference!r}, but missing /Catalog key", + __name__ + ) + self._validated_root = cast( + DictionaryObject, cast(PdfObject, root).get_object() + ) + else: + raise PdfReadError("Cannot find Root object in pdf") + return self._validated_root + + @property + def _info(self) -> Optional[DictionaryObject]: + """ + Provide access to "/Info". Standardized with PdfWriter. + + Returns: + /Info Dictionary; None if the entry does not exist + + """ + info = self.trailer.get(TK.INFO, None) + if is_null_or_none(info): + return None + assert info is not None, "mypy" + info = info.get_object() + if not isinstance(info, DictionaryObject): + raise PdfReadError( + "Trailer not found or does not point to a document information dictionary" + ) + return info + + @property + def _ID(self) -> Optional[ArrayObject]: + """ + Provide access to "/ID". Standardized with PdfWriter. + + Returns: + /ID array; None if the entry does not exist + + """ + id = self.trailer.get(TK.ID, None) + if is_null_or_none(id): + return None + assert id is not None, "mypy" + return cast(ArrayObject, id.get_object()) + + @property + def pdf_header(self) -> str: + """ + The first 8 bytes of the file. + + This is typically something like ``'%PDF-1.6'`` and can be used to + detect if the file is actually a PDF file and which version it is. + """ + # TODO: Make this return a bytes object for consistency + # but that needs a deprecation + loc = self.stream.tell() + self.stream.seek(0, 0) + pdf_file_version = self.stream.read(8).decode("utf-8", "backslashreplace") + self.stream.seek(loc, 0) # return to where it was + return pdf_file_version + + @property + def xmp_metadata(self) -> Optional[XmpInformation]: + """XMP (Extensible Metadata Platform) data.""" + try: + self._override_encryption = True + return cast(XmpInformation, self.root_object.xmp_metadata) + finally: + self._override_encryption = False + + def _get_page_number_by_indirect( + self, indirect_reference: Union[None, int, NullObject, IndirectObject] + ) -> Optional[int]: + """ + Retrieve the page number from an indirect reference. + + Args: + indirect_reference: The indirect reference to locate. + + Returns: + Page number or None. + + """ + if self._page_id2num is None: + self._page_id2num = { + x.indirect_reference.idnum: i for i, x in enumerate(self.pages) # type: ignore + } + + if is_null_or_none(indirect_reference): + return None + assert isinstance(indirect_reference, (int, IndirectObject)), "mypy" + if isinstance(indirect_reference, int): + idnum = indirect_reference + else: + idnum = indirect_reference.idnum + assert self._page_id2num is not None, "hint for mypy" + return self._page_id2num.get(idnum, None) + + def _get_object_from_stream( + self, indirect_reference: IndirectObject + ) -> Union[int, PdfObject, str]: + # indirect reference to object in object stream + # read the entire object stream into memory + stmnum, _idx = self.xref_objStm[indirect_reference.idnum] + obj_stm: EncodedStreamObject = IndirectObject(stmnum, 0, self).get_object() # type: ignore + # This is an xref to a stream, so its type better be a stream + assert cast(str, obj_stm["/Type"]) == "/ObjStm" + # Parse ALL objects in this stream in one pass and cache them. + # This avoids O(N²) behavior when many objects from the same stream + # are resolved individually (each call would re-parse the header). + stream_data = BytesIO(obj_stm.get_data()) + n = int(obj_stm["/N"]) # type: ignore[call-overload] + first_offset = int(obj_stm["/First"]) # type: ignore[call-overload] + + # ObjStm header format: "objnum offset objnum offset ..." + # smallest possible entry: "0 0" = 3 bytes (1 digit + 1 space + 1 digit) + # using // 4 would reject a valid 3-byte single entry (3 // 4 = 0) + max_n = stream_data.getbuffer().nbytes // 3 + stream_data.seek(0) + if n > max_n: + if self.strict: + raise LimitReachedError(f"Value /N {n} for object {stmnum} exceeds maximum allowed value {max_n}.") + logger_warning( + f"Value /N {n} for object {stmnum} exceeds maximum allowed value {max_n}. Limiting to {max_n}.", + src=__name__ + ) + n = max_n + + # Phase 1: Read the index (objnum, offset) pairs from the header. + obj_index: list[tuple[int, int]] = [] + for _i in range(n): + read_non_whitespace(stream_data) + stream_data.seek(-1, 1) + objnum = NumberObject.read_from_stream(stream_data) + read_non_whitespace(stream_data) + stream_data.seek(-1, 1) + offset = NumberObject.read_from_stream(stream_data) + read_non_whitespace(stream_data) + stream_data.seek(-1, 1) + obj_index.append((int(objnum), int(offset))) + + # Phase 2: Parse each object and cache it. + target_obj: Union[int, PdfObject, str] = NullObject() + found = False + for i, (obj_num, obj_offset) in enumerate(obj_index): + # Skip objects already in the cache. + cached = self.cache_get_indirect_object(0, obj_num) + if cached is not None: + if obj_num == indirect_reference.idnum: + target_obj = cached + found = True + continue + + stream_data.seek(first_offset + obj_offset, 0) + + # To cope with case where the 'pointer' is on a white space + read_non_whitespace(stream_data) + stream_data.seek(-1, 1) + + try: + obj = read_object(stream_data, self) + except PdfStreamError as exc: + # Stream object cannot be read. Normally, a critical error, but + # Adobe Reader doesn't complain, so continue (in strict mode?) + logger_warning( + f"Invalid stream (index {i}) within object " + f"{obj_num} 0: {exc}", + __name__, + ) + if self.strict: # pragma: no cover + raise PdfReadError( + f"Cannot read object stream: {exc}" + ) # pragma: no cover + obj = NullObject() # pragma: no cover + + # Only cache if this stream is the authoritative source for the object. + # Incremental updates may override objects originally in the stream; + # caching those stale versions would shadow the newer xref entry. + authoritative_stm, _idx = self.xref_objStm.get(obj_num, (None, None)) + if authoritative_stm == stmnum: + self.cache_indirect_object(0, obj_num, obj) # type: ignore[arg-type] + + if obj_num == indirect_reference.idnum: + target_obj = obj + found = True + + if not found and self.strict: # pragma: no cover + raise PdfReadError( + "This is a fatal error in strict mode." + ) # pragma: no cover + return target_obj + + def get_object( + self, indirect_reference: Union[int, IndirectObject] + ) -> Optional[PdfObject]: + if isinstance(indirect_reference, int): + indirect_reference = IndirectObject(indirect_reference, 0, self) + retval = self.cache_get_indirect_object( + indirect_reference.generation, indirect_reference.idnum + ) + if retval is not None: + return retval + if ( + indirect_reference.generation == 0 + and indirect_reference.idnum in self.xref_objStm + ): + retval = self._get_object_from_stream(indirect_reference) # type: ignore + elif ( + indirect_reference.generation in self.xref + and indirect_reference.idnum in self.xref[indirect_reference.generation] + ): + if self.xref_free_entry.get(indirect_reference.generation, {}).get( + indirect_reference.idnum, False + ): + return NullObject() + start = self.xref[indirect_reference.generation][indirect_reference.idnum] + self.stream.seek(start, 0) + try: + idnum, generation = self.read_object_header(self.stream) + if ( + idnum != indirect_reference.idnum + or generation != indirect_reference.generation + ): + raise PdfReadError("Not matching, we parse the file for it") + except Exception: + if hasattr(self.stream, "getbuffer"): + buf = bytes(self.stream.getbuffer()) + else: + p = self.stream.tell() + self.stream.seek(0, 0) + buf = self.stream.read(-1) + self.stream.seek(p, 0) + m = re.search( + rf"\s{indirect_reference.idnum}\s+{indirect_reference.generation}\s+obj".encode(), + buf, + ) + if m is not None: + logger_warning( + f"Object ID {indirect_reference.idnum},{indirect_reference.generation} ref repaired", + __name__, + ) + self.xref[indirect_reference.generation][ + indirect_reference.idnum + ] = (m.start(0) + 1) + self.stream.seek(m.start(0) + 1) + idnum, generation = self.read_object_header(self.stream) + else: + idnum = -1 + generation = -1 # exception will be raised below + if idnum != indirect_reference.idnum and self.xref_index: + # xref table probably had bad indexes due to not being zero-indexed + if self.strict: + raise PdfReadError( + f"Expected object ID ({indirect_reference.idnum} {indirect_reference.generation}) " + f"does not match actual ({idnum} {generation}); " + "xref table not zero-indexed." + ) + # xref table is corrected in non-strict mode + elif idnum != indirect_reference.idnum and self.strict: + # some other problem + raise PdfReadError( + f"Expected object ID ({indirect_reference.idnum} {indirect_reference.generation}) " + f"does not match actual ({idnum} {generation})." + ) + if self.strict: + assert generation == indirect_reference.generation + + current_object = (indirect_reference.idnum, indirect_reference.generation) + if current_object in self._known_objects: + raise LimitReachedError(f"Detected loop with self reference for {indirect_reference!r}.") + self._known_objects.add(current_object) + retval = read_object(self.stream, self) # type: ignore + self._known_objects.remove(current_object) + + # override encryption is used for the /Encrypt dictionary + if not self._override_encryption and self._encryption is not None: + # if we don't have the encryption key: + if not self._encryption.is_decrypted(): + raise FileNotDecryptedError("File has not been decrypted") + # otherwise, decrypt here... + retval = cast(PdfObject, retval) + retval = self._encryption.decrypt_object( + retval, indirect_reference.idnum, indirect_reference.generation, + strict=self.strict, + ) + else: + if hasattr(self.stream, "getbuffer"): + buf = bytes(self.stream.getbuffer()) + else: + p = self.stream.tell() + self.stream.seek(0, 0) + buf = self.stream.read(-1) + self.stream.seek(p, 0) + m = re.search( + rf"\s{indirect_reference.idnum}\s+{indirect_reference.generation}\s+obj".encode(), + buf, + ) + if m is not None: + logger_warning( + f"Object {indirect_reference.idnum} {indirect_reference.generation} found", + __name__, + ) + if indirect_reference.generation not in self.xref: + self.xref[indirect_reference.generation] = {} + self.xref[indirect_reference.generation][indirect_reference.idnum] = ( + m.start(0) + 1 + ) + self.stream.seek(m.end(0) + 1) + skip_over_whitespace(self.stream) + self.stream.seek(-1, 1) + retval = read_object(self.stream, self) # type: ignore + + # override encryption is used for the /Encrypt dictionary + if not self._override_encryption and self._encryption is not None: + # if we don't have the encryption key: + if not self._encryption.is_decrypted(): + raise FileNotDecryptedError("File has not been decrypted") + # otherwise, decrypt here... + retval = cast(PdfObject, retval) + retval = self._encryption.decrypt_object( + retval, indirect_reference.idnum, indirect_reference.generation, + strict=self.strict, + ) + else: + logger_warning( + f"Object {indirect_reference.idnum} {indirect_reference.generation} not defined.", + __name__, + ) + if self.strict: + raise PdfReadError("Could not find object.") + # For ObjStm objects, _get_object_from_stream already cached + # the result during batch parsing; skip the redundant cache write + # to avoid "Overwriting cache" warnings. For non-ObjStm objects + # (including encrypted ones that need decrypted values cached), + # always write. + if not ( + indirect_reference.generation == 0 + and indirect_reference.idnum in self.xref_objStm + ): + self.cache_indirect_object( + indirect_reference.generation, indirect_reference.idnum, retval + ) + return retval + + def read_object_header(self, stream: StreamType) -> tuple[int, int]: + # Should never be necessary to read out whitespace, since the + # cross-reference table should put us in the right spot to read the + # object header. In reality some files have stupid cross-reference + # tables that are off by whitespace bytes. + skip_over_comment(stream) + extra = skip_over_whitespace(stream) + stream.seek(-1, 1) + idnum = read_until_whitespace(stream) + extra |= skip_over_whitespace(stream) + stream.seek(-1, 1) + generation = read_until_whitespace(stream) + extra |= skip_over_whitespace(stream) + stream.seek(-1, 1) + + # although it's not used, it might still be necessary to read + _obj = stream.read(3) + + read_non_whitespace(stream) + stream.seek(-1, 1) + if extra and self.strict: + logger_warning( + f"Superfluous whitespace found in object header {idnum} {generation}", # type: ignore + __name__, + ) + return int(idnum), int(generation) + + def cache_get_indirect_object( + self, generation: int, idnum: int + ) -> Optional[PdfObject]: + try: + return self.resolved_objects.get((generation, idnum)) + except RecursionError: + raise PdfReadError("Maximum recursion depth reached.") + + def cache_indirect_object( + self, generation: int, idnum: int, obj: Optional[PdfObject] + ) -> Optional[PdfObject]: + if (generation, idnum) in self.resolved_objects: + msg = f"Overwriting cache for {generation} {idnum}" + if self.strict: + raise PdfReadError(msg) + logger_warning(msg, __name__) + self.resolved_objects[(generation, idnum)] = obj + if obj is not None: + obj.indirect_reference = IndirectObject(idnum, generation, self) + return obj + + def _replace_object(self, indirect_reference: IndirectObject, obj: PdfObject) -> PdfObject: + # function reserved for future development + if indirect_reference.pdf != self: + raise ValueError("Cannot update PdfReader with external object") + if (indirect_reference.generation, indirect_reference.idnum) not in self.resolved_objects: + raise ValueError("Cannot find referenced object") + self.resolved_objects[(indirect_reference.generation, indirect_reference.idnum)] = obj + obj.indirect_reference = indirect_reference + return obj + + def read(self, stream: StreamType) -> None: + """ + Read and process the PDF stream, extracting necessary data. + + Args: + stream: The PDF file stream. + + """ + self._basic_validation(stream) + self._find_eof_marker(stream) + startxref = self._find_startxref_pos(stream) + self._startxref = startxref + + # check and eventually correct the startxref only if not strict + xref_issue_nr = self._get_xref_issues(stream, startxref) + if xref_issue_nr != 0: + if self.strict and xref_issue_nr: + raise PdfReadError("Broken xref table") + logger_warning(f"incorrect startxref pointer({xref_issue_nr})", __name__) + + # read all cross-reference tables and their trailers + self._read_xref_tables_and_trailers(stream, startxref, xref_issue_nr) + + # if not zero-indexed, verify that the table is correct; change it if necessary + if self.xref_index and not self.strict: + loc = stream.tell() + for gen, xref_entry in self.xref.items(): + if gen == 65535: + continue + xref_k = sorted( + xref_entry.keys() + ) # ensure ascending to prevent damage + for id in xref_k: + stream.seek(xref_entry[id], 0) + try: + pid, _pgen = self.read_object_header(stream) + except ValueError: + self._rebuild_xref_table(stream) + break + if pid == id - self.xref_index: + # fixing index item per item is required for revised PDF. + self.xref[gen][pid] = self.xref[gen][id] + del self.xref[gen][id] + # if not, then either it's just plain wrong, or the + # non-zero-index is actually correct + stream.seek(loc, 0) # return to where it was + + # remove wrong objects (not pointing to correct structures) - cf #2326 + if not self.strict: + loc = stream.tell() + for gen, xref_entry in self.xref.items(): + if gen == 65535: + continue + ids = list(xref_entry.keys()) + for id in ids: + stream.seek(xref_entry[id], 0) + try: + self.read_object_header(stream) + except ValueError: + logger_warning( + f"Ignoring wrong pointing object {id} {gen} (offset {xref_entry[id]})", + __name__, + ) + del xref_entry[id] # we can delete the id, we are parsing ids + stream.seek(loc, 0) # return to where it was + + def _basic_validation(self, stream: StreamType) -> None: + """Ensure the stream is valid and not empty.""" + stream.seek(0, os.SEEK_SET) + try: + header_byte = stream.read(5) + except UnicodeDecodeError: + raise UnsupportedOperation("cannot read header") + if header_byte == b"": + raise EmptyFileError("Cannot read an empty file") + if header_byte != b"%PDF-": + if self.strict: + raise PdfReadError( + f"PDF starts with '{header_byte.decode('utf8')}', " + "but '%PDF-' expected" + ) + logger_warning(f"invalid pdf header: {header_byte!r}", __name__) + stream.seek(0, os.SEEK_END) + + def _find_eof_marker(self, stream: StreamType) -> None: + """ + Jump to the %%EOF marker. + + According to the specs, the %%EOF marker should be at the very end of + the file. Hence for standard-compliant PDF documents this function will + read only the last part (DEFAULT_BUFFER_SIZE). + """ + HEADER_SIZE = 8 # to parse whole file, Header is e.g. '%PDF-1.6' + line = b"" + first = True + while not line.startswith(b"%%EOF"): + if line != b"" and first: + if any( + line.strip().endswith(tr) for tr in (b"%%EO", b"%%E", b"%%", b"%") + ): + # Consider the file as truncated while + # having enough confidence to carry on. + logger_warning("EOF marker seems truncated", __name__) + break + first = False + if b"startxref" in line: + logger_warning( + "CAUTION: startxref found while searching for %%EOF. " + "The file might be truncated and some data might not be read.", + __name__, + ) + if stream.tell() < HEADER_SIZE: + if self.strict: + raise PdfReadError("EOF marker not found") + logger_warning("EOF marker not found", __name__) + line = read_previous_line(stream) + + def _find_startxref_pos(self, stream: StreamType) -> int: + """ + Find startxref entry - the location of the xref table. + + Args: + stream: + + Returns: + The bytes offset + + """ + line = read_previous_line(stream) + try: + startxref = int(line) + except ValueError: + # 'startxref' may be on the same line as the location + if not line.startswith(b"startxref"): + raise PdfReadError("startxref not found") + startxref = int(line[9:].strip()) + logger_warning("startxref on same line as offset", __name__) + else: + line = read_previous_line(stream) + if not line.startswith(b"startxref"): + raise PdfReadError("startxref not found") + return startxref + + def _read_standard_xref_table(self, stream: StreamType) -> None: + # standard cross-reference table + ref = stream.read(3) + if ref != b"ref": + raise PdfReadError("xref table read error") + read_non_whitespace(stream) + stream.seek(-1, 1) + first_time = True # check if the first time looking at the xref table + while True: + num = cast(int, read_object(stream, self)) + if first_time and num != 0: + self.xref_index = num + if self.strict: + logger_warning( + "Xref table not zero-indexed. ID numbers for objects will be corrected.", + __name__, + ) + # if table not zero indexed, could be due to error from when PDF was created + # which will lead to mismatched indices later on, only warned and corrected if self.strict==True + first_time = False + read_non_whitespace(stream) + stream.seek(-1, 1) + size = cast(int, read_object(stream, self)) + if not isinstance(size, int): + logger_warning( + "Invalid/Truncated xref table. Rebuilding it.", + __name__, + ) + self._rebuild_xref_table(stream) + stream.read() + return + read_non_whitespace(stream) + stream.seek(-1, 1) + cnt = 0 + while cnt < size: + line = stream.read(20) + if not line: + raise PdfReadError("Unexpected empty line in Xref table.") + + # It's very clear in section 3.4.3 of the PDF spec + # that all cross-reference table lines are a fixed + # 20 bytes (as of PDF 1.7). However, some files have + # 21-byte entries (or more) due to the use of \r\n + # (CRLF) EOL's. Detect that case, and adjust the line + # until it does not begin with a \r (CR) or \n (LF). + while line[0] in b"\x0D\x0A": + stream.seek(-20 + 1, 1) + line = stream.read(20) + + # On the other hand, some malformed PDF files + # use a single character EOL without a preceding + # space. Detect that case, and seek the stream + # back one character (0-9 means we've bled into + # the next xref entry, t means we've bled into the + # text "trailer"): + if line[-1] in b"0123456789t": + stream.seek(-1, 1) + + try: + offset_b, generation_b = line[:16].split(b" ") + entry_type_b = line[17:18] + + offset, generation = int(offset_b), int(generation_b) + except Exception: + if hasattr(stream, "getbuffer"): + buf = bytes(stream.getbuffer()) + else: + p = stream.tell() + stream.seek(0, 0) + buf = stream.read(-1) + stream.seek(p) + + f = re.search(rf"{num}\s+(\d+)\s+obj".encode(), buf) + if f is None: + logger_warning( + f"entry {num} in Xref table invalid; object not found", + __name__, + ) + generation = 65535 + offset = -1 + entry_type_b = b"f" + else: + logger_warning( + f"entry {num} in Xref table invalid but object found", + __name__, + ) + generation = int(f.group(1)) + offset = f.start() + + if generation not in self.xref: + self.xref[generation] = {} + self.xref_free_entry[generation] = {} + if num in self.xref[generation]: + # It really seems like we should allow the last + # xref table in the file to override previous + # ones. Since we read the file backwards, assume + # any existing key is already set correctly. + pass + else: + if entry_type_b == b"n": + self.xref[generation][num] = offset + try: + self.xref_free_entry[generation][num] = entry_type_b == b"f" + except Exception: + pass + try: + self.xref_free_entry[65535][num] = entry_type_b == b"f" + except Exception: + pass + cnt += 1 + num += 1 + read_non_whitespace(stream) + stream.seek(-1, 1) + # Skip any PDF comments between xref entries and the trailer + # keyword. Some PDF producers (e.g. Vectorizer.AI) insert + # comments here which are legal per the PDF spec (§7.2.3). + while stream.read(1) == b"%": + stream.seek(-1, 1) + skip_over_comment(stream) + read_non_whitespace(stream) + stream.seek(-1, 1) + stream.seek(-1, 1) + trailer_tag = stream.read(7) + if trailer_tag != b"trailer": + # more xrefs! + stream.seek(-7, 1) + else: + break + + def _read_xref_tables_and_trailers( + self, stream: StreamType, startxref: Optional[int], xref_issue_nr: int + ) -> None: + """Read the cross-reference tables and trailers in the PDF stream.""" + self.xref = {} + self.xref_free_entry = {} + self.xref_objStm = {} + self.trailer = DictionaryObject() + visited_xref_offsets: set[int] = set() + while startxref is not None: + # Detect circular /Prev references in the xref chain + if startxref in visited_xref_offsets: + logger_warning( + f"Circular xref chain detected at offset {startxref}, stopping", + __name__, + ) + break + visited_xref_offsets.add(startxref) + # load the xref table + stream.seek(startxref, 0) + x = stream.read(1) + if x in b"\r\n": + x = stream.read(1) + if x == b"x": + startxref = self._read_xref(stream) + elif xref_issue_nr: + try: + self._rebuild_xref_table(stream) + break + except Exception: + xref_issue_nr = 0 + elif x.isdigit(): + try: + xrefstream = self._read_pdf15_xref_stream(stream) + except Exception as e: + if TK.ROOT in self.trailer: + logger_warning( + f"Previous trailer cannot be read: {e.args}", __name__ + ) + break + raise PdfReadError(f"Trailer cannot be read: {e!s}") + self._process_xref_stream(xrefstream) + if "/Prev" in xrefstream: + startxref = cast(int, xrefstream["/Prev"]) + else: + break + else: + startxref = self._read_xref_other_error(stream, startxref) + + def _process_xref_stream(self, xrefstream: DictionaryObject) -> None: + """Process and handle the xref stream.""" + trailer_keys = TK.ROOT, TK.ENCRYPT, TK.INFO, TK.ID, TK.SIZE + for key in trailer_keys: + if key in xrefstream and key not in self.trailer: + self.trailer[NameObject(key)] = xrefstream.raw_get(key) + if "/XRefStm" in xrefstream: + p = self.stream.tell() + self.stream.seek(cast(int, xrefstream["/XRefStm"]) + 1, 0) + self._read_pdf15_xref_stream(self.stream) + self.stream.seek(p, 0) + + def _read_xref(self, stream: StreamType) -> Optional[int]: + self._read_standard_xref_table(stream) + if stream.read(1) == b"": + return None + stream.seek(-1, 1) + read_non_whitespace(stream) + stream.seek(-1, 1) + new_trailer = cast(dict[str, Any], read_object(stream, self)) + for key, value in new_trailer.items(): + if key not in self.trailer: + self.trailer[key] = value + if "/XRefStm" in new_trailer: + p = stream.tell() + stream.seek(cast(int, new_trailer["/XRefStm"]) + 1, 0) + try: + self._read_pdf15_xref_stream(stream) + except Exception: + logger_warning( + f"XRef object at {new_trailer['/XRefStm']} can not be read, some object may be missing", + __name__, + ) + stream.seek(p, 0) + if "/Prev" in new_trailer: + return cast(int, new_trailer["/Prev"]) + return None + + def _read_xref_other_error( + self, stream: StreamType, startxref: int + ) -> Optional[int]: + # some PDFs have /Prev=0 in the trailer, instead of no /Prev + if startxref == 0: + if self.strict: + raise PdfReadError( + "/Prev=0 in the trailer (try opening with strict=False)" + ) + logger_warning( + "/Prev=0 in the trailer - assuming there is no previous xref table", + __name__, + ) + return None + # bad xref character at startxref. Let's see if we can find + # the xref table nearby, as we've observed this error with an + # off-by-one before. + stream.seek(-11, 1) + tmp = stream.read(20) + xref_loc = tmp.find(b"xref") + if xref_loc != -1: + startxref -= 10 - xref_loc + return startxref + # No explicit xref table, try finding a cross-reference stream. + stream.seek(startxref, 0) + for look in range(25): # value extended to cope with more linearized files + if stream.read(1).isdigit(): + # This is not a standard PDF, consider adding a warning + startxref += look + return startxref + # no xref table found at specified location + if "/Root" in self.trailer and not self.strict: + # if Root has been already found, just raise warning + logger_warning("Invalid parent xref., rebuild xref", __name__) + try: + self._rebuild_xref_table(stream) + return None + except Exception: + raise PdfReadError("Cannot rebuild xref") + raise PdfReadError("Could not find xref table at specified location") + + def _sanitize_pdf15_xref_stream_index_pairs( + self, index_pairs: list[int], entry_sizes: list[int], xref_stream: ContentStream + ) -> list[int]: + # `entry_sizes` holds the byte widths for the entries. Summing determines the total number of bytes per entry. + # We expect up to 3 values, clamping to at least 1 avoids ZeroDivisionError in next step. + # `min_entry_bytes` will be the smallest plausible size of one xref entry. + min_entry_bytes = max(sum(int(entry_sizes[i]) for i in range(min(len(entry_sizes), 3))), 1) + # maximum number of entries that could physically fit + max_entries = len(xref_stream.get_data()) // min_entry_bytes + 1 + + result = [] + total = 0 + + for index, pair_value in enumerate(index_pairs): + pair_value_int = int(pair_value) + + # `index_pairs` has the format `[start0, count0, start1, count1, ...]` + # Only modify the counts here, but keep the start values. + if index % 2 == 1: + if total + pair_value_int > max_entries: + if self.strict: + raise LimitReachedError( + f"Total XRef entries {total + pair_value_int} exceed maximum allowed value {max_entries}." + ) + new_v = max(0, max_entries - total) + logger_warning( + f"Clamping XRef count from {pair_value_int} to {new_v} to fit stream size.", + src=__name__ + ) + pair_value_int = new_v + + total += pair_value_int + + result.append(pair_value_int) + + return result + + def _read_pdf15_xref_stream( + self, stream: StreamType + ) -> Union[ContentStream, EncodedStreamObject, DecodedStreamObject]: + """Read the cross-reference stream for PDF 1.5+.""" + stream.seek(-1, 1) + stream_idnum, stream_generation = self.read_object_header(stream) + xref_stream = cast(ContentStream, read_object(stream, self)) + if cast(str, xref_stream["/Type"]) != "/XRef": + raise PdfReadError(f"Unexpected type {xref_stream['/Type']!r}") + self.cache_indirect_object(stream_generation, stream_idnum, xref_stream) + + # Index pairs specify the subsections in the dictionary. + # If none, create one subsection that spans everything. + if "/Size" not in xref_stream: + # According to table 17 of the PDF 2.0 specification, this key is required. + raise PdfReadError(f"Size missing from XRef stream {xref_stream!r}!") + index_pairs = xref_stream.get("/Index", [0, xref_stream["/Size"]]) + + entry_sizes = cast(list[int], xref_stream.get("/W")) + assert len(entry_sizes) >= 3 + if self.strict and len(entry_sizes) > 3: + raise PdfReadError(f"Too many entry sizes: {entry_sizes}") + index_pairs = self._sanitize_pdf15_xref_stream_index_pairs( + index_pairs=index_pairs, entry_sizes=entry_sizes, xref_stream=xref_stream + ) + + stream_data = BytesIO(xref_stream.get_data()) + + def get_entry(i: int) -> Union[int, tuple[int, ...]]: + # Reads the correct number of bytes for each entry. See the + # discussion of the W parameter in PDF spec table 17. + if entry_sizes[i] > 0: + d = stream_data.read(entry_sizes[i]) + return convert_to_int(d, entry_sizes[i]) + + # PDF Spec Table 17: A value of zero for an element in the + # W array indicates...the default value shall be used + if i == 0: + return 1 # First value defaults to 1 + return 0 + + def used_before(num: int, generation: Union[int, tuple[int, ...]]) -> bool: + # We move backwards through the xrefs, don't replace any. + return num in self.xref.get(generation, []) or num in self.xref_objStm # type: ignore + + # Iterate through each subsection + self._read_xref_subsections(index_pairs, get_entry, used_before) + return xref_stream + + @staticmethod + def _get_xref_issues(stream: StreamType, startxref: int) -> int: + """ + Return an int which indicates an issue. 0 means there is no issue. + + Args: + stream: + startxref: + + Returns: + 0 means no issue, other values represent specific issues. + + """ + if startxref == 0: + return 4 + + stream.seek(startxref - 1, 0) # -1 to check character before + line = stream.read(1) + if line == b"j": + line = stream.read(1) + if line not in b"\r\n \t": + return 1 + line = stream.read(4) + if line != b"xref": + # not a xref so check if it is an XREF object + line = b"" + while line in b"0123456789 \t": + line = stream.read(1) + if line == b"": + return 2 + line += stream.read(2) # 1 char already read, +2 to check "obj" + if line.lower() != b"obj": + return 3 + return 0 + + @classmethod + def _find_pdf_objects(cls, data: bytes) -> Iterable[tuple[int, int, int]]: + index = 0 + ord_0 = ord("0") + ord_9 = ord("9") + while True: + index = data.find(b" obj", index) + if index == -1: + return + + index_before_space = index - 1 + + # Skip whitespace backwards + while index_before_space >= 0 and data[index_before_space] in WHITESPACES_AS_BYTES: + index_before_space -= 1 + + # Read generation number + generation_end = index_before_space + 1 + while index_before_space >= 0 and ord_0 <= data[index_before_space] <= ord_9: + index_before_space -= 1 + generation_start = index_before_space + 1 + + # Skip whitespace + while index_before_space >= 0 and data[index_before_space] in WHITESPACES_AS_BYTES: + index_before_space -= 1 + + # Read object number + object_end = index_before_space + 1 + while index_before_space >= 0 and ord_0 <= data[index_before_space] <= ord_9: + index_before_space -= 1 + object_start = index_before_space + 1 + + # Validate + if object_start < object_end and generation_start < generation_end: + object_number = int(data[object_start:object_end]) + generation_number = int(data[generation_start:generation_end]) + + yield object_number, generation_number, object_start + + index += 4 # len(b" obj") + + @classmethod + def _find_pdf_trailers(cls, data: bytes) -> Iterable[int]: + index = 0 + data_length = len(data) + while True: + index = data.find(b"trailer", index) + if index == -1: + return + + index_after_trailer = index + 7 # len(b"trailer") + + # Skip whitespace + while index_after_trailer < data_length and data[index_after_trailer] in WHITESPACES_AS_BYTES: + index_after_trailer += 1 + + # Must be dictionary start + if index_after_trailer + 1 < data_length and data[index_after_trailer:index_after_trailer+2] == b"<<": + yield index_after_trailer # offset of '<<' + + index += 7 # len(b"trailer") + + def _rebuild_xref_table(self, stream: StreamType) -> None: + self.xref = {} + stream.seek(0, 0) + stream_data = stream.read(-1) + + for object_number, generation_number, object_start in self._find_pdf_objects(stream_data): + if generation_number not in self.xref: + self.xref[generation_number] = {} + self.xref[generation_number][object_number] = object_start + + logger_warning("parsing for Object Streams", __name__) + for generation_number in self.xref: + for object_number in self.xref[generation_number]: + # get_object in manual + stream.seek(self.xref[generation_number][object_number], 0) + try: + _ = self.read_object_header(stream) + obj = cast(StreamObject, read_object(stream, self)) + if obj.get("/Type", "") != "/ObjStm": + continue + object_stream = BytesIO(obj.get_data()) + actual_count = 0 + while True: + current = read_until_whitespace(object_stream) + if not current.isdigit(): + break + inner_object_number = int(current) + skip_over_whitespace(object_stream) + object_stream.seek(-1, 1) + current = read_until_whitespace(object_stream) + if not current.isdigit(): # pragma: no cover + break # pragma: no cover + inner_generation_number = int(current) + self.xref_objStm[inner_object_number] = (object_number, inner_generation_number) + actual_count += 1 + if actual_count != obj.get("/N"): # pragma: no cover + logger_warning( # pragma: no cover + f"found {actual_count} objects within Object({object_number},{generation_number})" + f" whereas {obj.get('/N')} expected", + __name__, + ) + except Exception: # could be multiple causes + pass + + stream.seek(0, 0) + for position in self._find_pdf_trailers(stream_data): + stream.seek(position, 0) + new_trailer = cast(dict[Any, Any], read_object(stream, self)) + # Here, we are parsing the file from start to end, the new data have to erase the existing. + for key, value in new_trailer.items(): + self.trailer[key] = value + + def _read_xref_subsections( + self, + idx_pairs: list[int], + get_entry: Callable[[int], Union[int, tuple[int, ...]]], + used_before: Callable[[int, Union[int, tuple[int, ...]]], bool], + ) -> None: + """Read and process the subsections of the xref.""" + for start, size in self._pairs(idx_pairs): + # The subsections must increase + for num in range(start, start + size): + # The first entry is the type + xref_type = get_entry(0) + # The rest of the elements depend on the xref_type + if xref_type == 0: + # linked list of free objects + next_free_object = get_entry(1) # noqa: F841 + next_generation = get_entry(2) # noqa: F841 + elif xref_type == 1: + # objects that are in use but are not compressed + byte_offset = get_entry(1) + generation = get_entry(2) + if generation not in self.xref: + self.xref[generation] = {} # type: ignore + if not used_before(num, generation): + self.xref[generation][num] = byte_offset # type: ignore + elif xref_type == 2: + # compressed objects + objstr_num = get_entry(1) + obstr_idx = get_entry(2) + generation = 0 # PDF spec table 18, generation is 0 + if not used_before(num, generation): + self.xref_objStm[num] = (objstr_num, obstr_idx) + elif self.strict: + raise PdfReadError(f"Unknown xref type: {xref_type}") + + def _pairs(self, array: list[int]) -> Iterable[tuple[int, int]]: + """Iterate over pairs in the array.""" + i = 0 + while i + 1 < len(array): + yield array[i], array[i + 1] + i += 2 + + def decrypt(self, password: Union[str, bytes]) -> PasswordType: + """ + When using an encrypted / secured PDF file with the PDF Standard + encryption handler, this function will allow the file to be decrypted. + It checks the given password against the document's user password and + owner password, and then stores the resulting decryption key if either + password is correct. + + It does not matter which password was matched. Both passwords provide + the correct decryption key that will allow the document to be used with + this library. + + Args: + password: The password to match. + + Returns: + An indicator if the document was decrypted and whether it was the + owner password or the user password. + + """ + if not self._encryption: + raise PdfReadError("Not encrypted file") + # TODO: raise Exception for wrong password + return self._encryption.verify(password) + + @property + def is_encrypted(self) -> bool: + """ + Read-only boolean property showing whether this PDF file is encrypted. + + Note that this property, if true, will remain true even after the + :meth:`decrypt()` method is called. + """ + return TK.ENCRYPT in self.trailer + + def add_form_topname(self, name: str) -> Optional[DictionaryObject]: + """ + Add a top level form that groups all form fields below it. + + Args: + name: text string of the "/T" Attribute of the created object + + Returns: + The created object. ``None`` means no object was created. + + """ + catalog = self.root_object + + if "/AcroForm" not in catalog or not isinstance( + catalog["/AcroForm"], DictionaryObject + ): + return None + acroform = cast(DictionaryObject, catalog[NameObject("/AcroForm")]) + if "/Fields" not in acroform: + # TODO: No error but this may be extended for XFA Forms + return None + + interim = DictionaryObject() + interim[NameObject("/T")] = TextStringObject(name) + interim[NameObject("/Kids")] = acroform[NameObject("/Fields")] + self.cache_indirect_object( + 0, + max(i for (g, i) in self.resolved_objects if g == 0) + 1, + interim, + ) + arr = ArrayObject() + arr.append(interim.indirect_reference) + acroform[NameObject("/Fields")] = arr + for o in cast(ArrayObject, interim["/Kids"]): + obj = o.get_object() + if "/Parent" in obj: + logger_warning( + f"Top Level Form Field {obj.indirect_reference} have a non-expected parent", + __name__, + ) + obj[NameObject("/Parent")] = interim.indirect_reference + return interim + + def rename_form_topname(self, name: str) -> Optional[DictionaryObject]: + """ + Rename top level form field that all form fields below it. + + Args: + name: text string of the "/T" field of the created object + + Returns: + The modified object. ``None`` means no object was modified. + + """ + catalog = self.root_object + + if "/AcroForm" not in catalog or not isinstance( + catalog["/AcroForm"], DictionaryObject + ): + return None + acroform = cast(DictionaryObject, catalog[NameObject("/AcroForm")]) + if "/Fields" not in acroform: + return None + + interim = cast( + DictionaryObject, + cast(ArrayObject, acroform[NameObject("/Fields")])[0].get_object(), + ) + interim[NameObject("/T")] = TextStringObject(name) + return interim + + def _repr_mimebundle_( + self, + include: Union[None, Iterable[str]] = None, + exclude: Union[None, Iterable[str]] = None, + ) -> dict[str, Any]: + """ + Integration into Jupyter Notebooks. + + This method returns a dictionary that maps a mime-type to its + representation. + + .. seealso:: + + https://ipython.readthedocs.io/en/stable/config/integrating.html + """ + self.stream.seek(0) + pdf_data = self.stream.read() + data = { + "application/pdf": pdf_data, + } + + if include is not None: + # Filter representations based on include list + data = {k: v for k, v in data.items() if k in include} + + if exclude is not None: + # Remove representations based on exclude list + data = {k: v for k, v in data.items() if k not in exclude} + + return data diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_text_extraction/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_text_extraction/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b3b89aa4ebbd5aeebc430ef3b45fcf26890b75d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_text_extraction/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_text_extraction/__pycache__/_text_extractor.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_text_extraction/__pycache__/_text_extractor.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b535060cf0f5812a94dc88010ff1038e6cbe9385 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_text_extraction/__pycache__/_text_extractor.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_text_extraction/_layout_mode/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_text_extraction/_layout_mode/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d3151600e9bc1029a6d85c2bc9e53e9e36fd07df --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_text_extraction/_layout_mode/__init__.py @@ -0,0 +1,16 @@ +"""Layout mode text extraction extension for pypdf""" +from ..._font import Font +from ._fixed_width_page import ( + fixed_char_width, + fixed_width_page, + text_show_operations, + y_coordinate_groups, +) + +__all__ = [ + "Font", + "fixed_char_width", + "fixed_width_page", + "text_show_operations", + "y_coordinate_groups", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_text_extraction/_layout_mode/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_text_extraction/_layout_mode/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0bbec8b4ce4bfe96d93c3541caa562b121d76b6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_text_extraction/_layout_mode/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_text_extraction/_layout_mode/__pycache__/_fixed_width_page.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_text_extraction/_layout_mode/__pycache__/_fixed_width_page.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e092c3c5bdddfe5eef96e1a136c306486fa490ff Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_text_extraction/_layout_mode/__pycache__/_fixed_width_page.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_text_extraction/_layout_mode/__pycache__/_text_state_manager.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_text_extraction/_layout_mode/__pycache__/_text_state_manager.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c571d51c3ab655b1d8050a9379d336958fe12bcb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_text_extraction/_layout_mode/__pycache__/_text_state_manager.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_text_extraction/_layout_mode/__pycache__/_text_state_params.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_text_extraction/_layout_mode/__pycache__/_text_state_params.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10ca84a9636941ce6e9cc5598250e1f6232759c3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_text_extraction/_layout_mode/__pycache__/_text_state_params.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_text_extraction/_layout_mode/_fixed_width_page.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_text_extraction/_layout_mode/_fixed_width_page.py new file mode 100644 index 0000000000000000000000000000000000000000..48f654ebb4c680494bdab5c17582e632f1e3ab54 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_text_extraction/_layout_mode/_fixed_width_page.py @@ -0,0 +1,400 @@ +"""Extract PDF text preserving the layout of the source PDF""" + +from collections.abc import Iterator +from itertools import groupby +from math import ceil +from pathlib import Path +from typing import Any, Literal, Optional, TypedDict + +from ..._font import Font +from ..._utils import logger_warning +from .. import LAYOUT_NEW_BT_GROUP_SPACE_WIDTHS +from ._text_state_manager import TextStateManager +from ._text_state_params import TextStateParams + + +class BTGroup(TypedDict): + """ + Dict describing a line of text rendered within a BT/ET operator pair. + If multiple text show operations render text on the same line, the text + will be combined into a single BTGroup dict. + + Keys: + tx: x coordinate of first character in BTGroup + ty: y coordinate of first character in BTGroup + font_size: nominal font size + font_height: effective font height + text: rendered text + displaced_tx: x coordinate of last character in BTGroup + flip_sort: -1 if page is upside down, else 1 + """ + + tx: float + ty: float + font_size: float + font_height: float + text: str + displaced_tx: float + flip_sort: Literal[-1, 1] + + +def bt_group(tj_op: TextStateParams, rendered_text: str, dispaced_tx: float) -> BTGroup: + """ + BTGroup constructed from a TextStateParams instance, rendered text, and + displaced tx value. + + Args: + tj_op (TextStateParams): TextStateParams instance + rendered_text (str): rendered text + dispaced_tx (float): x coordinate of last character in BTGroup + + """ + return BTGroup( + tx=tj_op.tx, + ty=tj_op.ty, + font_size=tj_op.font_size, + font_height=tj_op.font_height, + text=rendered_text, + displaced_tx=dispaced_tx, + flip_sort=-1 if tj_op.flip_vertical else 1, + ) + + +def recurs_to_target_op( + ops: Iterator[tuple[list[Any], bytes]], + text_state_mgr: TextStateManager, + end_target: Literal[b"Q", b"ET"], + fonts: dict[str, Font], + strip_rotated: bool = True, +) -> tuple[list[BTGroup], list[TextStateParams]]: + """ + Recurse operators between BT/ET and/or q/Q operators managing the transform + stack and capturing text positioning and rendering data. + + Args: + ops: iterator of operators in content stream + text_state_mgr: a TextStateManager instance + end_target: Either b"Q" (ends b"q" op) or b"ET" (ends b"BT" op) + fonts: font dictionary as returned by PageObject._layout_mode_fonts() + + Returns: + tuple: list of BTGroup dicts + list of TextStateParams dataclass instances. + + """ + # 1 entry per line of text rendered within each BT/ET operation. + bt_groups: list[BTGroup] = [] + + # 1 entry per text show operator (Tj/TJ/'/") + tj_ops: list[TextStateParams] = [] + + if end_target == b"Q": + # add new q level. cm's added at this level will be popped at next b'Q' + text_state_mgr.add_q() + + for operands, op in ops: + # The loop is broken by the end target, or exits normally when there are no more ops. + if op == end_target: + if op == b"Q": + text_state_mgr.remove_q() + if op == b"ET": + if not tj_ops: + return bt_groups, tj_ops + _text = "" + bt_idx = 0 # idx of first tj in this bt group + last_displaced_tx = tj_ops[bt_idx].displaced_tx + last_ty = tj_ops[bt_idx].ty + for _idx, _tj in enumerate( + tj_ops + ): # ... build text from new Tj operators + if strip_rotated and _tj.rotated: + continue + if not _tj.font.interpretable: # generates warning + continue + # if the y position of the text is greater than the font height, assume + # the text is on a new line and start a new group + if abs(_tj.ty - last_ty) > _tj.font_height: + if _text.strip(): + bt_groups.append( + bt_group(tj_ops[bt_idx], _text, last_displaced_tx) + ) + bt_idx = _idx + _text = "" + + # if the x position of the text is less than the last x position by + # more than 5 spaces widths, assume the text order should be flipped + # and start a new group + if ( + last_displaced_tx - _tj.tx + > _tj.space_tx * LAYOUT_NEW_BT_GROUP_SPACE_WIDTHS + ): + if _text.strip(): + bt_groups.append( + bt_group(tj_ops[bt_idx], _text, last_displaced_tx) + ) + bt_idx = _idx + last_displaced_tx = _tj.displaced_tx + _text = "" + + # calculate excess x translation based on ending tx of previous Tj. + # multiply by bool (_idx != bt_idx) to ensure spaces aren't double + # applied to the first tj of a BTGroup in fixed_width_page(). + excess_tx = round(_tj.tx - last_displaced_tx, 3) * (_idx != bt_idx) + # space_tx could be 0 if either Tz or font_size was 0 for this _tj. + spaces = int(excess_tx // _tj.space_tx) if _tj.space_tx else 0 + new_text = f'{" " * spaces}{_tj.txt}' + + last_ty = _tj.ty + _text = f"{_text}{new_text}" + last_displaced_tx = _tj.displaced_tx + if _text: + bt_groups.append(bt_group(tj_ops[bt_idx], _text, last_displaced_tx)) + text_state_mgr.reset_tm() + break + if op == b"q": + bts, tjs = recurs_to_target_op( + ops, text_state_mgr, b"Q", fonts, strip_rotated + ) + bt_groups.extend(bts) + tj_ops.extend(tjs) + elif op == b"cm": + text_state_mgr.add_cm(*operands) + elif op == b"BT": + bts, tjs = recurs_to_target_op( + ops, text_state_mgr, b"ET", fonts, strip_rotated + ) + bt_groups.extend(bts) + tj_ops.extend(tjs) + elif op == b"Tj": + tj_ops.append(text_state_mgr.text_state_params(operands[0])) + elif op == b"TJ": + _tj = text_state_mgr.text_state_params() + for tj_op in operands[0]: + if isinstance(tj_op, bytes): + _tj = text_state_mgr.text_state_params(tj_op) + tj_ops.append(_tj) + else: + text_state_mgr.add_trm(_tj.displacement_matrix(td_offset=tj_op)) + elif op == b"'": + text_state_mgr.reset_trm() + text_state_mgr.add_tm([0, -text_state_mgr.TL]) + tj_ops.append(text_state_mgr.text_state_params(operands[0])) + elif op == b'"': + text_state_mgr.reset_trm() + text_state_mgr.set_state_param(b"Tw", operands[0]) + text_state_mgr.set_state_param(b"Tc", operands[1]) + text_state_mgr.add_tm([0, -text_state_mgr.TL]) + tj_ops.append(text_state_mgr.text_state_params(operands[2])) + elif op in (b"Td", b"Tm", b"TD", b"T*"): + text_state_mgr.reset_trm() + if op == b"Tm": + text_state_mgr.reset_tm() + elif op == b"TD": + text_state_mgr.set_state_param(b"TL", -operands[1]) + elif op == b"T*": + operands = [0, -text_state_mgr.TL] + text_state_mgr.add_tm(operands) + elif op == b"Tf": + text_state_mgr.set_font(fonts[operands[0]], operands[1]) + else: # handle Tc, Tw, Tz, TL, and Ts operators + text_state_mgr.set_state_param(op, operands) + else: + logger_warning( + f"Unbalanced target operations, expected {end_target!r}.", + __name__, + ) + return bt_groups, tj_ops + + +def y_coordinate_groups( + bt_groups: list[BTGroup], debug_path: Optional[Path] = None +) -> dict[int, list[BTGroup]]: + """ + Group text operations by rendered y coordinate, i.e. the line number. + + Args: + bt_groups: list of dicts as returned by text_show_operations() + debug_path (Path, optional): Path to a directory for saving debug output. + + Returns: + Dict[int, List[BTGroup]]: dict of lists of text rendered by each BT operator + keyed by y coordinate + + """ + ty_groups = { + ty: sorted(grp, key=lambda x: x["tx"]) + for ty, grp in groupby( + bt_groups, key=lambda bt_grp: int(bt_grp["ty"] * bt_grp["flip_sort"]) + ) + } + # combine groups whose y coordinates differ by less than the effective font height + # (accounts for mixed fonts and other minor oddities) + last_ty = next(iter(ty_groups)) + last_txs = {int(_t["tx"]) for _t in ty_groups[last_ty] if _t["text"].strip()} + for ty in list(ty_groups)[1:]: + fsz = min(ty_groups[_y][0]["font_height"] for _y in (ty, last_ty)) + txs = {int(_t["tx"]) for _t in ty_groups[ty] if _t["text"].strip()} + # prevent merge if both groups are rendering in the same x position. + no_text_overlap = not (txs & last_txs) + offset_less_than_font_height = abs(ty - last_ty) < fsz + if no_text_overlap and offset_less_than_font_height: + ty_groups[last_ty] = sorted( + ty_groups.pop(ty) + ty_groups[last_ty], key=lambda x: x["tx"] + ) + last_txs |= txs + else: + last_ty = ty + last_txs = txs + if debug_path: # pragma: no cover + import json # noqa: PLC0415 + + debug_path.joinpath("bt_groups.json").write_text( + json.dumps(ty_groups, indent=2, default=str), "utf-8" + ) + return ty_groups + + +def text_show_operations( + ops: Iterator[tuple[list[Any], bytes]], + fonts: dict[str, Font], + strip_rotated: bool = True, + debug_path: Optional[Path] = None, +) -> list[BTGroup]: + """ + Extract text from BT/ET operator pairs. + + Args: + ops (Iterator[Tuple[List, bytes]]): iterator of operators in content stream + fonts (Dict[str, Font]): font dictionary + strip_rotated: Removes text if rotated w.r.t. to the page. Defaults to True. + debug_path (Path, optional): Path to a directory for saving debug output. + + Returns: + List[BTGroup]: list of dicts of text rendered by each BT operator + + """ + state_mgr = TextStateManager() # transformation stack manager + bt_groups: list[BTGroup] = [] # BT operator dict + tj_ops: list[TextStateParams] = [] # Tj/TJ operator data + for operands, op in ops: + if op in (b"BT", b"q"): + bts, tjs = recurs_to_target_op( + ops, state_mgr, b"ET" if op == b"BT" else b"Q", fonts, strip_rotated + ) + bt_groups.extend(bts) + tj_ops.extend(tjs) + elif op == b"Tf": + state_mgr.set_font(fonts[operands[0]], operands[1]) + else: # set Tc, Tw, Tz, TL, and Ts if required. ignores all other ops + state_mgr.set_state_param(op, operands) + + if any(tj.rotated for tj in tj_ops): + if strip_rotated: + logger_warning( + "Rotated text discovered. Output will be incomplete.", __name__ + ) + else: + logger_warning( + "Rotated text discovered. Layout will be degraded.", __name__ + ) + if not all(tj.font.interpretable for tj in tj_ops): + logger_warning( + "PDF contains an uninterpretable font. Output will be incomplete.", __name__ + ) + + # left align the data, i.e. decrement all tx values by min(tx) + min_x = min((x["tx"] for x in bt_groups), default=0.0) + bt_groups = [ + dict(ogrp, tx=ogrp["tx"] - min_x, displaced_tx=ogrp["displaced_tx"] - min_x) # type: ignore[misc] + for ogrp in sorted( + bt_groups, key=lambda x: (x["ty"] * x["flip_sort"], -x["tx"]), reverse=True + ) + ] + + if debug_path: # pragma: no cover + import json # noqa: PLC0415 + + debug_path.joinpath("bts.json").write_text( + json.dumps(bt_groups, indent=2, default=str), "utf-8" + ) + debug_path.joinpath("tjs.json").write_text( + json.dumps( + tj_ops, indent=2, default=lambda x: getattr(x, "to_dict", str)(x) + ), + "utf-8", + ) + return bt_groups + + +def fixed_char_width(bt_groups: list[BTGroup], scale_weight: float = 1.25) -> float: + """ + Calculate average character width weighted by the length of the rendered + text in each sample for conversion to fixed-width layout. + + Args: + bt_groups (List[BTGroup]): List of dicts of text rendered by each + BT operator + + Returns: + float: fixed character width + + """ + char_widths = [] + for _bt in bt_groups: + _len = len(_bt["text"]) * scale_weight + char_widths.append(((_bt["displaced_tx"] - _bt["tx"]) / _len, _len)) + return sum(_w * _l for _w, _l in char_widths) / sum(_l for _, _l in char_widths) + + +def fixed_width_page( + ty_groups: dict[int, list[BTGroup]], char_width: float, space_vertically: bool, font_height_weight: float +) -> str: + """ + Generate page text from text operations grouped by rendered y coordinate. + + Args: + ty_groups: dict of text show ops as returned by y_coordinate_groups() + char_width: fixed character width + space_vertically: include blank lines inferred from y distance + font height. + font_height_weight: multiplier for font height when calculating blank lines. + + Returns: + str: page text in a fixed width format that closely adheres to the rendered + layout in the source pdf. + + """ + lines: list[str] = [] + last_y_coord = 0 + table = str.maketrans(dict.fromkeys(range(14, 32), " ")) + for y_coord, line_data in ty_groups.items(): + if space_vertically and lines: + fh = line_data[0]["font_height"] + blank_lines = 0 if fh == 0 else ( + int(abs(y_coord - last_y_coord) / (fh * font_height_weight)) - 1 + ) + lines.extend([""] * blank_lines) + + line_parts = [] # It uses a list to construct the line, avoiding string concatenation. + current_len = 0 # Track the size with int instead of len(str) overhead. + last_disp = 0.0 + for bt_op in line_data: + tx = bt_op["tx"] + offset = int(tx // char_width) + needed_spaces = offset - current_len + if needed_spaces > 0 and ceil(last_disp) < int(tx): + padding = " " * needed_spaces + line_parts.append(padding) + current_len += needed_spaces + + raw_text = bt_op["text"] + text = raw_text.translate(table) + line_parts.append(text) + current_len += len(text) + last_disp = bt_op["displaced_tx"] + + full_line = "".join(line_parts).rstrip() + if full_line.strip() or (space_vertically and lines): + lines.append(full_line) + + last_y_coord = y_coord + + return "\n".join(lines) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_text_extraction/_layout_mode/_text_state_manager.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_text_extraction/_layout_mode/_text_state_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..03f1c139b74f4cfeb778b94454d8a6a7e501ddb3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_text_extraction/_layout_mode/_text_state_manager.py @@ -0,0 +1,221 @@ +"""manage the PDF transform stack during "layout" mode text extraction""" + +from collections import ChainMap, Counter +from collections import ChainMap as ChainMapType +from collections import Counter as CounterType +from collections.abc import MutableMapping +from typing import Any, Union + +from ..._font import Font +from ...errors import PdfReadError +from .. import mult +from ._text_state_params import TextStateParams + +TextStateManagerChainMapType = ChainMapType[Union[int, str], Union[float, bool]] +TextStateManagerDictType = MutableMapping[Union[int, str], Union[float, bool]] + + +class TextStateManager: + """ + Tracks the current text state including cm/tm/trm transformation matrices. + + Attributes: + transform_stack (ChainMap): ChainMap of cm/tm transformation matrices + q_queue (Counter[int]): Counter of q operators + q_depth (List[int]): list of q operator nesting levels + Tc (float): character spacing + Tw (float): word spacing + Tz (int): horizontal scaling + TL (float): leading + Ts (float): text rise + font (Font): font object + font_size (int | float): font size + + """ + + def __init__(self) -> None: + self.transform_stack: TextStateManagerChainMapType = ChainMap( + self.new_transform() + ) + self.q_queue: CounterType[int] = Counter() + self.q_depth = [0] + self.Tc: float = 0.0 + self.Tw: float = 0.0 + self.Tz: float = 100.0 + self.TL: float = 0.0 + self.Ts: float = 0.0 + self.font_stack: list[tuple[Union[Font, None], Union[int, float]]] = [] + self.font: Union[Font, None] = None + self.font_size: Union[int, float] = 0 + + def set_state_param(self, op: bytes, value: Union[float, list[Any]]) -> None: + """ + Set a text state parameter. Supports Tc, Tz, Tw, TL, and Ts operators. + + Args: + op: operator read from PDF stream as bytes. No action is taken + for unsupported operators (see supported operators above). + value (float | List[Any]): new parameter value. If a list, + value[0] is used. + + """ + if op not in [b"Tc", b"Tz", b"Tw", b"TL", b"Ts"]: + return + self.__setattr__(op.decode(), value[0] if isinstance(value, list) else value) + + def set_font(self, font: Font, size: float) -> None: + """ + Set the current font and font_size. + + Args: + font (Font): a layout mode Font + size (float): font size + + """ + self.font = font + self.font_size = size + + def text_state_params(self, value: Union[bytes, str] = "") -> TextStateParams: + """ + Create a TextStateParams instance to display a text string. Type[bytes] values + will be decoded implicitly. + + Args: + value (str | bytes): text to associate with the captured state. + + Raises: + PdfReadError: if font not set (no Tf operator in incoming pdf content stream) + + Returns: + TextStateParams: current text state parameters + + """ + if not isinstance(self.font, Font): + raise PdfReadError( + "font not set: is PDF missing a Tf operator?" + ) # pragma: no cover + if isinstance(value, bytes): + try: + if isinstance(self.font.encoding, str): + txt = value.decode(self.font.encoding, "surrogatepass") + else: + txt = "".join( + self.font.encoding[x] + if x in self.font.encoding + else bytes((x,)).decode() + for x in value + ) + except (UnicodeEncodeError, UnicodeDecodeError): + txt = value.decode("utf-8", "replace") + txt = "".join( + self.font.character_map.get(x, x) for x in txt + ) + else: + txt = value + return TextStateParams( + txt, + self.font, + self.font_size, + self.Tc, + self.Tw, + self.Tz, + self.TL, + self.Ts, + self.effective_transform, + ) + + @staticmethod + def raw_transform( + _a: float = 1.0, + _b: float = 0.0, + _c: float = 0.0, + _d: float = 1.0, + _e: float = 0.0, + _f: float = 0.0, + ) -> TextStateManagerDictType: + """Only a/b/c/d/e/f matrix params""" + return dict(zip(range(6), map(float, (_a, _b, _c, _d, _e, _f)))) + + @staticmethod + def new_transform( + _a: float = 1.0, + _b: float = 0.0, + _c: float = 0.0, + _d: float = 1.0, + _e: float = 0.0, + _f: float = 0.0, + is_text: bool = False, + is_render: bool = False, + ) -> TextStateManagerDictType: + """Standard a/b/c/d/e/f matrix params + 'is_text' and 'is_render' keys""" + result = TextStateManager.raw_transform(_a, _b, _c, _d, _e, _f) + result.update({"is_text": is_text, "is_render": is_render}) + return result + + def reset_tm(self) -> TextStateManagerChainMapType: + """Clear all transforms from chainmap having is_text==True or is_render==True""" + while ( + self.transform_stack.maps[0]["is_text"] + or self.transform_stack.maps[0]["is_render"] + ): + self.transform_stack = self.transform_stack.parents + return self.transform_stack + + def reset_trm(self) -> TextStateManagerChainMapType: + """Clear all transforms from chainmap having is_render==True""" + while self.transform_stack.maps[0]["is_render"]: + self.transform_stack = self.transform_stack.parents + return self.transform_stack + + def remove_q(self) -> TextStateManagerChainMapType: + """Rewind to stack prior state after closing a 'q' with internal 'cm' ops""" + self.font, self.font_size = self.font_stack.pop(-1) + self.transform_stack = self.reset_tm() + self.transform_stack.maps = self.transform_stack.maps[ + self.q_queue.pop(self.q_depth.pop(), 0) : + ] + return self.transform_stack + + def add_q(self) -> None: + """Add another level to q_queue""" + self.font_stack.append((self.font, self.font_size)) + self.q_depth.append(len(self.q_depth)) + + def add_cm(self, *args: Any) -> TextStateManagerChainMapType: + """Concatenate an additional transform matrix""" + self.transform_stack = self.reset_tm() + self.q_queue.update(self.q_depth[-1:]) + self.transform_stack = self.transform_stack.new_child(self.new_transform(*args)) + return self.transform_stack + + def _complete_matrix(self, operands: list[float]) -> list[float]: + """Adds a, b, c, and d to an "e/f only" operand set (e.g Td)""" + if len(operands) == 2: # this is a Td operator or equivalent + operands = [1.0, 0.0, 0.0, 1.0, *operands] + return operands + + def add_tm(self, operands: list[float]) -> TextStateManagerChainMapType: + """Append a text transform matrix""" + self.transform_stack = self.transform_stack.new_child( + self.new_transform( # type: ignore[misc] + *self._complete_matrix(operands), is_text=True # type: ignore[arg-type] + ) + ) + return self.transform_stack + + def add_trm(self, operands: list[float]) -> TextStateManagerChainMapType: + """Append a text rendering transform matrix""" + self.transform_stack = self.transform_stack.new_child( + self.new_transform( # type: ignore[misc] + *self._complete_matrix(operands), is_text=True, is_render=True # type: ignore[arg-type] + ) + ) + return self.transform_stack + + @property + def effective_transform(self) -> list[float]: + """Current effective transform accounting for cm, tm, and trm transforms""" + eff_transform = [*self.transform_stack.maps[0].values()] + for transform in self.transform_stack.maps[1:]: + eff_transform = mult(eff_transform, transform) # type: ignore[arg-type] # dict has int keys 0-5 + return eff_transform diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_text_extraction/_layout_mode/_text_state_params.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_text_extraction/_layout_mode/_text_state_params.py new file mode 100644 index 0000000000000000000000000000000000000000..5203f12733f4b97dcb025e9f0366c4ae8dd54b68 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_text_extraction/_layout_mode/_text_state_params.py @@ -0,0 +1,135 @@ +"""A dataclass that captures the CTM and Text State for a tj operation""" + +import math +from dataclasses import dataclass, field +from typing import Any, Union + +from ..._font import Font +from .. import mult, orient + + +@dataclass +class TextStateParams: + """ + Text state parameters and operator values for a single text value in a + TJ or Tj PDF operation. + + Attributes: + txt (str): the text to be rendered. + font (Font): font object + font_size (int | float): font size + Tc (float): character spacing. Defaults to 0.0. + Tw (float): word spacing. Defaults to 0.0. + Tz (float): horizontal scaling. Defaults to 100.0. + TL (float): leading, vertical displacement between text lines. Defaults to 0.0. + Ts (float): text rise. Used for super/subscripts. Defaults to 0.0. + transform (List[float]): effective transformation matrix. + tx (float): x cood of rendered text, i.e. self.transform[4] + ty (float): y cood of rendered text. May differ from self.transform[5] per self.Ts. + displaced_tx (float): x coord immediately following rendered text + space_tx (float): tx for a space character + font_height (float): effective font height accounting for CTM + flip_vertical (bool): True if y axis has been inverted (i.e. if self.transform[3] < 0.) + rotated (bool): True if the text orientation is rotated with respect to the page. + + """ + + txt: str + font: Font + font_size: Union[int, float] + Tc: float = 0.0 + Tw: float = 0.0 + Tz: float = 100.0 + TL: float = 0.0 + Ts: float = 0.0 + transform: list[float] = field( + default_factory=lambda: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0] + ) + tx: float = field(default=0.0, init=False) + ty: float = field(default=0.0, init=False) + displaced_tx: float = field(default=0.0, init=False) + space_tx: float = field(default=0.0, init=False) + font_height: float = field(default=0.0, init=False) + flip_vertical: bool = field(default=False, init=False) + rotated: bool = field(default=False, init=False) + + def __post_init__(self) -> None: + if orient(self.transform) in (90, 270): + self.transform = mult( + [1.0, -self.transform[1], -self.transform[2], 1.0, 0.0, 0.0], + self.transform, + ) + self.rotated = True + # self.transform[0] AND self.transform[3] < 0 indicates true rotation. + # If only self.transform[3] < 0, the y coords are simply inverted. + if orient(self.transform) == 180 and self.transform[0] < -1e-6: + self.transform = mult([-1.0, 0.0, 0.0, -1.0, 0.0, 0.0], self.transform) + self.rotated = True + self.displaced_tx = self.displaced_transform()[4] + self.tx = self.transform[4] + self.ty = self.render_transform()[5] + self.space_tx = round(self.word_tx(" "), 3) + if self.space_tx < 1e-6: + # if the " " char is assigned 0 width (e.g. for fine tuned spacing + # with TJ int operators a la crazyones.pdf), calculate space_tx as + # a td_offset of -1 * font.space_width where font.space_width is + # the space_width calculated in _font.py. + self.space_tx = round(self.word_tx("", -self.font.space_width), 3) + self.font_height = self.font_size * math.sqrt( + self.transform[1] ** 2 + self.transform[3] ** 2 + ) + # flip_vertical handles PDFs generated by Microsoft Word's "publish" command. + self.flip_vertical = self.transform[3] < -1e-6 # inverts y axis + + def font_size_matrix(self) -> list[float]: + """Font size matrix""" + return [ + self.font_size * (self.Tz / 100.0), + 0.0, + 0.0, + self.font_size, + 0.0, + self.Ts, + ] + + def displaced_transform(self) -> list[float]: + """Effective transform matrix after text has been rendered.""" + return mult(self.displacement_matrix(), self.transform) + + def render_transform(self) -> list[float]: + """Effective transform matrix accounting for font size, Tz, and Ts.""" + return mult(self.font_size_matrix(), self.transform) + + def displacement_matrix( + self, word: Union[str, None] = None, td_offset: float = 0.0 + ) -> list[float]: + """ + Text displacement matrix + + Args: + word (str, optional): Defaults to None in which case self.txt displacement is + returned. + td_offset (float, optional): translation applied by TD operator. Defaults to 0.0. + + """ + word = word if word is not None else self.txt + return [1.0, 0.0, 0.0, 1.0, self.word_tx(word, td_offset), 0.0] + + def word_tx(self, word: str, td_offset: float = 0.0) -> float: + """Horizontal text displacement for any word according this text state""" + width: float = 0.0 + for char in word: + if char == " ": + width += self.font.space_width + else: + width += self.font.text_width(char) + return ( + (self.font_size * ((width - td_offset) / 1000.0)) + + self.Tc + + word.count(" ") * self.Tw + ) * (self.Tz / 100.0) + + @staticmethod + def to_dict(inst: "TextStateParams") -> dict[str, Any]: + """Dataclass to dict for json.dumps serialization""" + return {k: getattr(inst, k) for k in inst.__dataclass_fields__ if k != "font"} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4834186fb7cdbc91af9ad664fdf6f5a3970e298d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_utils.py @@ -0,0 +1,646 @@ +# Copyright (c) 2006, Mathieu Fenniak +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * The name of the author may not be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +"""Utility functions for PDF library.""" +__author__ = "Mathieu Fenniak" +__author_email__ = "biziqe@mathieu.fenniak.net" + +import functools +import logging +import re +import sys +import warnings +from dataclasses import dataclass +from datetime import datetime, timezone +from io import DEFAULT_BUFFER_SIZE +from os import SEEK_CUR +from re import Pattern +from typing import ( + IO, + Any, + Optional, + Union, + overload, +) + +if sys.version_info[:2] >= (3, 10): + # Python 3.10+: https://www.python.org/dev/peps/pep-0484/ + from typing import TypeAlias +else: + from typing_extensions import TypeAlias + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + +from .errors import ( + STREAM_TRUNCATED_PREMATURELY, + DeprecationError, + PdfStreamError, +) + +TransformationMatrixType: TypeAlias = tuple[ + tuple[float, float, float], tuple[float, float, float], tuple[float, float, float] +] +CompressedTransformationMatrix: TypeAlias = tuple[ + float, float, float, float, float, float +] + +StreamType = IO[Any] +BinaryStreamType = IO[bytes] +StrByteType = Union[str, StreamType] + + +def parse_iso8824_date(text: Optional[str]) -> Optional[datetime]: + orgtext = text + if not text: + return None + if text[0].isdigit(): + text = "D:" + text + if text.endswith(("Z", "z")): + text += "0000" + text = text.replace("z", "+").replace("Z", "+").replace("'", "") + i = max(text.find("+"), text.find("-")) + if i > 0 and i != len(text) - 5: + text += "00" + for f in ( + "D:%Y", + "D:%Y%m", + "D:%Y%m%d", + "D:%Y%m%d%H", + "D:%Y%m%d%H%M", + "D:%Y%m%d%H%M%S", + "D:%Y%m%d%H%M%S%z", + ): + try: + d = datetime.strptime(text, f) # noqa: DTZ007 + except ValueError: + continue + else: + if text.endswith("+0000"): + d = d.replace(tzinfo=timezone.utc) + return d + raise ValueError(f"Can not convert date: {orgtext}") + + +def format_iso8824_date(dt: datetime) -> str: + """ + Convert a datetime object to PDF date string format. + + Converts datetime to the PDF date format D:YYYYMMDDHHmmSSOHH'mm + as specified in the PDF Reference. + + Args: + dt: A datetime object to convert. + + Returns: + A date string in PDF format. + """ + date_str = dt.strftime("D:%Y%m%d%H%M%S") + if dt.tzinfo is not None: + offset = dt.utcoffset() + assert offset is not None + total_seconds = int(offset.total_seconds()) + hours, remainder = divmod(abs(total_seconds), 3600) + minutes = remainder // 60 + sign = "+" if total_seconds >= 0 else "-" + date_str += f"{sign}{hours:02d}'{minutes:02d}'" + return date_str + + +def _get_max_pdf_version_header(header1: str, header2: str) -> str: + versions = ( + "%PDF-1.3", + "%PDF-1.4", + "%PDF-1.5", + "%PDF-1.6", + "%PDF-1.7", + "%PDF-2.0", + ) + pdf_header_indices = [] + if header1 in versions: + pdf_header_indices.append(versions.index(header1)) + if header2 in versions: + pdf_header_indices.append(versions.index(header2)) + if len(pdf_header_indices) == 0: + raise ValueError(f"Neither {header1!r} nor {header2!r} are proper headers") + return versions[max(pdf_header_indices)] + + +WHITESPACES = (b"\x00", b"\t", b"\n", b"\f", b"\r", b" ") +WHITESPACES_AS_BYTES = b"".join(WHITESPACES) +WHITESPACES_AS_REGEXP = b"[" + WHITESPACES_AS_BYTES + b"]" + + +def read_until_whitespace(stream: StreamType, maxchars: Optional[int] = None) -> bytes: + """ + Read non-whitespace characters and return them. + + Stops upon encountering whitespace or when maxchars is reached. + + Args: + stream: The data stream from which was read. + maxchars: The maximum number of bytes returned; by default unlimited. + + Returns: + The data which was read. + + """ + txt = b"" + while True: + tok = stream.read(1) + if tok.isspace() or not tok: + break + txt += tok + if len(txt) == maxchars: + break + return txt + + +def read_non_whitespace(stream: BinaryStreamType) -> bytes: + """ + Find and read the next non-whitespace character (ignores whitespace). + + Args: + stream: The data stream from which was read. + + Returns: + The data which was read. + + """ + tok = stream.read(1) + while tok in WHITESPACES: + tok = stream.read(1) + return tok + + +def skip_over_whitespace(stream: StreamType) -> bool: + """ + Similar to read_non_whitespace, but return a boolean if at least one + whitespace character was read. + + Args: + stream: The data stream from which was read. + + Returns: + True if one or more whitespace was skipped, otherwise return False. + + """ + tok = stream.read(1) + cnt = 0 + while tok in WHITESPACES: + cnt += 1 + tok = stream.read(1) + return cnt > 0 + + +def check_if_whitespace_only(value: bytes) -> bool: + """ + Check if the given value consists of whitespace characters only. + + Args: + value: The bytes to check. + + Returns: + True if the value only has whitespace characters, otherwise return False. + + """ + return all(b in WHITESPACES_AS_BYTES for b in value) + + +def skip_over_comment(stream: StreamType) -> None: + tok = stream.read(1) + stream.seek(-1, 1) + if tok == b"%": + while tok not in (b"\n", b"\r"): + tok = stream.read(1) + if tok == b"": + raise PdfStreamError("File ended unexpectedly.") + + +def read_until_regex(stream: StreamType, regex: Pattern[bytes]) -> bytes: + """ + Read until the regular expression pattern matched (ignore the match). + Treats EOF on the underlying stream as the end of the token to be matched. + + Args: + regex: re.Pattern + + Returns: + The read bytes. + + """ + parts: list[bytes] = [] + total_len = 0 + tail = b"" + chunk_size = 16 + while True: + tok = stream.read(chunk_size) + if not tok: + return b"".join(parts) + # Search overlap of previous tail + new chunk to catch + # multi-byte regex matches spanning chunk boundaries. + buf = tail + tok + m = regex.search(buf) + if m is not None: + overlap = len(tail) + actual_start = total_len - overlap + m.start() + stream.seek(actual_start - total_len - len(tok), 1) + parts.append(tok) + return b"".join(parts)[:actual_start] + parts.append(tok) + total_len += len(tok) + # Fixed overlap: 16 bytes is sufficient for the short + # delimiter patterns used in PDF parsing. + tail = tok[-16:] + if chunk_size < 8192: + chunk_size <<= 1 + return b"".join(parts) + + +def read_block_backwards(stream: BinaryStreamType, to_read: int) -> bytes: + """ + Given a stream at position X, read a block of size to_read ending at position X. + + This changes the stream's position to the beginning of where the block was + read. + + Args: + stream: + to_read: + + Returns: + The data which was read. + + """ + if stream.tell() < to_read: + raise PdfStreamError("Could not read malformed PDF file") + # Seek to the start of the block we want to read. + stream.seek(-to_read, SEEK_CUR) + read = stream.read(to_read) + # Seek to the start of the block we read after reading it. + stream.seek(-to_read, SEEK_CUR) + return read + + +def read_previous_line(stream: StreamType) -> bytes: + """ + Given a byte stream with current position X, return the previous line. + + All characters between the first CR/LF byte found before X + (or, the start of the file, if no such byte is found) and position X + After this call, the stream will be positioned one byte after the + first non-CRLF character found beyond the first CR/LF byte before X, + or, if no such byte is found, at the beginning of the stream. + + Args: + stream: StreamType: + + Returns: + The data which was read. + + """ + line_content = [] + found_crlf = False + if stream.tell() == 0: + raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY) + while True: + to_read = min(DEFAULT_BUFFER_SIZE, stream.tell()) + if to_read == 0: + break + # Read the block. After this, our stream will be one + # beyond the initial position. + block = read_block_backwards(stream, to_read) + idx = len(block) - 1 + if not found_crlf: + # We haven't found our first CR/LF yet. + # Read off characters until we hit one. + while idx >= 0 and block[idx] not in b"\r\n": + idx -= 1 + if idx >= 0: + found_crlf = True + if found_crlf: + # We found our first CR/LF already (on this block or + # a previous one). + # Our combined line is the remainder of the block + # plus any previously read blocks. + line_content.append(block[idx + 1 :]) + # Continue to read off any more CRLF characters. + while idx >= 0 and block[idx] in b"\r\n": + idx -= 1 + else: + # Didn't find CR/LF yet - add this block to our + # previously read blocks and continue. + line_content.append(block) + if idx >= 0: + # We found the next non-CRLF character. + # Set the stream position correctly, then break + stream.seek(idx + 1, SEEK_CUR) + break + # Join all the blocks in the line (which are in reverse order) + return b"".join(line_content[::-1]) + + +def matrix_multiply( + a: TransformationMatrixType, b: TransformationMatrixType +) -> TransformationMatrixType: + return tuple( # type: ignore[return-value] + tuple(sum(float(i) * float(j) for i, j in zip(row, col)) for col in zip(*b)) + for row in a + ) + + +def mark_location(stream: StreamType) -> None: + """Create text file showing current location in context.""" + # Mainly for debugging + radius = 5000 + stream.seek(-radius, 1) + with open("pypdf_pdfLocation.txt", "wb") as output_fh: + output_fh.write(stream.read(radius)) + output_fh.write(b"HERE") + output_fh.write(stream.read(radius)) + stream.seek(-radius, 1) + + +@overload +def ord_(b: str) -> int: + ... + + +@overload +def ord_(b: bytes) -> bytes: + ... + + +@overload +def ord_(b: int) -> int: + ... + + +def ord_(b: Union[int, str, bytes]) -> Union[int, bytes]: + if isinstance(b, str): + return ord(b) + return b + + +def deprecate(msg: str, stacklevel: int = 3) -> None: + warnings.warn(msg, DeprecationWarning, stacklevel=stacklevel) + + +def deprecation(msg: str) -> None: + raise DeprecationError(msg) + + +def deprecate_with_replacement(old_name: str, new_name: str, removed_in: str) -> None: + """Issue a warning that a feature will be removed, but has a replacement.""" + deprecate( + f"{old_name} is deprecated and will be removed in pypdf {removed_in}. Use {new_name} instead.", + 4, + ) + + +def deprecation_with_replacement(old_name: str, new_name: str, removed_in: str) -> None: + """Raise an exception that a feature was already removed, but has a replacement.""" + deprecation( + f"{old_name} is deprecated and was removed in pypdf {removed_in}. Use {new_name} instead." + ) + + +def deprecate_no_replacement(name: str, removed_in: str) -> None: + """Issue a warning that a feature will be removed without replacement.""" + deprecate(f"{name} is deprecated and will be removed in pypdf {removed_in}.", 4) + + +def deprecation_no_replacement(name: str, removed_in: str) -> None: + """Raise an exception that a feature was already removed without replacement.""" + deprecation(f"{name} is deprecated and was removed in pypdf {removed_in}.") + + +def logger_error(message: str, *, source: str, **values: Any) -> None: + """ + Use this instead of logger.error directly. + + That allows people to overwrite it more easily. + + See the docs on when to use which: + https://pypdf.readthedocs.io/en/latest/user/suppress-warnings.html + """ + logging.getLogger(source).error(message, values) + + +def logger_warning(msg: str, src: str) -> None: + """ + Use this instead of logger.warning directly. + + That allows people to overwrite it more easily. + + ## Exception, warnings.warn, logger_warning + - Exceptions should be used if the user should write code that deals with + an error case, e.g. the PDF being completely broken. + - warnings.warn should be used if the user needs to fix their code, e.g. + DeprecationWarnings + - logger_warning should be used if the user needs to know that an issue was + handled by pypdf, e.g. a non-compliant PDF being read in a way that + pypdf could apply a robustness fix to still read it. This applies mainly + to strict=False mode. + """ + logging.getLogger(src).warning(msg) + + +def rename_kwargs( + func_name: str, kwargs: dict[str, Any], aliases: dict[str, str], fail: bool = False +) -> None: + """ + Helper function to deprecate arguments. + + Args: + func_name: Name of the function to be deprecated + kwargs: + aliases: + fail: + + """ + for old_term, new_term in aliases.items(): + if old_term in kwargs: + if fail: + raise DeprecationError( + f"{old_term} is deprecated as an argument. Use {new_term} instead" + ) + if new_term in kwargs: + raise TypeError( + f"{func_name} received both {old_term} and {new_term} as " + f"an argument. {old_term} is deprecated. " + f"Use {new_term} instead." + ) + kwargs[new_term] = kwargs.pop(old_term) + warnings.warn( + message=( + f"{old_term} is deprecated as an argument. Use {new_term} instead" + ), + category=DeprecationWarning, + stacklevel=3, + ) + + +def _human_readable_bytes(bytes: int) -> str: + if bytes < 10**3: + return f"{bytes} Byte" + if bytes < 10**6: + return f"{bytes / 10**3:.1f} kB" + if bytes < 10**9: + return f"{bytes / 10**6:.1f} MB" + return f"{bytes / 10**9:.1f} GB" + + +# The following class has been copied from Django: +# https://github.com/django/django/blob/adae619426b6f50046b3daaa744db52989c9d6db/django/utils/functional.py#L51-L65 +# It received some modifications to comply with our own coding standards. +# +# Original license: +# +# --------------------------------------------------------------------------------- +# Copyright (c) Django Software Foundation and individual contributors. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# 1. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# 3. Neither the name of Django nor the names of its contributors may be used +# to endorse or promote products derived from this software without +# specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# --------------------------------------------------------------------------------- +class classproperty: # noqa: N801 + """ + Decorator that converts a method with a single cls argument into a property + that can be accessed directly from the class. + """ + + def __init__(self, method=None) -> None: # type: ignore # noqa: ANN001 + self.fget = method + + def __get__(self, instance, cls=None) -> Any: # type: ignore # noqa: ANN001 + return self.fget(cls) + + def getter(self, method) -> Self: # type: ignore # noqa: ANN001 + self.fget = method + return self + + +@dataclass +class File: + from .generic import IndirectObject # noqa: PLC0415 + + name: str = "" + """ + Filename as identified within the PDF file. + """ + data: bytes = b"" + """ + Data as bytes. + """ + indirect_reference: Optional[IndirectObject] = None + """ + Reference to the object storing the stream. + """ + + def __str__(self) -> str: + return f"{self.__class__.__name__}(name={self.name}, data: {_human_readable_bytes(len(self.data))})" + + def __repr__(self) -> str: + return self.__str__()[:-1] + f", hash: {hash(self.data)})" + + +@functools.total_ordering +class Version: + COMPONENT_PATTERN = re.compile(r"^(\d+)(.*)$") + + def __init__(self, version_str: str) -> None: + self.version_str = version_str + self.components = self._parse_version(version_str) + + def _parse_version(self, version_str: str) -> list[tuple[int, str]]: + components = version_str.split(".") + parsed_components = [] + for component in components: + match = Version.COMPONENT_PATTERN.match(component) + if not match: + parsed_components.append((0, component)) + continue + integer_prefix = match.group(1) + suffix = match.group(2) + if integer_prefix is None: + integer_prefix = 0 + parsed_components.append((int(integer_prefix), suffix)) + return parsed_components + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Version): + return False + return self.components == other.components + + def __hash__(self) -> int: + # Convert to tuple as lists cannot be hashed. + return hash((self.__class__, tuple(self.components))) + + def __lt__(self, other: Any) -> bool: + if not isinstance(other, Version): + raise ValueError(f"Version cannot be compared against {type(other)}") + + for self_component, other_component in zip(self.components, other.components): + self_value, self_suffix = self_component + other_value, other_suffix = other_component + + if self_value < other_value: + return True + if self_value > other_value: + return False + + if self_suffix < other_suffix: + return True + if self_suffix > other_suffix: + return False + + return len(self.components) < len(other.components) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_version.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..5655bca31483ee7bd4ff94e4837ce30a3a08ad5d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_version.py @@ -0,0 +1 @@ +__version__ = "6.11.0" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_writer.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_writer.py new file mode 100644 index 0000000000000000000000000000000000000000..42c672711c6e9229602b1b18aa7603da9fa84599 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_writer.py @@ -0,0 +1,3395 @@ +# Copyright (c) 2006, Mathieu Fenniak +# Copyright (c) 2007, Ashish Kulkarni +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * The name of the author may not be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +import decimal +import enum +import hashlib +import re +import struct +import sys +import uuid +from collections.abc import Iterable, Mapping +from io import BytesIO, FileIO, IOBase +from itertools import compress +from pathlib import Path +from re import Pattern +from types import TracebackType +from typing import ( + IO, + Any, + Callable, + Optional, + Union, + cast, +) + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + +from ._doc_common import DocumentInformation, PdfDocCommon +from ._encryption import EncryptAlgorithm, Encryption +from ._page import PageObject, Transformation +from ._page_labels import nums_clear_range, nums_insert, nums_next +from ._reader import PdfReader +from ._utils import ( + StrByteType, + StreamType, + _get_max_pdf_version_header, + deprecate_with_replacement, + deprecation_no_replacement, + logger_warning, +) +from .constants import AnnotationDictionaryAttributes as AA +from .constants import CatalogAttributes as CA +from .constants import ( + CatalogDictionary, + GoToActionArguments, + ImageType, + InteractiveFormDictEntries, + OutlineFontFlag, + PageLabelStyle, + PagesAttributes, + TypFitArguments, + UserAccessPermissions, +) +from .constants import Core as CO +from .constants import FieldDictionaryAttributes as FA +from .constants import PageAttributes as PG +from .constants import TrailerKeys as TK +from .errors import LimitReachedError, PdfReadError, PyPdfError +from .generic import ( + PAGE_FIT, + ArrayObject, + BooleanObject, + ByteStringObject, + ContentStream, + Destination, + DictionaryObject, + EmbeddedFile, + Fit, + FloatObject, + IndirectObject, + NameObject, + NullObject, + NumberObject, + PdfObject, + RectangleObject, + ReferenceLink, + StreamObject, + TextStringObject, + TreeObject, + ViewerPreferences, + create_string_object, + extract_links, + hex_to_rgb, + is_null_or_none, +) +from .generic._appearance_stream import TextStreamAppearance +from .pagerange import PageRange, PageRangeSpec +from .types import ( + AnnotationSubtype, + BorderArrayType, + LayoutType, + OutlineItemType, + OutlineType, + PagemodeType, +) +from .xmp import XmpInformation + +ALL_DOCUMENT_PERMISSIONS = UserAccessPermissions.all() + + +class ObjectDeletionFlag(enum.IntFlag): + NONE = 0 + TEXT = enum.auto() + LINKS = enum.auto() + ATTACHMENTS = enum.auto() + OBJECTS_3D = enum.auto() + ALL_ANNOTATIONS = enum.auto() + XOBJECT_IMAGES = enum.auto() + INLINE_IMAGES = enum.auto() + DRAWING_IMAGES = enum.auto() + IMAGES = XOBJECT_IMAGES | INLINE_IMAGES | DRAWING_IMAGES + + +def _rolling_checksum(stream: BytesIO, blocksize: int = 65536) -> str: + hash = hashlib.md5(usedforsecurity=False) + for block in iter(lambda: stream.read(blocksize), b""): + hash.update(block) + return hash.hexdigest() + + +class PdfWriter(PdfDocCommon): + """ + Write a PDF file out, given pages produced by another class or through + cloning a PDF file during initialization. + + Typically data is added from a :class:`PdfReader`. + + Args: + clone_from: identical to fileobj (for compatibility) + + incremental: If true, loads the document and set the PdfWriter in incremental mode. + + When writing incrementally, the original document is written first and new/modified + content is appended. To be used for signed document/forms to keep signature valid. + + full: If true, loads all the objects (always full if incremental = True). + This parameter may allow loading large PDFs. + + strict: If true, pypdf will raise an exception if a PDF does not follow the specification. + If false, pypdf will try to be forgiving and do something reasonable, but it will log + a warning message. It is a best-effort approach. + + """ + + def __init__( + self, + fileobj: Union[None, PdfReader, StrByteType, Path] = "", + clone_from: Union[None, PdfReader, StrByteType, Path] = None, + incremental: bool = False, + full: bool = False, + strict: bool = False, + *, + incremental_clone_object_count_limit: Optional[int] = 500_000, + incremental_clone_object_id_limit: Optional[int] = 1_000_000, + ) -> None: + self.strict = strict + """ + If true, pypdf will raise an exception if a PDF does not follow the specification. + If false, pypdf will try to be forgiving and do something reasonable, but it will log + a warning message. It is a best-effort approach. + """ + + self.incremental = incremental or full + """ + Returns if the PdfWriter object has been started in incremental mode. + """ + + self._objects: list[Optional[PdfObject]] = [] + """ + The indirect objects in the PDF. + For the incremental case, it will be filled with None + in clone_reader_document_root. + """ + + self._original_hash: list[int] = [] + """ + List of hashes after import; used to identify changes. + """ + + self._idnum_hash: dict[bytes, tuple[IndirectObject, list[IndirectObject]]] = {} + """ + Maps hash values of indirect objects to the list of IndirectObjects. + This is used for compression. + """ + + self._id_translated: dict[int, dict[int, int]] = {} + """List of already translated IDs. + dict[id(pdf)][(idnum, generation)] + """ + + self._info_obj: Optional[PdfObject] + """The PDF files's document information dictionary, + defined by Info in the PDF file's trailer dictionary.""" + + self._ID: Union[ArrayObject, None] = None + """The PDF file identifier, + defined by the ID in the PDF file's trailer dictionary.""" + + self._unresolved_links: list[tuple[ReferenceLink, ReferenceLink]] = [] + "Tracks links in pages added to the writer for resolving later." + self._merged_in_pages: dict[Optional[IndirectObject], Optional[IndirectObject]] = {} + "Tracks pages added to the writer and what page they turned into." + + # Security parameters. + self._incremental_clone_object_count_limit = ( + incremental_clone_object_count_limit + if isinstance(incremental_clone_object_count_limit, int) + else sys.maxsize + ) + self._incremental_clone_object_id_limit = ( + incremental_clone_object_id_limit if isinstance(incremental_clone_object_id_limit, int) else sys.maxsize + ) + + if self.incremental: + if isinstance(fileobj, (str, Path)): + with open(fileobj, "rb") as f: + fileobj = BytesIO(f.read(-1)) + if isinstance(fileobj, BytesIO): + fileobj = PdfReader(fileobj) + if not isinstance(fileobj, PdfReader): + raise PyPdfError("Invalid type for incremental mode") + self._reader = fileobj # prev content is in _reader.stream + self._header = fileobj.pdf_header.encode() + self._readonly = True # TODO: to be analysed + else: + self._header = b"%PDF-1.3" + self._info_obj = self._add_object( + DictionaryObject( + {NameObject("/Producer"): create_string_object("pypdf")} + ) + ) + + def _get_clone_from( + fileobj: Union[None, PdfReader, str, Path, IO[Any], BytesIO], + clone_from: Union[None, PdfReader, str, Path, IO[Any], BytesIO], + ) -> Union[None, PdfReader, str, Path, IO[Any], BytesIO]: + if isinstance(fileobj, (str, Path, IO, BytesIO)) and ( + fileobj == "" or clone_from is not None + ): + return clone_from + cloning = True + if isinstance(fileobj, (str, Path)) and ( + not Path(str(fileobj)).exists() + or Path(str(fileobj)).stat().st_size == 0 + ): + cloning = False + if isinstance(fileobj, (IOBase, BytesIO)): + t = fileobj.tell() + if fileobj.seek(0, 2) == 0: + cloning = False + fileobj.seek(t, 0) + if cloning: + clone_from = fileobj + return clone_from + + clone_from = _get_clone_from(fileobj, clone_from) + # To prevent overwriting + self.temp_fileobj = fileobj + self.fileobj = "" + self._with_as_usage = False + self._cloned = False + # The root of our page tree node + pages = DictionaryObject( + { + NameObject(PagesAttributes.TYPE): NameObject("/Pages"), + NameObject(PagesAttributes.COUNT): NumberObject(0), + NameObject(PagesAttributes.KIDS): ArrayObject(), + } + ) + self.flattened_pages = [] + self._encryption: Optional[Encryption] = None + self._encrypt_entry: Optional[DictionaryObject] = None + + if clone_from is not None: + if not isinstance(clone_from, PdfReader): + clone_from = PdfReader(clone_from) + self.clone_document_from_reader(clone_from) + self._cloned = True + else: + self._pages = self._add_object(pages) + self._root_object = DictionaryObject( + { + NameObject(PagesAttributes.TYPE): NameObject(CO.CATALOG), + NameObject(CO.PAGES): self._pages, + } + ) + self._add_object(self._root_object) + if full and not incremental: + self.incremental = False + if isinstance(self._ID, list): + if isinstance(self._ID[0], TextStringObject): + self._ID[0] = ByteStringObject(self._ID[0].get_original_bytes()) + if isinstance(self._ID[1], TextStringObject): + self._ID[1] = ByteStringObject(self._ID[1].get_original_bytes()) + + # for commonality + @property + def is_encrypted(self) -> bool: + """ + Read-only boolean property showing whether this PDF file is encrypted. + + Note that this property, if true, will remain true even after the + :meth:`decrypt()` method is called. + """ + return False + + @property + def root_object(self) -> DictionaryObject: + """ + Provide direct access to PDF Structure. + + Note: + Recommended only for read access. + + """ + return self._root_object + + @property + def _info(self) -> Optional[DictionaryObject]: + """ + Provide access to "/Info". Standardized with PdfReader. + + Returns: + /Info Dictionary; None if the entry does not exist + + """ + return ( + None + if self._info_obj is None + else cast(DictionaryObject, self._info_obj.get_object()) + ) + + @_info.setter + def _info(self, value: Optional[Union[IndirectObject, DictionaryObject]]) -> None: + if value is None: + try: + self._objects[self._info_obj.indirect_reference.idnum - 1] = None # type: ignore + except (KeyError, AttributeError): + pass + self._info_obj = None + else: + if self._info_obj is None: + self._info_obj = self._add_object(DictionaryObject()) + obj = cast(DictionaryObject, self._info_obj.get_object()) + obj.clear() + obj.update(cast(DictionaryObject, value.get_object())) + + @property + def xmp_metadata(self) -> Optional[XmpInformation]: + """XMP (Extensible Metadata Platform) data.""" + return cast(XmpInformation, self.root_object.xmp_metadata) + + @xmp_metadata.setter + def xmp_metadata(self, value: Union[XmpInformation, bytes, None]) -> None: + """XMP (Extensible Metadata Platform) data.""" + if value is None: + if "/Metadata" in self.root_object: + del self.root_object["/Metadata"] + return + + metadata = self.root_object.get("/Metadata", None) + if not isinstance(metadata, IndirectObject): + if metadata is not None: + del self.root_object["/Metadata"] + metadata_stream = StreamObject() + stream_reference = self._add_object(metadata_stream) + self.root_object[NameObject("/Metadata")] = stream_reference + else: + metadata_stream = cast(StreamObject, metadata.get_object()) + + if isinstance(value, XmpInformation): + bytes_data = value.stream.get_data() + else: + bytes_data = value + metadata_stream.set_data(bytes_data) + + @property + def with_as_usage(self) -> bool: + deprecation_no_replacement("with_as_usage", "5.0") + return self._with_as_usage + + @with_as_usage.setter + def with_as_usage(self, value: bool) -> None: + deprecation_no_replacement("with_as_usage", "5.0") + self._with_as_usage = value + + def __enter__(self) -> Self: + """Store how writer is initialized by 'with'.""" + c: bool = self._cloned + t = self.temp_fileobj + self.__init__() # type: ignore + self._cloned = c + self._with_as_usage = True + self.fileobj = t # type: ignore + return self + + def __exit__( + self, + exc_type: Optional[type[BaseException]], + exc: Optional[BaseException], + traceback: Optional[TracebackType], + ) -> None: + """Write data to the fileobj.""" + if self.fileobj and not self._cloned: + self.write(self.fileobj) + + @property + def pdf_header(self) -> str: + """ + Read/Write property of the PDF header that is written. + + This should be something like ``'%PDF-1.5'``. It is recommended to set + the lowest version that supports all features which are used within the + PDF file. + + Note: `pdf_header` returns a string but accepts bytes or str for writing + """ + return self._header.decode() + + @pdf_header.setter + def pdf_header(self, new_header: Union[str, bytes]) -> None: + if isinstance(new_header, str): + new_header = new_header.encode() + self._header = new_header + + def _add_object(self, obj: PdfObject) -> IndirectObject: + if ( + getattr(obj, "indirect_reference", None) is not None + and obj.indirect_reference.pdf == self # type: ignore + ): + return obj.indirect_reference # type: ignore + # check for /Contents in Pages (/Contents in annotations are strings) + if isinstance(obj, DictionaryObject) and isinstance( + obj.get(PG.CONTENTS, None), (ArrayObject, DictionaryObject) + ): + obj[NameObject(PG.CONTENTS)] = self._add_object(obj[PG.CONTENTS]) + self._objects.append(obj) + obj.indirect_reference = IndirectObject(len(self._objects), 0, self) + return obj.indirect_reference + + def get_object( + self, + indirect_reference: Union[int, IndirectObject], + ) -> PdfObject: + if isinstance(indirect_reference, int): + obj = self._objects[indirect_reference - 1] + elif indirect_reference.pdf != self: + raise ValueError("PDF must be self") + else: + obj = self._objects[indirect_reference.idnum - 1] + if obj is None: + raise PdfReadError(f"Object {indirect_reference!r} not found!") + return obj + + def _replace_object( + self, + indirect_reference: Union[int, IndirectObject], + obj: PdfObject, + ) -> PdfObject: + if isinstance(indirect_reference, IndirectObject): + if indirect_reference.pdf != self: + raise ValueError("PDF must be self") + indirect_reference = indirect_reference.idnum + gen = self._objects[indirect_reference - 1].indirect_reference.generation # type: ignore + if ( + getattr(obj, "indirect_reference", None) is not None + and obj.indirect_reference.pdf != self # type: ignore + ): + obj = obj.clone(self) + self._objects[indirect_reference - 1] = obj + obj.indirect_reference = IndirectObject(indirect_reference, gen, self) + + assert isinstance(obj, PdfObject), "mypy" + return obj + + def _add_page( + self, + page: PageObject, + index: int, + excluded_keys: Iterable[str] = (), + ) -> PageObject: + if not isinstance(page, PageObject) or page.get(PagesAttributes.TYPE, None) != CO.PAGE: + raise ValueError("Invalid page object") + assert self.flattened_pages is not None, "for mypy" + page_org = page + excluded_keys = list(excluded_keys) + excluded_keys += [PagesAttributes.PARENT, "/StructParents"] + # Acrobat does not accept two indirect references pointing on the same + # page; therefore in order to add multiple copies of the same + # page, we need to create a new dictionary for the page, however the + # objects below (including content) are not duplicated: + try: # delete an already existing page + del self._id_translated[id(page_org.indirect_reference.pdf)][ # type: ignore + page_org.indirect_reference.idnum # type: ignore + ] + except Exception: + pass + + page = cast( + "PageObject", page_org.clone(self, False, excluded_keys).get_object() + ) + if page_org.pdf is not None: + other = page_org.pdf.pdf_header + self.pdf_header = _get_max_pdf_version_header(self.pdf_header, other) + + node, idx = self._get_page_in_node(index) + page[NameObject(PagesAttributes.PARENT)] = node.indirect_reference + + if idx >= 0: + cast(ArrayObject, node[PagesAttributes.KIDS]).insert(idx, page.indirect_reference) + self.flattened_pages.insert(index, page) + else: + cast(ArrayObject, node[PagesAttributes.KIDS]).append(page.indirect_reference) + self.flattened_pages.append(page) + recurse = 0 + while not is_null_or_none(node): + node = cast(DictionaryObject, node.get_object()) + node[NameObject(PagesAttributes.COUNT)] = NumberObject(cast(int, node[PagesAttributes.COUNT]) + 1) + node = node.get(PagesAttributes.PARENT, None) # type: ignore[assignment] # TODO: Fix. + recurse += 1 + if recurse > 1000: + raise PyPdfError("Too many recursive calls!") + + if page_org.pdf is not None: + # the page may contain links to other pages, and those other + # pages may or may not already be added. we store the + # information we need, so that we can resolve the references + # later. + self._unresolved_links.extend(extract_links(page, page_org)) + self._merged_in_pages[page_org.indirect_reference] = page.indirect_reference + + return page + + def set_need_appearances_writer(self, state: bool = True) -> None: + """ + Sets the "NeedAppearances" flag in the PDF writer. + + The "NeedAppearances" flag indicates whether the appearance dictionary + for form fields should be automatically generated by the PDF viewer or + if the embedded appearance should be used. + + Args: + state: The actual value of the NeedAppearances flag. + + Returns: + None + + """ + # See §12.7.2 and §7.7.2 for more information: + # https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf + try: + # get the AcroForm tree + if CatalogDictionary.ACRO_FORM not in self._root_object: + self._root_object[ + NameObject(CatalogDictionary.ACRO_FORM) + ] = self._add_object(DictionaryObject()) + + need_appearances = NameObject(InteractiveFormDictEntries.NeedAppearances) + cast(DictionaryObject, self._root_object[CatalogDictionary.ACRO_FORM])[ + need_appearances + ] = BooleanObject(state) + except Exception as exc: # pragma: no cover + logger_warning( + f"set_need_appearances_writer({state}) catch : {exc}", __name__ + ) + + def create_viewer_preferences(self) -> ViewerPreferences: + o = ViewerPreferences() + self._root_object[ + NameObject(CatalogDictionary.VIEWER_PREFERENCES) + ] = self._add_object(o) + return o + + def add_page( + self, + page: PageObject, + excluded_keys: Iterable[str] = (), + ) -> PageObject: + """ + Add a page to this PDF file. + + Recommended for advanced usage including the adequate excluded_keys. + + The page is usually acquired from a :class:`PdfReader` + instance. + + Args: + page: The page to add to the document. Should be + an instance of :class:`PageObject` + excluded_keys: + + Returns: + The added PageObject. + + """ + assert self.flattened_pages is not None, "mypy" + return self._add_page(page, len(self.flattened_pages), excluded_keys) + + def insert_page( + self, + page: PageObject, + index: int = 0, + excluded_keys: Iterable[str] = (), + ) -> PageObject: + """ + Insert a page in this PDF file. The page is usually acquired from a + :class:`PdfReader` instance. + + Args: + page: The page to add to the document. + index: Position at which the page will be inserted. + excluded_keys: + + Returns: + The added PageObject. + + """ + assert self.flattened_pages is not None, "mypy" + if index < 0: + index += len(self.flattened_pages) + if index < 0: + raise ValueError("Invalid index value") + if index >= len(self.flattened_pages): + return self.add_page(page, excluded_keys) + return self._add_page(page, index, excluded_keys) + + def _get_page_number_by_indirect( + self, indirect_reference: Union[None, int, NullObject, IndirectObject] + ) -> Optional[int]: + """ + Generate _page_id2num. + + Args: + indirect_reference: + + Returns: + The page number or None + + """ + # To provide same function as in PdfReader + if is_null_or_none(indirect_reference): + return None + assert indirect_reference is not None, "mypy" + if isinstance(indirect_reference, int): + indirect_reference = IndirectObject(indirect_reference, 0, self) + obj = indirect_reference.get_object() + if isinstance(obj, PageObject): + return obj.page_number + return None + + def add_blank_page( + self, width: Optional[float] = None, height: Optional[float] = None + ) -> PageObject: + """ + Append a blank page to this PDF file and return it. + + If no page size is specified, use the size of the last page. + + Args: + width: The width of the new page expressed in default user + space units. + height: The height of the new page expressed in default + user space units. + + Returns: + The newly appended page. + + Raises: + PageSizeNotDefinedError: if width and height are not defined + and previous page does not exist. + + """ + page = PageObject.create_blank_page(self, width, height) + return self.add_page(page) + + def insert_blank_page( + self, + width: Optional[Union[float, decimal.Decimal]] = None, + height: Optional[Union[float, decimal.Decimal]] = None, + index: int = 0, + ) -> PageObject: + """ + Insert a blank page to this PDF file and return it. + + If no page size is specified for a dimension, use the size of the last page. + + Args: + width: The width of the new page in default user space units. + height: The height of the new page in default user space units. + index: Position to add the page. + + Returns: + The newly inserted page. + + Raises: + PageSizeNotDefinedError: if width and height are not defined + and previous page does not exist. + IndexError: Index is outside of [-self.get_num_pages(), self.get_num_pages()] + """ + num_pages = self.get_num_pages() + if abs(index) <= num_pages: + # Use the chosen index, but do not exceed the available pages + fixed_index = min(index, num_pages - 1) + mediabox = self.pages[fixed_index].mediabox + if width is None or width <= 0: + width = mediabox.width + if height is None or height <= 0: + height = mediabox.height + else: + raise IndexError(f"Index should be in range [-{num_pages}, {num_pages}]") + + page = PageObject.create_blank_page(self, width, height) + self.insert_page(page, index) + return page + + @property + def open_destination( + self, + ) -> Union[None, Destination, TextStringObject, ByteStringObject]: + return super().open_destination + + @open_destination.setter + def open_destination(self, dest: Union[None, str, Destination, PageObject]) -> None: + if dest is None: + try: + del self._root_object["/OpenAction"] + except KeyError: + pass + elif isinstance(dest, str): + self._root_object[NameObject("/OpenAction")] = TextStringObject(dest) + elif isinstance(dest, Destination): + self._root_object[NameObject("/OpenAction")] = dest.dest_array + elif isinstance(dest, PageObject): + self._root_object[NameObject("/OpenAction")] = Destination( + "Opening", + dest.indirect_reference + if dest.indirect_reference is not None + else NullObject(), + PAGE_FIT, + ).dest_array + + def add_js(self, javascript: str) -> None: + """ + Add JavaScript which will launch upon opening this PDF. + + Args: + javascript: Your JavaScript. + + Example: + This will launch the print window when the PDF is opened. + + >>> from pypdf import PdfWriter + >>> output = PdfWriter() + >>> output.add_js("this.print({bUI:true,bSilent:false,bShrinkToFit:true});") + + """ + # Names / JavaScript preferred to be able to add multiple scripts + if "/Names" not in self._root_object: + self._root_object[NameObject(CA.NAMES)] = DictionaryObject() + names = cast(DictionaryObject, self._root_object[CA.NAMES]) + if "/JavaScript" not in names: + names[NameObject("/JavaScript")] = DictionaryObject( + {NameObject("/Names"): ArrayObject()} + ) + js_list = cast( + ArrayObject, cast(DictionaryObject, names["/JavaScript"])["/Names"] + ) + # We need a name for parameterized JavaScript in the PDF file, + # but it can be anything. + js_list.append(create_string_object(str(uuid.uuid4()))) + + js = DictionaryObject( + { + NameObject(PagesAttributes.TYPE): NameObject("/Action"), + NameObject("/S"): NameObject("/JavaScript"), + NameObject("/JS"): TextStringObject(f"{javascript}"), + } + ) + js_list.append(self._add_object(js)) + + def add_attachment(self, filename: str, data: Union[str, bytes]) -> "EmbeddedFile": + """ + Embed a file inside the PDF. + + Reference: + https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf + Section 7.11.3 + + Args: + filename: The filename to display. + data: The data in the file. + + Returns: + EmbeddedFile instance for the newly created embedded file. + + """ + return EmbeddedFile._create_new(self, filename, data) + + def append_pages_from_reader( + self, + reader: PdfReader, + after_page_append: Optional[Callable[[PageObject], None]] = None, + ) -> None: + """ + Copy pages from reader to writer. Includes an optional callback + parameter which is invoked after pages are appended to the writer. + + ``append`` should be preferred. + + Args: + reader: a PdfReader object from which to copy page + annotations to this writer object. The writer's annots + will then be updated. + after_page_append: + Callback function that is invoked after each page is appended to + the writer. Signature includes a reference to the appended page + (delegates to append_pages_from_reader). The single parameter of + the callback is a reference to the page just appended to the + document. + + """ + reader_num_pages = len(reader.pages) + # Copy pages from reader to writer + for reader_page_number in range(reader_num_pages): + reader_page = reader.pages[reader_page_number] + writer_page = self.add_page(reader_page) + # Trigger callback, pass writer page as parameter + if callable(after_page_append): + after_page_append(writer_page) + + def _merge_content_stream_to_page( + self, + page: PageObject, + new_content_data: bytes, + ) -> None: + """ + Combines existing content stream(s) with new content (as bytes). + + Args: + page: The page to which the new content data will be added. + new_content_data: A binary-encoded new content stream, for + instance the commands to draw an XObject. + """ + # First resolve the existing page content. This always is an IndirectObject: + # PDF Explained by John Whitington + # https://www.oreilly.com/library/view/pdf-explained/9781449321581/ch04.html + if NameObject("/Contents") in page: + existing_content_ref = page[NameObject("/Contents")] + existing_content = existing_content_ref.get_object() + + if isinstance(existing_content, ArrayObject): + # Create a new StreamObject for the new_content_data + new_stream_obj = StreamObject() + new_stream_obj.set_data(new_content_data) + existing_content.append(self._add_object(new_stream_obj)) + page[NameObject("/Contents")] = self._add_object(existing_content) + if isinstance(existing_content, StreamObject): + # Merge new content to existing StreamObject + merged_data = existing_content.get_data() + b"\n" + new_content_data + new_stream = StreamObject() + new_stream.set_data(merged_data) + page[NameObject("/Contents")] = self._add_object(new_stream) + else: + # If no existing content, then we have an empty page. + # Create a new StreamObject in a new /Contents entry. + new_stream = StreamObject() + new_stream.set_data(new_content_data) + page[NameObject("/Contents")] = self._add_object(new_stream) + + def _add_apstream_object( + self, + page: PageObject, + appearance_stream_obj: StreamObject, + object_name: str, + x_offset: float, + y_offset: float, + ) -> None: + """ + Adds an appearance stream to the page content in the form of + an XObject. + + Args: + page: The page to which to add the appearance stream. + appearance_stream_obj: The appearance stream. + object_name: The name of the appearance stream. + x_offset: The horizontal offset for the appearance stream. + y_offset: The vertical offset for the appearance stream. + """ + # Prepare XObject resource dictionary on the page. This currently + # only deals with font resources, but can easily be adapted to also + # include other resources. + pg_res = cast(DictionaryObject, page[PG.RESOURCES]) + if "/Resources" in appearance_stream_obj: + ap_stream_res = cast(DictionaryObject, appearance_stream_obj["/Resources"]) + ap_stream_font_dict = cast(DictionaryObject, ap_stream_res.get("/Font", DictionaryObject())) + if "/Font" not in pg_res: + font_dict_ref = self._add_object(DictionaryObject()) + pg_res[NameObject("/Font")] = font_dict_ref + pg_font_res = cast(DictionaryObject, pg_res["/Font"].get_object()) + # Merge fonts from the appearance stream into the page's font resources + for font_name, font_res in ap_stream_font_dict.items(): + if font_name not in pg_font_res: + font_res_ref = self._add_object(font_res) + pg_font_res[font_name] = font_res_ref + # Always add the resolved stream object to the writer to get a new IndirectObject. + # This ensures we have a valid IndirectObject managed by *this* writer. + xobject_ref = self._add_object(appearance_stream_obj) + xobject_name = NameObject(f"/Fm_{object_name}")._sanitize() + if "/XObject" not in pg_res: + pg_res[NameObject("/XObject")] = DictionaryObject() + pg_xo_res = cast(DictionaryObject, pg_res["/XObject"]) + if xobject_name not in pg_xo_res: + pg_xo_res[xobject_name] = xobject_ref + else: + logger_warning( + f"XObject {xobject_name!r} already added to page resources. This might be an issue.", + __name__ + ) + xobject_cm = Transformation().translate(x_offset, y_offset) + xobject_drawing_commands = f"q\n{xobject_cm._to_cm()}\n{xobject_name} Do\nQ".encode() + self._merge_content_stream_to_page(page, xobject_drawing_commands) + + FFBITS_NUL = FA.FfBits(0) + + def update_page_form_field_values( + self, + page: Union[PageObject, list[PageObject], None], + fields: Mapping[str, Union[str, list[str], tuple[str, str, float]]], + flags: FA.FfBits = FFBITS_NUL, + auto_regenerate: Optional[bool] = True, + flatten: bool = False, + ) -> None: + """ + Update the form field values for a given page from a fields dictionary. + + Copy field texts and values from fields to page. + If the field links to a parent object, add the information to the parent. + + Args: + page: `PageObject` - references **PDF writer's page** where the + annotations and field data will be updated. + `List[Pageobject]` - provides list of pages to be processed. + `None` - all pages. + fields: a Python dictionary of: + + * field names (/T) as keys and text values (/V) as value + * field names (/T) as keys and list of text values (/V) for multiple choice list + * field names (/T) as keys and tuple of: + * text values (/V) + * font id (e.g. /F1, the font id must exist) + * font size (0 for autosize) + + flags: A set of flags from :class:`~pypdf.constants.FieldDictionaryAttributes.FfBits`. + + auto_regenerate: Set/unset the need_appearances flag; + the flag is unchanged if auto_regenerate is None. + + flatten: Whether or not to flatten the annotation. If True, this adds the annotation's + appearance stream to the page contents. Note that this option does not remove the + annotation itself. + + """ + if CatalogDictionary.ACRO_FORM not in self._root_object: + raise PyPdfError("No /AcroForm dictionary in PDF of PdfWriter Object") + acro_form = cast(DictionaryObject, self._root_object[CatalogDictionary.ACRO_FORM]) + if InteractiveFormDictEntries.Fields not in acro_form: + raise PyPdfError("No /Fields dictionary in PDF of PdfWriter Object") + if isinstance(auto_regenerate, bool): + self.set_need_appearances_writer(auto_regenerate) + # Iterate through pages, update field values + if page is None: + page = list(self.pages) + if isinstance(page, list): + for p in page: + if PG.ANNOTS in p: # just to prevent warnings + self.update_page_form_field_values(p, fields, flags, None, flatten=flatten) + return + if PG.ANNOTS not in page: + logger_warning("No fields to update on this page", __name__) + return + appearance_stream_obj: Optional[StreamObject] = None + + for annotation in page[PG.ANNOTS]: # type: ignore + annotation = cast(DictionaryObject, annotation.get_object()) + if annotation.get("/Subtype", "") != "/Widget": + continue + if "/FT" in annotation and "/T" in annotation: + parent_annotation = annotation + else: + parent_annotation = annotation.get( + PG.PARENT, DictionaryObject() + ).get_object() + + for field, value in fields.items(): + rectangle = cast(RectangleObject, annotation[AA.Rect]) + if not ( + self._get_qualified_field_name(parent_annotation) == field + or parent_annotation.get("/T", None) == field + ): + continue + if ( + parent_annotation.get("/FT", None) == "/Ch" + and "/I" in parent_annotation + ): + del parent_annotation["/I"] + if flags: + annotation[NameObject(FA.Ff)] = NumberObject(flags) + # Set the field value + if not (value is None and flatten): # Only change values if given by user and not flattening. + if isinstance(value, list): + lst = ArrayObject(TextStringObject(v) for v in value) + parent_annotation[NameObject(FA.V)] = lst + elif isinstance(value, tuple): + annotation[NameObject(FA.V)] = TextStringObject( + value[0], + ) + else: + parent_annotation[NameObject(FA.V)] = TextStringObject(value) + # Get or create the field's appearance stream object + if parent_annotation.get(FA.FT) == "/Btn": + # Checkbox button (no /FT found in Radio widgets); + # We can find the associated appearance stream object + # within the annotation. + v = NameObject(value) + ap = cast(DictionaryObject, annotation[NameObject(AA.AP)]) + normal_ap = cast(DictionaryObject, ap["/N"]) + if v not in normal_ap: + v = NameObject("/Off") + appearance_stream_obj = normal_ap.get(v) + # Other cases will be updated through the for loop + annotation[NameObject(AA.AS)] = v + annotation[NameObject(FA.V)] = v + elif ( + parent_annotation.get(FA.FT) == "/Tx" + or parent_annotation.get(FA.FT) == "/Ch" + ): + # Textbox; we need to generate the appearance stream object + if isinstance(value, tuple): + appearance_stream_obj = TextStreamAppearance.from_text_annotation( + acro_form, parent_annotation, annotation, value[1], value[2] + ) + else: + appearance_stream_obj = TextStreamAppearance.from_text_annotation( + acro_form, parent_annotation, annotation + ) + # Add the appearance stream object + if AA.AP not in annotation: + annotation[NameObject(AA.AP)] = DictionaryObject( + {NameObject("/N"): self._add_object(appearance_stream_obj)} + ) + elif "/N" not in (ap:= cast(DictionaryObject, annotation[AA.AP])): + cast(DictionaryObject, annotation[NameObject(AA.AP)])[ + NameObject("/N") + ] = self._add_object(appearance_stream_obj) + else: # [/AP][/N] exists + n = annotation[AA.AP]["/N"].indirect_reference.idnum # type: ignore + self._objects[n - 1] = appearance_stream_obj + appearance_stream_obj.indirect_reference = IndirectObject(n, 0, self) + elif ( + annotation.get(FA.FT) == "/Sig" + ): # deprecated # not implemented yet + logger_warning("Signature forms not implemented yet", __name__) + if flatten and appearance_stream_obj is not None: + self._add_apstream_object(page, appearance_stream_obj, field, rectangle[0], rectangle[1]) + + def reattach_fields( + self, page: Optional[PageObject] = None + ) -> list[DictionaryObject]: + """ + Parse annotations within the page looking for orphan fields and + reattach then into the Fields Structure. + + Args: + page: page to analyze. + If none is provided, all pages will be analyzed. + + Returns: + list of reattached fields. + + """ + lst = [] + if page is None: + for p in self.pages: + lst += self.reattach_fields(p) + return lst + + try: + af = cast(DictionaryObject, self._root_object[CatalogDictionary.ACRO_FORM]) + except KeyError: + af = DictionaryObject() + self._root_object[NameObject(CatalogDictionary.ACRO_FORM)] = af + try: + fields = cast(ArrayObject, af[InteractiveFormDictEntries.Fields]) + except KeyError: + fields = ArrayObject() + af[NameObject(InteractiveFormDictEntries.Fields)] = fields + + if "/Annots" not in page: + return lst + annotations = cast(ArrayObject, page["/Annots"]) + for idx, annotation in enumerate(annotations): + is_indirect = isinstance(annotation, IndirectObject) + annotation = cast(DictionaryObject, annotation.get_object()) + if annotation.get("/Subtype", "") == "/Widget" and "/FT" in annotation: + if ( + "indirect_reference" in annotation.__dict__ + and annotation.indirect_reference in fields + ): + continue + if not is_indirect: + annotations[idx] = self._add_object(annotation) + fields.append(annotation.indirect_reference) + lst.append(annotation) + return lst + + def _collect_incremental_clone_object_ids(self, reader: PdfReader) -> list[int]: + object_ids: set[int] = set() + for xref_entry in reader.xref.values(): + object_ids.update(filter(None, xref_entry)) + object_ids.update(filter(None, reader.xref_objStm)) + + object_count = len(object_ids) + if object_count > self._incremental_clone_object_count_limit: + raise LimitReachedError( + f"Incremental clone object count {object_count} exceeds " + f"maximum allowed count {self._incremental_clone_object_count_limit}." + ) + + max_object_id = max(object_ids, default=0) + if max_object_id > self._incremental_clone_object_id_limit: + raise LimitReachedError( + f"Incremental clone object ID {max_object_id} exceeds " + f"maximum allowed ID {self._incremental_clone_object_id_limit}." + ) + + return sorted(object_ids) + + def clone_reader_document_root(self, reader: PdfReader) -> None: + """ + Copy the reader document root to the writer and all sub-elements, + including pages, threads, outlines,... For partial insertion, ``append`` + should be considered. + + Args: + reader: PdfReader from which the document root should be copied. + + """ + self._info_obj = None + if self.incremental: + object_ids = self._collect_incremental_clone_object_ids(reader) + self._objects = [None] * (object_ids[-1] if object_ids else 0) + for object_id in object_ids: + reader_object = reader.get_object(object_id) + if reader_object is not None: + self._objects[object_id - 1] = reader_object.replicate(self) + else: + self._objects.clear() + self._root_object = reader.root_object.clone(self) + self._pages = self._root_object.raw_get("/Pages") + + if len(self._objects) > cast(int, reader.trailer["/Size"]): + if self.strict: + raise PdfReadError( + f"Object count {len(self._objects)} exceeds defined trailer size {reader.trailer['/Size']}" + ) + logger_warning( + f"Object count {len(self._objects)} exceeds defined trailer size {reader.trailer['/Size']}", + __name__ + ) + + # must be done here before rewriting + if self.incremental: + self._original_hash = [ + (obj.hash_bin() if obj is not None else 0) for obj in self._objects + ] + + try: + self._flatten() + except IndexError: + raise PdfReadError("Got index error while flattening.") + + assert self.flattened_pages is not None + for p in self.flattened_pages: + self._replace_object(cast(IndirectObject, p.indirect_reference).idnum, p) + if not self.incremental: + p[NameObject("/Parent")] = self._pages + if not self.incremental: + cast(DictionaryObject, self._pages.get_object())[ + NameObject("/Kids") + ] = ArrayObject([p.indirect_reference for p in self.flattened_pages]) + + def clone_document_from_reader( + self, + reader: PdfReader, + after_page_append: Optional[Callable[[PageObject], None]] = None, + ) -> None: + """ + Create a copy (clone) of a document from a PDF file reader cloning + section '/Root' and '/Info' and '/ID' of the pdf. + + Args: + reader: PDF file reader instance from which the clone + should be created. + after_page_append: + Callback function that is invoked after each page is appended to + the writer. Signature includes a reference to the appended page + (delegates to append_pages_from_reader). The single parameter of + the callback is a reference to the page just appended to the + document. + + """ + self.clone_reader_document_root(reader) + inf = reader._info + if self.incremental: + if inf is not None: + self._info_obj = cast( + IndirectObject, inf.clone(self).indirect_reference + ) + assert isinstance(self._info, DictionaryObject), "for mypy" + self._original_hash[ + self._info_obj.indirect_reference.idnum - 1 + ] = self._info.hash_bin() + elif inf is not None: + self._info_obj = self._add_object( + DictionaryObject(cast(DictionaryObject, inf.get_object())) + ) + # else: _info_obj = None done in clone_reader_document_root() + + try: + self._ID = cast(ArrayObject, reader._ID).clone(self) + except AttributeError: + pass + + if callable(after_page_append): + for page in cast( + ArrayObject, cast(DictionaryObject, self._pages.get_object())["/Kids"] + ): + after_page_append(page.get_object()) + + def _compute_document_identifier(self) -> ByteStringObject: + stream = BytesIO() + self._write_pdf_structure(stream) + stream.seek(0) + return ByteStringObject(_rolling_checksum(stream).encode("utf8")) + + def generate_file_identifiers(self) -> None: + """ + Generate an identifier for the PDF that will be written. + + The only point of this is ensuring uniqueness. Reproducibility is not + required. + When a file is first written, both identifiers shall be set to the same value. + If both identifiers match when a file reference is resolved, it is very + likely that the correct and unchanged file has been found. If only the first + identifier matches, a different version of the correct file has been found. + see §14.4 "File Identifiers". + """ + if self._ID: + id1 = self._ID[0] + id2 = self._compute_document_identifier() + else: + id1 = self._compute_document_identifier() + id2 = id1 + self._ID = ArrayObject((id1, id2)) + + def encrypt( + self, + user_password: str, + owner_password: Optional[str] = None, + use_128bit: bool = True, + permissions_flag: UserAccessPermissions = ALL_DOCUMENT_PERMISSIONS, + *, + algorithm: Optional[str] = None, + ) -> None: + """ + Encrypt this PDF file with the PDF Standard encryption handler. + + Args: + user_password: The password which allows for opening + and reading the PDF file with the restrictions provided. + owner_password: The password which allows for + opening the PDF files without any restrictions. By default, + the owner password is the same as the user password. + use_128bit: flag as to whether to use 128bit + encryption. When false, 40bit encryption will be used. + By default, this flag is on. + permissions_flag: permissions as described in + Table 3.20 of the PDF 1.7 specification. A bit value of 1 means + the permission is granted. + Hence an integer value of -1 will set all flags. + Bit position 3 is for printing, 4 is for modifying content, + 5 and 6 control annotations, 9 for form fields, + 10 for extraction of text and graphics. + algorithm: encrypt algorithm. Values may be one of "RC4-40", "RC4-128", + "AES-128", "AES-256-R5", "AES-256". If it is valid, + `use_128bit` will be ignored. + + """ + if owner_password is None: + owner_password = user_password + + if algorithm is not None: + try: + alg = getattr(EncryptAlgorithm, algorithm.replace("-", "_")) + except AttributeError: + raise ValueError(f"Algorithm '{algorithm}' NOT supported") + else: + alg = EncryptAlgorithm.RC4_128 + if not use_128bit: + alg = EncryptAlgorithm.RC4_40 + self.generate_file_identifiers() + assert self._ID + self._encryption = Encryption.make(alg, permissions_flag, self._ID[0]) + # in case call `encrypt` again + entry = self._encryption.write_entry(user_password, owner_password) + if self._encrypt_entry: + # replace old encrypt_entry + assert self._encrypt_entry.indirect_reference is not None + entry.indirect_reference = self._encrypt_entry.indirect_reference + self._objects[entry.indirect_reference.idnum - 1] = entry + else: + self._add_object(entry) + self._encrypt_entry = entry + + def _resolve_links(self) -> None: + """Patch up links that were added to the document earlier, to + make sure they still point to the same pages. + """ + for (new_link, old_link) in self._unresolved_links: + old_page = old_link.find_referenced_page() + if not old_page: + continue + new_page = self._merged_in_pages.get(old_page) + if new_page is None: + continue + new_link.patch_reference(self, new_page) + + def write_stream(self, stream: StreamType) -> None: + if hasattr(stream, "mode") and "b" not in stream.mode: + logger_warning( + f"File <{stream.name}> to write to is not in binary mode. " + "It may not be written to correctly.", + __name__, + ) + self._resolve_links() + + if self.incremental: + self._reader.stream.seek(0) + stream.write(self._reader.stream.read(-1)) + if len(self.list_objects_in_increment()) > 0: + self._write_increment(stream) # writes objs, xref stream and startxref + else: + object_positions, free_objects = self._write_pdf_structure(stream) + xref_location = self._write_xref_table( + stream, object_positions, free_objects + ) + self._write_trailer(stream, xref_location) + + def write(self, stream: Union[Path, StrByteType]) -> tuple[bool, IO[Any]]: + """ + Write the collection of pages added to this object out as a PDF file. + + Args: + stream: An object to write the file to. The object can support + the write method and the tell method, similar to a file object, or + be a file path, just like the fileobj, just named it stream to keep + existing workflow. + + Returns: + A tuple (bool, IO). + + """ + my_file = False + + if stream == "": + raise ValueError(f"Output({stream=}) is empty.") + + if isinstance(stream, (str, Path)): + stream = FileIO(stream, "wb") + my_file = True + + self.write_stream(stream) + + if my_file: + stream.close() + else: + stream.flush() + + return my_file, stream + + def list_objects_in_increment(self) -> list[IndirectObject]: + """ + For analysis or debugging. + Provides the list of new or modified objects that will be written + in the increment. + Deleted objects will not be freed but will become orphans. + + Returns: + List of new or modified IndirectObjects + + """ + original_hash_count = len(self._original_hash) + return [ + cast(IndirectObject, obj).indirect_reference + for i, obj in enumerate(self._objects) + if ( + obj is not None + and ( + i >= original_hash_count + or obj.hash_bin() != self._original_hash[i] + ) + ) + ] + + def _write_increment(self, stream: StreamType) -> None: + object_positions = {} + object_blocks = [] + current_start = -1 + current_stop = -2 + original_hash_count = len(self._original_hash) + for i, obj in enumerate(self._objects): + if obj is not None and ( + i >= original_hash_count + or obj.hash_bin() != self._original_hash[i] + ): + idnum = i + 1 + assert isinstance(obj, PdfObject), "mypy" + # first write new/modified object + object_positions[idnum] = stream.tell() + stream.write(f"{idnum} 0 obj\n".encode()) + """ encryption is not operational + if self._encryption and obj != self._encrypt_entry: + obj = self._encryption.encrypt_object(obj, idnum, 0) + """ + obj.write_to_stream(stream) + stream.write(b"\nendobj\n") + + # prepare xref + if idnum != current_stop: + if current_start > 0: + object_blocks.append( + [current_start, current_stop - current_start] + ) + current_start = idnum + current_stop = idnum + 1 + assert current_start > 0, "for pytest only" + object_blocks.append([current_start, current_stop - current_start]) + # write incremented xref + xref_location = stream.tell() + xr_id = len(self._objects) + 1 + stream.write(f"{xr_id} 0 obj".encode()) + init_data = { + NameObject("/Type"): NameObject("/XRef"), + NameObject("/Size"): NumberObject(xr_id + 1), + NameObject("/Root"): self.root_object.indirect_reference, + NameObject("/Filter"): NameObject("/FlateDecode"), + NameObject("/Index"): ArrayObject( + [NumberObject(_it) for _su in object_blocks for _it in _su] + ), + NameObject("/W"): ArrayObject( + [NumberObject(1), NumberObject(4), NumberObject(1)] + ), + "__streamdata__": b"", + } + if self._info is not None and ( + self._info.indirect_reference.idnum - 1 # type: ignore + >= len(self._original_hash) + or cast(IndirectObject, self._info).hash_bin() # kept for future + != self._original_hash[ + self._info.indirect_reference.idnum - 1 # type: ignore + ] + ): + init_data[NameObject(TK.INFO)] = self._info.indirect_reference + init_data[NameObject(TK.PREV)] = NumberObject(self._reader._startxref) + if self._ID: + init_data[NameObject(TK.ID)] = self._ID + xr = StreamObject.initialize_from_dictionary(init_data) + xr.set_data( + b"".join( + [struct.pack(b">BIB", 1, _pos, 0) for _pos in object_positions.values()] + ) + ) + xr.write_to_stream(stream) + stream.write(f"\nendobj\nstartxref\n{xref_location}\n%%EOF\n".encode()) # eof + + def _write_pdf_structure(self, stream: StreamType) -> tuple[list[int], list[int]]: + object_positions = [] + free_objects = [] + stream.write(self.pdf_header.encode() + b"\n") + stream.write(b"%\xE2\xE3\xCF\xD3\n") + + for idnum, obj in enumerate(self._objects, start=1): + if obj is not None: + object_positions.append(stream.tell()) + stream.write(f"{idnum} 0 obj\n".encode()) + if self._encryption and obj != self._encrypt_entry: + obj = self._encryption.encrypt_object(obj, idnum, 0) + obj.write_to_stream(stream) + stream.write(b"\nendobj\n") + else: + object_positions.append(-1) + free_objects.append(idnum) + free_objects.append(0) # add 0 to loop in accordance with specification + return object_positions, free_objects + + def _write_xref_table( + self, stream: StreamType, object_positions: list[int], free_objects: list[int] + ) -> int: + xref_location = stream.tell() + stream.write(b"xref\n") + stream.write(f"0 {len(self._objects) + 1}\n".encode()) + stream.write(f"{free_objects[0]:0>10} {65535:0>5} f \n".encode()) + free_idx = 1 + for offset in object_positions: + if offset > 0: + stream.write(f"{offset:0>10} {0:0>5} n \n".encode()) + else: + stream.write(f"{free_objects[free_idx]:0>10} {1:0>5} f \n".encode()) + free_idx += 1 + return xref_location + + def _write_trailer(self, stream: StreamType, xref_location: int) -> None: + """ + Write the PDF trailer to the stream. + + To quote the PDF specification: + [The] trailer [gives] the location of the cross-reference table and + of certain special objects within the body of the file. + """ + stream.write(b"trailer\n") + trailer = DictionaryObject( + { + NameObject(TK.SIZE): NumberObject(len(self._objects) + 1), + NameObject(TK.ROOT): self.root_object.indirect_reference, + } + ) + if self._info is not None: + trailer[NameObject(TK.INFO)] = self._info.indirect_reference + if self._ID is not None: + trailer[NameObject(TK.ID)] = self._ID + if self._encrypt_entry: + trailer[NameObject(TK.ENCRYPT)] = self._encrypt_entry.indirect_reference + trailer.write_to_stream(stream) + stream.write(f"\nstartxref\n{xref_location}\n%%EOF\n".encode()) # eof + + @property + def metadata(self) -> Optional[DocumentInformation]: + """ + Retrieve/set the PDF file's document information dictionary, if it exists. + + Args: + value: dict with the entries to be set. if None : remove the /Info entry from the pdf. + + Note that some PDF files use (XMP) metadata streams instead of document + information dictionaries, and these metadata streams will not be + accessed by this function, but by :meth:`~xmp_metadata`. + + """ + return super().metadata + + @metadata.setter + def metadata( + self, + value: Optional[Union[DocumentInformation, DictionaryObject, dict[Any, Any]]], + ) -> None: + if value is None: + self._info = None + else: + if self._info is not None: + self._info.clear() + + self.add_metadata(value) + + def add_metadata(self, infos: dict[str, Any]) -> None: + """ + Add custom metadata to the output. + + Args: + infos: a Python dictionary where each key is a field + and each value is your new metadata. + + """ + args = {} + if isinstance(infos, PdfObject): + infos = cast(DictionaryObject, infos.get_object()) + for key, value in list(infos.items()): + if isinstance(value, PdfObject): + value = value.get_object() + args[NameObject(key)] = create_string_object(str(value)) + if self._info is None: + self._info = DictionaryObject() + self._info.update(args) + + _UNSET = object() + + def compress_identical_objects( + self, + remove_identicals: Any = _UNSET, + remove_orphans: Any = _UNSET, + *, + remove_duplicates: bool = True, + remove_unreferenced: bool = True, + ) -> None: + """ + Parse the PDF file and merge objects that have the same hash. + This will make objects common to multiple pages. + Recommended to be used just before writing output. + + Args: + remove_identicals: Deprecated. + remove_orphans: Deprecated. + remove_duplicates: Remove duplicate objects. + remove_unreferenced: Remove unreferenced objects. + + """ + if remove_identicals != self._UNSET: + deprecate_with_replacement("remove_identicals", "remove_duplicates", "7.0.0") + assert isinstance(remove_identicals, bool) + remove_duplicates = remove_identicals + if remove_orphans != self._UNSET: + deprecate_with_replacement("remove_orphans", "remove_unreferenced", "7.0.0") + assert isinstance(remove_orphans, bool) + remove_unreferenced = remove_orphans + + def replace_in_obj( + obj: PdfObject, crossref: dict[IndirectObject, IndirectObject] + ) -> None: + if isinstance(obj, DictionaryObject): + key_val = obj.items() + elif isinstance(obj, ArrayObject): + key_val = enumerate(obj) # type: ignore + else: + return + assert isinstance(obj, (DictionaryObject, ArrayObject)) + for k, v in key_val: + if isinstance(v, IndirectObject): + unreferenced[v.idnum - 1] = False + if v in crossref: + obj[k] = crossref[v] + else: + """The filtering on DictionaryObject and ArrayObject only + will be performed within replace_in_obj""" + replace_in_obj(v, crossref) + + # _idnum_hash: dict[hash] = (1st_ind_obj, [2nd_ind_obj,...]) + self._idnum_hash = {} + unreferenced = [True] * len(self._objects) + # look for similar objects + for idx, obj in enumerate(self._objects): + if is_null_or_none(obj): + continue + assert obj is not None, "mypy" # mypy: TypeGuard of `is_null_or_none` does not help here. + assert isinstance(obj.indirect_reference, IndirectObject) + h = obj.hash_value() + if remove_duplicates and h in self._idnum_hash: + self._idnum_hash[h][1].append(obj.indirect_reference) + self._objects[idx] = None + else: + self._idnum_hash[h] = (obj.indirect_reference, []) + + # generate the dict converting others to 1st + cnv = {v[0]: v[1] for v in self._idnum_hash.values() if len(v[1]) > 0} + cnv_rev: dict[IndirectObject, IndirectObject] = {} + for k, v in cnv.items(): + cnv_rev.update(zip(v, (k,) * len(v))) + + # replace reference to merged objects + for obj in self._objects: + if isinstance(obj, (DictionaryObject, ArrayObject)): + replace_in_obj(obj, cnv_rev) + + if remove_unreferenced: + unreferenced[self.root_object.indirect_reference.idnum - 1] = False # type: ignore + + if not is_null_or_none(self._info): + unreferenced[self._info.indirect_reference.idnum - 1] = False # type: ignore + + try: + unreferenced[self._ID.indirect_reference.idnum - 1] = False # type: ignore + except AttributeError: + pass + + for i in compress(range(len(self._objects)), unreferenced): + self._objects[i] = None + + def get_reference(self, obj: PdfObject) -> IndirectObject: + idnum = self._objects.index(obj) + 1 + ref = IndirectObject(idnum, 0, self) + assert ref.get_object() == obj + return ref + + def get_outline_root(self) -> TreeObject: + if CO.OUTLINES in self._root_object: + # Entries in the catalog dictionary + outline = cast(TreeObject, self._root_object[CO.OUTLINES]) + if not isinstance(outline, TreeObject): + t = TreeObject(outline) + self._replace_object(outline.indirect_reference.idnum, t) + outline = t + idnum = self._objects.index(outline) + 1 + outline_ref = IndirectObject(idnum, 0, self) + assert outline_ref.get_object() == outline + else: + outline = TreeObject() + outline.update({}) + outline_ref = self._add_object(outline) + self._root_object[NameObject(CO.OUTLINES)] = outline_ref + + return outline + + def get_threads_root(self) -> ArrayObject: + """ + The list of threads. + + See §12.4.3 of the PDF 1.7 or PDF 2.0 specification. + + Returns: + An array (possibly empty) of Dictionaries with an ``/F`` key, + and optionally information about the thread in ``/I`` or ``/Metadata`` keys. + + """ + if CO.THREADS in self._root_object: + # Entries in the catalog dictionary + threads = cast(ArrayObject, self._root_object[CO.THREADS]) + else: + threads = ArrayObject() + self._root_object[NameObject(CO.THREADS)] = threads + return threads + + @property + def threads(self) -> ArrayObject: + """ + Read-only property for the list of threads. + + See §12.4.3 of the PDF 1.7 or PDF 2.0 specification. + + Each element is a dictionary with an ``/F`` key, and optionally + information about the thread in ``/I`` or ``/Metadata`` keys. + """ + return self.get_threads_root() + + def add_outline_item_destination( + self, + page_destination: Union[IndirectObject, PageObject, TreeObject], + parent: Union[None, TreeObject, IndirectObject] = None, + before: Union[None, TreeObject, IndirectObject] = None, + is_open: bool = True, + ) -> IndirectObject: + page_destination = cast(PageObject, page_destination.get_object()) + if isinstance(page_destination, PageObject): + return self.add_outline_item_destination( + Destination( + f"page #{page_destination.page_number}", + cast(IndirectObject, page_destination.indirect_reference), + Fit.fit(), + ) + ) + + if parent is None: + parent = self.get_outline_root() + + page_destination[NameObject("/%is_open%")] = BooleanObject(is_open) + parent = cast(TreeObject, parent.get_object()) + page_destination_ref = self._add_object(page_destination) + if before is not None: + before = before.indirect_reference + parent.insert_child( + page_destination_ref, + before, + self, + page_destination.inc_parent_counter_outline + if is_open + else (lambda x, y: 0), # noqa: ARG005 + ) + if "/Count" not in page_destination: + page_destination[NameObject("/Count")] = NumberObject(0) + + return page_destination_ref + + def add_outline_item_dict( + self, + outline_item: OutlineItemType, + parent: Union[None, TreeObject, IndirectObject] = None, + before: Union[None, TreeObject, IndirectObject] = None, + is_open: bool = True, + ) -> IndirectObject: + outline_item_object = TreeObject() + outline_item_object.update(outline_item) + + """code currently unreachable + if "/A" in outline_item: + action = DictionaryObject() + a_dict = cast(DictionaryObject, outline_item["/A"]) + for k, v in list(a_dict.items()): + action[NameObject(str(k))] = v + action_ref = self._add_object(action) + outline_item_object[NameObject("/A")] = action_ref + """ + return self.add_outline_item_destination( + outline_item_object, parent, before, is_open + ) + + def add_outline_item( + self, + title: str, + page_number: Union[None, PageObject, IndirectObject, int], + parent: Union[None, TreeObject, IndirectObject] = None, + before: Union[None, TreeObject, IndirectObject] = None, + color: Optional[Union[tuple[float, float, float], str]] = None, + bold: bool = False, + italic: bool = False, + fit: Fit = PAGE_FIT, + is_open: bool = True, + ) -> IndirectObject: + """ + Add an outline item (commonly referred to as a "Bookmark") to the PDF file. + + Args: + title: Title to use for this outline item. + page_number: Page number this outline item will point to. + parent: A reference to a parent outline item to create nested + outline items. + before: + color: Color of the outline item's font as a red, green, blue tuple + from 0.0 to 1.0 or as a Hex String (#RRGGBB) + bold: Outline item font is bold + italic: Outline item font is italic + fit: The fit of the destination page. + + Returns: + The added outline item as an indirect object. + + """ + page_ref: Union[None, NullObject, IndirectObject, NumberObject] + if isinstance(italic, Fit): # it means that we are on the old params + if fit is not None and page_number is None: + page_number = fit + return self.add_outline_item( + title, page_number, parent, None, before, color, bold, italic, is_open=is_open + ) + if page_number is None: + action_ref = None + else: + if isinstance(page_number, IndirectObject): + page_ref = page_number + elif isinstance(page_number, PageObject): + page_ref = page_number.indirect_reference + elif isinstance(page_number, int): + try: + page_ref = self.pages[page_number].indirect_reference + except IndexError: + page_ref = NumberObject(page_number) + if page_ref is None: + logger_warning( + f"can not find reference of page {page_number}", + __name__, + ) + page_ref = NullObject() + dest = Destination( + NameObject("/" + title + " outline item"), + page_ref, + fit, + ) + + action_ref = self._add_object( + DictionaryObject( + { + NameObject(GoToActionArguments.D): dest.dest_array, + NameObject(GoToActionArguments.S): NameObject("/GoTo"), + } + ) + ) + outline_item = self._add_object( + _create_outline_item(action_ref, title, color, italic, bold) + ) + + if parent is None: + parent = self.get_outline_root() + return self.add_outline_item_destination(outline_item, parent, before, is_open) + + def add_outline(self) -> None: + raise NotImplementedError( + "This method is not yet implemented. Use :meth:`add_outline_item` instead." + ) + + def add_named_destination_array( + self, title: TextStringObject, destination: Union[IndirectObject, ArrayObject] + ) -> None: + named_dest = self.get_named_dest_root() + i = 0 + while i < len(named_dest): + if title < named_dest[i]: + named_dest.insert(i, destination) + named_dest.insert(i, TextStringObject(title)) + return + i += 2 + named_dest.extend([TextStringObject(title), destination]) + return + + def add_named_destination_object( + self, + page_destination: PdfObject, + ) -> IndirectObject: + page_destination_ref = self._add_object(page_destination.dest_array) # type: ignore + self.add_named_destination_array( + cast("TextStringObject", page_destination["/Title"]), page_destination_ref # type: ignore + ) + + return page_destination_ref + + def add_named_destination( + self, + title: str, + page_number: int, + ) -> IndirectObject: + page_ref = self.get_object(self._pages)[PagesAttributes.KIDS][page_number] # type: ignore + dest = DictionaryObject() + dest.update( + { + NameObject(GoToActionArguments.D): ArrayObject( + [page_ref, NameObject(TypFitArguments.FIT_H), NumberObject(826)] + ), + NameObject(GoToActionArguments.S): NameObject("/GoTo"), + } + ) + + dest_ref = self._add_object(dest) + if not isinstance(title, TextStringObject): + title = TextStringObject(str(title)) + + self.add_named_destination_array(title, dest_ref) + return dest_ref + + def remove_links(self) -> None: + """Remove links and annotations from this output.""" + for page in self.pages: + self.remove_objects_from_page(page, ObjectDeletionFlag.ALL_ANNOTATIONS) + + def remove_annotations( + self, subtypes: Optional[Union[AnnotationSubtype, Iterable[AnnotationSubtype]]] + ) -> None: + """ + Remove annotations by annotation subtype. + + Args: + subtypes: subtype or list of subtypes to be removed. + Examples are: "/Link", "/FileAttachment", "/Sound", + "/Movie", "/Screen", ... + If you want to remove all annotations, use subtypes=None. + + """ + for page in self.pages: + self._remove_annots_from_page(page, subtypes) + + def _remove_annots_from_page( + self, + page: Union[IndirectObject, PageObject, DictionaryObject], + subtypes: Optional[Iterable[str]], + ) -> None: + page = cast(DictionaryObject, page.get_object()) + if PG.ANNOTS in page: + i = 0 + while i < len(cast(ArrayObject, page[PG.ANNOTS])): + an = cast(ArrayObject, page[PG.ANNOTS])[i] + obj = cast(DictionaryObject, an.get_object()) + if subtypes is None or cast(str, obj["/Subtype"]) in subtypes: + if isinstance(an, IndirectObject): + self._objects[an.idnum - 1] = NullObject() # to reduce PDF size + del page[PG.ANNOTS][i] # type:ignore + else: + i += 1 + + def remove_objects_from_page( + self, + page: Union[PageObject, DictionaryObject], + to_delete: Union[ObjectDeletionFlag, Iterable[ObjectDeletionFlag]], + text_filters: Optional[dict[str, Any]] = None + ) -> None: + """ + Remove objects specified by ``to_delete`` from the given page. + + Args: + page: Page object to clean up. + to_delete: Objects to be deleted; can be a ``ObjectDeletionFlag`` + or a list of ObjectDeletionFlag + text_filters: Properties of text to be deleted, if applicable. Optional. + This is a Python dictionary with the following properties: + + * font_ids: List of font resource IDs (such as /F1 or /T1_0) to be deleted. + + """ + if isinstance(to_delete, (list, tuple)): + for to_d in to_delete: + self.remove_objects_from_page(page, to_d) + return None + assert isinstance(to_delete, ObjectDeletionFlag) + + if to_delete & ObjectDeletionFlag.LINKS: + return self._remove_annots_from_page(page, ("/Link",)) + if to_delete & ObjectDeletionFlag.ATTACHMENTS: + return self._remove_annots_from_page( + page, ("/FileAttachment", "/Sound", "/Movie", "/Screen") + ) + if to_delete & ObjectDeletionFlag.OBJECTS_3D: + return self._remove_annots_from_page(page, ("/3D",)) + if to_delete & ObjectDeletionFlag.ALL_ANNOTATIONS: + return self._remove_annots_from_page(page, None) + + jump_operators = [] + if to_delete & ObjectDeletionFlag.DRAWING_IMAGES: + jump_operators = [ + b"w", b"J", b"j", b"M", b"d", b"i", + b"W", b"W*", + b"b", b"b*", b"B", b"B*", b"S", b"s", b"f", b"f*", b"F", b"n", + b"m", b"l", b"c", b"v", b"y", b"h", b"re", + b"sh" + ] + if to_delete & ObjectDeletionFlag.TEXT: + jump_operators = [b"Tj", b"TJ", b"'", b'"'] + + if not isinstance(page, PageObject): + page = PageObject(self, page.indirect_reference) # pragma: no cover + if "/Contents" in page: + content = cast(ContentStream, page.get_contents()) + + images, forms = self._remove_objects_from_page__clean_forms( + elt=page, stack=[], jump_operators=jump_operators, to_delete=to_delete, text_filters=text_filters, + ) + + self._remove_objects_from_page__clean( + content=content, images=images, forms=forms, + jump_operators=jump_operators, to_delete=to_delete, + text_filters=text_filters + ) + page.replace_contents(content) + return [], [] # type: ignore[return-value] + + def _remove_objects_from_page__clean( + self, + content: ContentStream, + images: list[str], + forms: list[str], + jump_operators: list[bytes], + to_delete: ObjectDeletionFlag, + text_filters: Optional[dict[str, Any]] = None, + ) -> None: + font_id = None + font_ids_to_delete = [] + if text_filters and to_delete & ObjectDeletionFlag.TEXT: + font_ids_to_delete = text_filters.get("font_ids", []) + + i = 0 + while i < len(content.operations): + operands, operator = content.operations[i] + if operator == b"Tf": + font_id = operands[0] + if ( + ( + operator == b"INLINE IMAGE" + and (to_delete & ObjectDeletionFlag.INLINE_IMAGES) + ) + or (operator in jump_operators) + or ( + operator == b"Do" + and (to_delete & ObjectDeletionFlag.XOBJECT_IMAGES) + and (operands[0] in images) + ) + ): + if ( + not to_delete & ObjectDeletionFlag.TEXT + or (to_delete & ObjectDeletionFlag.TEXT and not text_filters) + or (to_delete & ObjectDeletionFlag.TEXT and font_id in font_ids_to_delete) + ): + del content.operations[i] + else: + i += 1 + else: + i += 1 + content.get_data() # this ensures ._data is rebuilt from the .operations + + def _remove_objects_from_page__clean_forms( + self, + elt: DictionaryObject, + stack: list[DictionaryObject], + jump_operators: list[bytes], + to_delete: ObjectDeletionFlag, + text_filters: Optional[dict[str, Any]] = None, + ) -> tuple[list[str], list[str]]: + # elt in recursive call is a new ContentStream object, so we have to check the indirect_reference + if (elt in stack) or ( + hasattr(elt, "indirect_reference") and any( + elt.indirect_reference == getattr(x, "indirect_reference", -1) + for x in stack + ) + ): + # to prevent infinite looping + return [], [] # pragma: no cover + try: + d = cast( + dict[Any, Any], + cast(DictionaryObject, elt["/Resources"])["/XObject"], + ) + except KeyError: + d = {} + images = [] + forms = [] + for k, v in d.items(): + o = v.get_object() + try: + content: Any = None + if ( + to_delete & ObjectDeletionFlag.XOBJECT_IMAGES + and o["/Subtype"] == "/Image" + ): + content = NullObject() # to delete the image keeping the entry + images.append(k) + if o["/Subtype"] == "/Form": + forms.append(k) + if isinstance(o, ContentStream): + content = o + else: + content = ContentStream(o, self) + content.update( + { + k1: v1 + for k1, v1 in o.items() + if k1 not in ["/Length", "/Filter", "/DecodeParms"] + } + ) + try: + content.indirect_reference = o.indirect_reference + except AttributeError: # pragma: no cover + pass + stack.append(elt) + + # clean subforms + self._remove_objects_from_page__clean_forms( + elt=content, stack=stack, jump_operators=jump_operators, to_delete=to_delete, + text_filters=text_filters, + ) + if content is not None: + if isinstance(v, IndirectObject): + self._objects[v.idnum - 1] = content + else: + # should only occur in a PDF not respecting PDF spec + # where streams must be indirected. + d[k] = self._add_object(content) # pragma: no cover + except (TypeError, KeyError): + pass + for im in images: + del d[im] # for clean-up + if isinstance(elt, StreamObject): # for /Form + if not isinstance(elt, ContentStream): # pragma: no cover + e = ContentStream(elt, self) + e.update(elt.items()) + elt = e + # clean the content + self._remove_objects_from_page__clean( + content=elt, images=images, forms=forms, jump_operators=jump_operators, + to_delete=to_delete, text_filters=text_filters + ) + return images, forms + + def remove_images( + self, + to_delete: ImageType = ImageType.ALL, + ) -> None: + """ + Remove images from this output. + + Args: + to_delete: The type of images to be deleted + (default = all images types) + + """ + if isinstance(to_delete, bool): + to_delete = ImageType.ALL + + i = ObjectDeletionFlag.NONE + + for image in ("XOBJECT_IMAGES", "INLINE_IMAGES", "DRAWING_IMAGES"): + if to_delete & ImageType[image]: + i |= ObjectDeletionFlag[image] + + for page in self.pages: + self.remove_objects_from_page(page, i) + + def remove_text(self, font_names: Optional[list[str]] = None) -> None: + """ + Remove text from the PDF. + + Args: + font_names: List of font names to remove, such as "Helvetica-Bold". + Optional. If not specified, all text will be removed. + """ + if not font_names: + font_names = [] + + for page in self.pages: + resource_ids_to_remove = [] + + # Content streams reference fonts and other resources with names like "/F1" or "/T1_0" + # Font names need to be converted to resource names/IDs for easier removal + if font_names: + # Recursively loop through page objects to gather font info + def get_font_info( + obj: Any, + font_info: Optional[dict[str, Any]] = None, + key: Optional[str] = None + ) -> dict[str, Any]: + if font_info is None: + font_info = {} + if isinstance(obj, IndirectObject): + obj = obj.get_object() + if isinstance(obj, dict): + if obj.get("/Type") == "/Font": + font_name = obj.get("/BaseFont", "") + # Normalize font names like "/RRXFFV+Palatino-Bold" to "Palatino-Bold" + normalized_font_name = font_name.lstrip("/").split("+")[-1] + if normalized_font_name not in font_info: + font_info[normalized_font_name] = { + "normalized_font_name": normalized_font_name, + "resource_ids": [], + } + if key not in font_info[normalized_font_name]["resource_ids"]: + font_info[normalized_font_name]["resource_ids"].append(key) + for k in obj: + font_info = get_font_info(obj[k], font_info, k) + elif isinstance(obj, (list, ArrayObject)): + for child_obj in obj: + font_info = get_font_info(child_obj, font_info) + return font_info + + # Add relevant resource names for removal + font_info = get_font_info(page.get("/Resources")) + for font_name in font_names: + if font_name in font_info: + resource_ids_to_remove.extend(font_info[font_name]["resource_ids"]) + + text_filters = {} + if font_names: + text_filters["font_ids"] = resource_ids_to_remove + self.remove_objects_from_page(page, ObjectDeletionFlag.TEXT, text_filters=text_filters) + + def add_uri( + self, + page_number: int, + uri: str, + rect: RectangleObject, + border: Optional[ArrayObject] = None, + ) -> None: + """ + Add an URI from a rectangular area to the specified page. + + Args: + page_number: index of the page on which to place the URI action. + uri: URI of resource to link to. + rect: :class:`RectangleObject` or + array of four integers specifying the clickable rectangular area + ``[xLL, yLL, xUR, yUR]``, or string in the form + ``"[ xLL yLL xUR yUR ]"``. + border: if provided, an array describing border-drawing + properties. See the PDF spec for details. No border will be + drawn if this argument is omitted. + + """ + page_link = self.get_object(self._pages)[PagesAttributes.KIDS][page_number] # type: ignore + page_ref = cast(dict[str, Any], self.get_object(page_link)) + + border_arr: BorderArrayType + if border is not None: + border_arr = [NumberObject(n) for n in border[:3]] + if len(border) == 4: + dash_pattern = ArrayObject([NumberObject(n) for n in border[3]]) + border_arr.append(dash_pattern) + else: + border_arr = [NumberObject(2), NumberObject(2), NumberObject(2)] + + if isinstance(rect, str): + rect = NumberObject(rect) + elif isinstance(rect, RectangleObject): + pass + else: + rect = RectangleObject(rect) + + lnk2 = DictionaryObject() + lnk2.update( + { + NameObject("/S"): NameObject("/URI"), + NameObject("/URI"): TextStringObject(uri), + } + ) + lnk = DictionaryObject() + lnk.update( + { + NameObject(AA.Type): NameObject("/Annot"), + NameObject(AA.Subtype): NameObject("/Link"), + NameObject(AA.P): page_link, + NameObject(AA.Rect): rect, + NameObject("/H"): NameObject("/I"), + NameObject(AA.Border): ArrayObject(border_arr), + NameObject("/A"): lnk2, + } + ) + lnk_ref = self._add_object(lnk) + + if PG.ANNOTS in page_ref: + page_ref[PG.ANNOTS].append(lnk_ref) + else: + page_ref[NameObject(PG.ANNOTS)] = ArrayObject([lnk_ref]) + + _valid_layouts = ( + "/NoLayout", + "/SinglePage", + "/OneColumn", + "/TwoColumnLeft", + "/TwoColumnRight", + "/TwoPageLeft", + "/TwoPageRight", + ) + + def _get_page_layout(self) -> Optional[LayoutType]: + try: + return cast(LayoutType, self._root_object["/PageLayout"]) + except KeyError: + return None + + def _set_page_layout(self, layout: Union[NameObject, LayoutType]) -> None: + """ + Set the page layout. + + Args: + layout: The page layout to be used. + + .. list-table:: Valid ``layout`` arguments + :widths: 50 200 + + * - /NoLayout + - Layout explicitly not specified + * - /SinglePage + - Show one page at a time + * - /OneColumn + - Show one column at a time + * - /TwoColumnLeft + - Show pages in two columns, odd-numbered pages on the left + * - /TwoColumnRight + - Show pages in two columns, odd-numbered pages on the right + * - /TwoPageLeft + - Show two pages at a time, odd-numbered pages on the left + * - /TwoPageRight + - Show two pages at a time, odd-numbered pages on the right + + """ + if not isinstance(layout, NameObject): + if layout not in self._valid_layouts: + logger_warning( + f"Layout should be one of: {'', ''.join(self._valid_layouts)}", + __name__, + ) + layout = NameObject(layout) + self._root_object.update({NameObject("/PageLayout"): layout}) + + def set_page_layout(self, layout: LayoutType) -> None: + """ + Set the page layout. + + Args: + layout: The page layout to be used + + .. list-table:: Valid ``layout`` arguments + :widths: 50 200 + + * - /NoLayout + - Layout explicitly not specified + * - /SinglePage + - Show one page at a time + * - /OneColumn + - Show one column at a time + * - /TwoColumnLeft + - Show pages in two columns, odd-numbered pages on the left + * - /TwoColumnRight + - Show pages in two columns, odd-numbered pages on the right + * - /TwoPageLeft + - Show two pages at a time, odd-numbered pages on the left + * - /TwoPageRight + - Show two pages at a time, odd-numbered pages on the right + + """ + self._set_page_layout(layout) + + @property + def page_layout(self) -> Optional[LayoutType]: + """ + Page layout property. + + .. list-table:: Valid ``layout`` values + :widths: 50 200 + + * - /NoLayout + - Layout explicitly not specified + * - /SinglePage + - Show one page at a time + * - /OneColumn + - Show one column at a time + * - /TwoColumnLeft + - Show pages in two columns, odd-numbered pages on the left + * - /TwoColumnRight + - Show pages in two columns, odd-numbered pages on the right + * - /TwoPageLeft + - Show two pages at a time, odd-numbered pages on the left + * - /TwoPageRight + - Show two pages at a time, odd-numbered pages on the right + """ + return self._get_page_layout() + + @page_layout.setter + def page_layout(self, layout: LayoutType) -> None: + self._set_page_layout(layout) + + _valid_modes = ( + "/UseNone", + "/UseOutlines", + "/UseThumbs", + "/FullScreen", + "/UseOC", + "/UseAttachments", + ) + + def _get_page_mode(self) -> Optional[PagemodeType]: + try: + return cast(PagemodeType, self._root_object["/PageMode"]) + except KeyError: + return None + + @property + def page_mode(self) -> Optional[PagemodeType]: + """ + Page mode property. + + .. list-table:: Valid ``mode`` values + :widths: 50 200 + + * - /UseNone + - Do not show outline or thumbnails panels + * - /UseOutlines + - Show outline (aka bookmarks) panel + * - /UseThumbs + - Show page thumbnails panel + * - /FullScreen + - Fullscreen view + * - /UseOC + - Show Optional Content Group (OCG) panel + * - /UseAttachments + - Show attachments panel + """ + return self._get_page_mode() + + @page_mode.setter + def page_mode(self, mode: PagemodeType) -> None: + if isinstance(mode, NameObject): + mode_name: NameObject = mode + else: + if mode not in self._valid_modes: + logger_warning( + f"Mode should be one of: {', '.join(self._valid_modes)}", __name__ + ) + mode_name = NameObject(mode) + self._root_object.update({NameObject("/PageMode"): mode_name}) + + def add_annotation( + self, + page_number: Union[int, PageObject], + annotation: dict[str, Any], + ) -> DictionaryObject: + """ + Add a single annotation to the page. + The added annotation must be a new annotation. + It cannot be recycled. + + Args: + page_number: PageObject or page index. + annotation: Annotation to be added (created with annotation). + + Returns: + The inserted object. + This can be used for popup creation, for example. + + """ + page = page_number + if isinstance(page, int): + page = self.pages[page] + elif not isinstance(page, PageObject): + raise TypeError("page: invalid type") + + to_add = cast(DictionaryObject, _pdf_objectify(annotation)) + to_add[NameObject("/P")] = page.indirect_reference + + if page.annotations is None: + page[NameObject("/Annots")] = ArrayObject() + assert page.annotations is not None + + # Internal link annotations need the correct object type for the + # destination + if to_add.get("/Subtype") == "/Link" and "/Dest" in to_add: + tmp = cast(dict[Any, Any], to_add[NameObject("/Dest")]) + dest = Destination( + NameObject("/LinkName"), + tmp["target_page_index"], + Fit( + fit_type=tmp["fit"], fit_args=dict(tmp)["fit_args"] + ), # I have no clue why this dict-hack is necessary + ) + to_add[NameObject("/Dest")] = dest.dest_array + + page.annotations.append(self._add_object(to_add)) + + if to_add.get("/Subtype") == "/Popup" and NameObject("/Parent") in to_add: + cast(DictionaryObject, to_add["/Parent"].get_object())[ + NameObject("/Popup") + ] = to_add.indirect_reference + + return to_add + + def clean_page(self, page: Union[PageObject, IndirectObject]) -> PageObject: + """ + Perform some clean up in the page. + Currently: convert NameObject named destination to TextStringObject + (required for names/dests list) + + Args: + page: + + Returns: + The cleaned PageObject + + """ + page = cast("PageObject", page.get_object()) + for a in page.get("/Annots", []): + a_obj = a.get_object() + d = a_obj.get("/Dest", None) + act = a_obj.get("/A", None) + if isinstance(d, NameObject): + a_obj[NameObject("/Dest")] = TextStringObject(d) + elif act is not None: + act = act.get_object() + d = act.get("/D", None) + if isinstance(d, NameObject): + act[NameObject("/D")] = TextStringObject(d) + return page + + def _create_stream( + self, fileobj: Union[Path, StrByteType, PdfReader] + ) -> tuple[IOBase, Optional[Encryption]]: + # If the fileobj parameter is a string, assume it is a path + # and create a file object at that location. If it is a file, + # copy the file's contents into a BytesIO stream object; if + # it is a PdfReader, copy that reader's stream into a + # BytesIO stream. + # If fileobj is none of the above types, it is not modified + encryption_obj = None + stream: IOBase + if isinstance(fileobj, (str, Path)): + with FileIO(fileobj, "rb") as f: + stream = BytesIO(f.read()) + elif isinstance(fileobj, PdfReader): + if fileobj._encryption: + encryption_obj = fileobj._encryption + orig_tell = fileobj.stream.tell() + fileobj.stream.seek(0) + stream = BytesIO(fileobj.stream.read()) + + # reset the stream to its original location + fileobj.stream.seek(orig_tell) + elif hasattr(fileobj, "seek") and hasattr(fileobj, "read"): + fileobj.seek(0) + filecontent = fileobj.read() + stream = BytesIO(filecontent) + else: + raise NotImplementedError( + "Merging requires an object that PdfReader can parse. " + "Typically, that is a Path or a string representing a Path, " + "a file object, or an object implementing .seek and .read. " + "Passing a PdfReader directly works as well." + ) + return stream, encryption_obj + + def append( + self, + fileobj: Union[StrByteType, PdfReader, Path], + outline_item: Union[ + str, None, PageRange, tuple[int, int], tuple[int, int, int], list[int] + ] = None, + pages: Union[ + None, + PageRange, + tuple[int, int], + tuple[int, int, int], + list[int], + list[PageObject], + ] = None, + import_outline: bool = True, + excluded_fields: Optional[Union[list[str], tuple[str, ...]]] = None, + ) -> None: + """ + Identical to the :meth:`merge()` method, but assumes you want to + concatenate all pages onto the end of the file instead of specifying a + position. + + Args: + fileobj: A File Object or an object that supports the standard + read and seek methods similar to a File Object. Could also be a + string representing a path to a PDF file. + outline_item: Optionally, you may specify a string to build an + outline (aka 'bookmark') to identify the beginning of the + included file. + pages: Can be a :class:`PageRange` + or a ``(start, stop[, step])`` tuple + or a list of pages to be processed + to merge only the specified range of pages from the source + document into the output document. + import_outline: You may prevent the source document's + outline (collection of outline items, previously referred to as + 'bookmarks') from being imported by specifying this as ``False``. + excluded_fields: Provide the list of fields/keys to be ignored + if ``/Annots`` is part of the list, the annotation will be ignored + if ``/B`` is part of the list, the articles will be ignored + + """ + if excluded_fields is None: + excluded_fields = () + if isinstance(outline_item, (tuple, list, PageRange)): + if isinstance(pages, bool): + if not isinstance(import_outline, bool): + excluded_fields = import_outline + import_outline = pages + pages = outline_item + self.merge( + None, + fileobj, + None, + pages, + import_outline, + excluded_fields, + ) + else: # if isinstance(outline_item, str): + self.merge( + None, + fileobj, + outline_item, + pages, + import_outline, + excluded_fields, + ) + + def merge( + self, + position: Optional[int], + fileobj: Union[Path, StrByteType, PdfReader], + outline_item: Optional[str] = None, + pages: Optional[Union[PageRangeSpec, list[PageObject]]] = None, + import_outline: bool = True, + excluded_fields: Optional[Union[list[str], tuple[str, ...]]] = (), + ) -> None: + """ + Merge the pages from the given file into the output file at the + specified page number. + + Args: + position: The *page number* to insert this file. File will + be inserted after the given number. + fileobj: A File Object or an object that supports the standard + read and seek methods similar to a File Object. Could also be a + string representing a path to a PDF file. + outline_item: Optionally, you may specify a string to build an outline + (aka 'bookmark') to identify the + beginning of the included file. + pages: can be a :class:`PageRange` + or a ``(start, stop[, step])`` tuple + or a list of pages to be processed + to merge only the specified range of pages from the source + document into the output document. + import_outline: You may prevent the source document's + outline (collection of outline items, previously referred to as + 'bookmarks') from being imported by specifying this as ``False``. + excluded_fields: provide the list of fields/keys to be ignored + if ``/Annots`` is part of the list, the annotation will be ignored + if ``/B`` is part of the list, the articles will be ignored + + Raises: + TypeError: The pages attribute is not configured properly + + """ + if isinstance(fileobj, PdfDocCommon): + reader = fileobj + else: + stream, _encryption_obj = self._create_stream(fileobj) + # Create a new PdfReader instance using the stream + # (either file or BytesIO or StringIO) created above + reader = PdfReader(stream, strict=False) # type: ignore[arg-type] + + if excluded_fields is None: + excluded_fields = () + # Find the range of pages to merge. + if pages is None: + pages = list(range(len(reader.pages))) + elif isinstance(pages, PageRange): + pages = list(range(*pages.indices(len(reader.pages)))) + elif isinstance(pages, list): + pass # keep unchanged + elif isinstance(pages, tuple) and len(pages) <= 3: + pages = list(range(*pages)) + elif not isinstance(pages, tuple): + raise TypeError( + '"pages" must be a tuple of (start, stop[, step]) or a list' + ) + + srcpages = {} + for page in pages: + if isinstance(page, PageObject): + pg = page + else: + pg = reader.pages[page] + assert pg.indirect_reference is not None + if position is None: + # numbers in the exclude list identifies that the exclusion is + # only applicable to 1st level of cloning + srcpages[pg.indirect_reference.idnum] = self.add_page( + pg, [*list(excluded_fields), 1, "/B", 1, "/Annots"] # type: ignore + ) + else: + srcpages[pg.indirect_reference.idnum] = self.insert_page( + pg, position, [*list(excluded_fields), 1, "/B", 1, "/Annots"] # type: ignore + ) + position += 1 + srcpages[pg.indirect_reference.idnum].original_page = pg + + reader._named_destinations = ( + reader.named_destinations + ) # need for the outline processing below + + arr: Any + + for dest in reader._named_destinations.values(): + self._merge__process_named_dests(dest=dest, reader=reader, srcpages=srcpages) + + outline_item_typ: TreeObject + if outline_item is not None: + outline_item_typ = cast( + "TreeObject", + self.add_outline_item( + TextStringObject(outline_item), + next(iter(srcpages.values())).indirect_reference, + fit=PAGE_FIT, + ).get_object(), + ) + else: + outline_item_typ = self.get_outline_root() + + _ro = reader.root_object + if import_outline and CO.OUTLINES in _ro: + outline = self._get_filtered_outline( + _ro.get(CO.OUTLINES, None), srcpages, reader + ) + self._insert_filtered_outline( + outline, outline_item_typ, None + ) # TODO: use before parameter + + if "/Annots" not in excluded_fields: + for pag in srcpages.values(): + lst = self._insert_filtered_annotations( + pag.original_page.get("/Annots", []), pag, srcpages, reader + ) + if len(lst) > 0: + pag[NameObject("/Annots")] = lst + self.clean_page(pag) + + if "/AcroForm" in _ro and not is_null_or_none(_ro["/AcroForm"]): + if "/AcroForm" not in self._root_object: + self._root_object[NameObject("/AcroForm")] = self._add_object( + cast( + DictionaryObject, + reader.root_object["/AcroForm"], + ).clone(self, False, ("/Fields",)) + ) + arr = ArrayObject() + else: + arr = cast( + ArrayObject, + cast(DictionaryObject, self._root_object["/AcroForm"])["/Fields"], + ) + trslat = self._id_translated[id(reader)] + try: + for f in reader.root_object["/AcroForm"]["/Fields"]: # type: ignore + try: + ind = IndirectObject(trslat[f.idnum], 0, self) + if ind not in arr: + arr.append(ind) + except KeyError: + # for trslat[] which mean the field has not be copied + # through the page + pass + except KeyError: # for /Acroform or /Fields are not existing + arr = self._add_object(ArrayObject()) + cast(DictionaryObject, self._root_object["/AcroForm"])[ + NameObject("/Fields") + ] = arr + + if "/B" not in excluded_fields: + self.add_filtered_articles("", srcpages, reader) + + def _merge__process_named_dests(self, dest: Any, reader: PdfDocCommon, srcpages: dict[int, PageObject]) -> None: + arr: Any = dest.dest_array + if "/Names" in self._root_object and dest["/Title"] in cast( + list[Any], + cast( + DictionaryObject, + cast(DictionaryObject, self._root_object["/Names"]).get("/Dests", DictionaryObject()), + ).get("/Names", DictionaryObject()), + ): + # already exists: should not duplicate it + pass + elif dest["/Page"] is None or isinstance(dest["/Page"], NullObject): + pass + elif isinstance(dest["/Page"], int): + # the page reference is a page number normally not a PDF Reference + # page numbers as int are normally accepted only in external goto + try: + p = reader.pages[dest["/Page"]] + except IndexError: + return + assert p.indirect_reference is not None + try: + arr[NumberObject(0)] = NumberObject( + srcpages[p.indirect_reference.idnum].page_number + ) + self.add_named_destination_array(dest["/Title"], arr) + except KeyError: + pass + elif dest["/Page"].indirect_reference.idnum in srcpages: + arr[NumberObject(0)] = srcpages[ + dest["/Page"].indirect_reference.idnum + ].indirect_reference + self.add_named_destination_array(dest["/Title"], arr) + + def _add_articles_thread( + self, + thread: DictionaryObject, # thread entry from the reader's array of threads + pages: dict[int, PageObject], + reader: PdfReader, + ) -> IndirectObject: + """ + Clone the thread with only the applicable articles. + + Args: + thread: + pages: + reader: + + Returns: + The added thread as an indirect reference + + """ + nthread = thread.clone( + self, force_duplicate=True, ignore_fields=("/F",) + ) # use of clone to keep link between reader and writer + self.threads.append(nthread.indirect_reference) + first_article = cast("DictionaryObject", thread["/F"]) + current_article: Optional[DictionaryObject] = first_article + new_article: Optional[DictionaryObject] = None + while current_article is not None: + pag = self._get_cloned_page( + cast("PageObject", current_article["/P"]), pages, reader + ) + if pag is not None: + if new_article is None: + new_article = cast( + "DictionaryObject", + self._add_object(DictionaryObject()).get_object(), + ) + new_first = new_article + nthread[NameObject("/F")] = new_article.indirect_reference + else: + new_article2 = cast( + "DictionaryObject", + self._add_object( + DictionaryObject( + {NameObject("/V"): new_article.indirect_reference} + ) + ).get_object(), + ) + new_article[NameObject("/N")] = new_article2.indirect_reference + new_article = new_article2 + new_article[NameObject("/P")] = pag + new_article[NameObject("/T")] = nthread.indirect_reference + new_article[NameObject("/R")] = current_article["/R"] + pag_obj = cast("PageObject", pag.get_object()) + if "/B" not in pag_obj: + pag_obj[NameObject("/B")] = ArrayObject() + cast("ArrayObject", pag_obj["/B"]).append( + new_article.indirect_reference + ) + current_article = cast("DictionaryObject", current_article["/N"]) + if current_article == first_article: + new_article[NameObject("/N")] = new_first.indirect_reference # type: ignore + new_first[NameObject("/V")] = new_article.indirect_reference # type: ignore + current_article = None + assert nthread.indirect_reference is not None + return nthread.indirect_reference + + def add_filtered_articles( + self, + fltr: Union[ + Pattern[Any], str + ], # thread entry from the reader's array of threads + pages: dict[int, PageObject], + reader: PdfReader, + ) -> None: + """ + Add articles matching the defined criteria. + + Args: + fltr: + pages: + reader: + + """ + if isinstance(fltr, str): + fltr = re.compile(fltr) + elif not isinstance(fltr, Pattern): + fltr = re.compile("") + for p in pages.values(): + pp = p.original_page + for a in pp.get("/B", ()): + a_obj = a.get_object() + if is_null_or_none(a_obj): + continue + thr = a_obj.get("/T") + if thr is None: + continue + thr = thr.get_object() + if thr.indirect_reference.idnum not in self._id_translated[ + id(reader) + ] and fltr.search((thr.get("/I", {})).get("/Title", "")): + self._add_articles_thread(thr, pages, reader) + + def _get_cloned_page( + self, + page: Union[None, IndirectObject, PageObject, NullObject], + pages: dict[int, PageObject], + reader: PdfReader, + ) -> Optional[IndirectObject]: + if isinstance(page, NullObject): + return None + if isinstance(page, DictionaryObject) and page.get("/Type", "") == "/Page": + _i = page.indirect_reference + elif isinstance(page, IndirectObject): + _i = page + try: + return pages[_i.idnum].indirect_reference # type: ignore + except Exception: + return None + + def _insert_filtered_annotations( + self, + annots: Union[IndirectObject, list[DictionaryObject], None], + page: PageObject, + pages: dict[int, PageObject], + reader: PdfReader, + ) -> list[Destination]: + outlist = ArrayObject() + if isinstance(annots, IndirectObject): + annots = cast("list[Any]", annots.get_object()) + if annots is None: + return outlist + if not isinstance(annots, list): + logger_warning(f"Expected list of annotations, got {annots} of type {annots.__class__.__name__}.", __name__) + return outlist + for an in annots: + ano = cast("DictionaryObject", an.get_object()) + if ( + ano["/Subtype"] != "/Link" # type: ignore[comparison-overlap] + or "/A" not in ano + or cast("DictionaryObject", ano["/A"])["/S"] != "/GoTo" # type: ignore[comparison-overlap] + or "/Dest" in ano + ): + if "/Dest" not in ano: + outlist.append(self._add_object(ano.clone(self))) + else: + d = ano["/Dest"] + if isinstance(d, str): + # it is a named dest + if str(d) in self.get_named_dest_root(): + outlist.append(ano.clone(self).indirect_reference) + else: + d = cast("ArrayObject", d) + p = self._get_cloned_page(d[0], pages, reader) + if p is not None: + anc = ano.clone(self, ignore_fields=("/Dest",)) + anc[NameObject("/Dest")] = ArrayObject([p, *d[1:]]) + outlist.append(self._add_object(anc)) + else: + d = cast("DictionaryObject", ano["/A"]).get("/D", NullObject()) + if is_null_or_none(d): + continue + if isinstance(d, str): + # it is a named dest + if str(d) in self.get_named_dest_root(): + outlist.append(ano.clone(self).indirect_reference) + else: + d = cast("ArrayObject", d) + p = self._get_cloned_page(d[0], pages, reader) + if p is not None: + anc = ano.clone(self, ignore_fields=("/D",)) + cast("DictionaryObject", anc["/A"])[ + NameObject("/D") + ] = ArrayObject([p, *d[1:]]) + outlist.append(self._add_object(anc)) + return outlist + + def _get_filtered_outline( + self, + node: Any, + pages: dict[int, PageObject], + reader: PdfReader, + ) -> list[Destination]: + """ + Extract outline item entries that are part of the specified page set. + + Args: + node: + pages: + reader: + + Returns: + A list of destination objects. + + """ + new_outline = [] + if node is None: + node = NullObject() + node = node.get_object() + if is_null_or_none(node): + node = DictionaryObject() + if node.get("/Type", "") == "/Outlines" or "/Title" not in node: + node = node.get("/First", None) + if node is not None: + node = node.get_object() + new_outline += self._get_filtered_outline(node, pages, reader) + else: + v: Union[None, IndirectObject, NullObject] + while node is not None: + node = node.get_object() + o = cast("Destination", reader._build_outline_item(node)) + v = self._get_cloned_page(cast("PageObject", o["/Page"]), pages, reader) + if v is None: + v = NullObject() + o[NameObject("/Page")] = v + if "/First" in node: + o._filtered_children = self._get_filtered_outline( + node["/First"], pages, reader + ) + else: + o._filtered_children = [] + if ( + not isinstance(o["/Page"], NullObject) + or len(o._filtered_children) > 0 + ): + new_outline.append(o) + node = node.get("/Next", None) + return new_outline + + def _clone_outline(self, dest: Destination) -> TreeObject: + n_ol = TreeObject() + self._add_object(n_ol) + n_ol[NameObject("/Title")] = TextStringObject(dest["/Title"]) + if not isinstance(dest["/Page"], NullObject): + if dest.node is not None and "/A" in dest.node: + n_ol[NameObject("/A")] = dest.node["/A"].clone(self) + else: + n_ol[NameObject("/Dest")] = dest.dest_array + # TODO: /SE + if dest.node is not None: + n_ol[NameObject("/F")] = NumberObject(dest.node.get("/F", 0)) + n_ol[NameObject("/C")] = ArrayObject( + dest.node.get( + "/C", [FloatObject(0.0), FloatObject(0.0), FloatObject(0.0)] + ) + ) + return n_ol + + def _insert_filtered_outline( + self, + outlines: list[Destination], + parent: Union[TreeObject, IndirectObject], + before: Union[None, TreeObject, IndirectObject] = None, + ) -> None: + for dest in outlines: + # TODO: can be improved to keep A and SE entries (ignored for the moment) + # with np=self.add_outline_item_destination(dest,parent,before) + if dest.get("/Type", "") == "/Outlines" or "/Title" not in dest: + np = parent + else: + np = self._clone_outline(dest) + cast(TreeObject, parent.get_object()).insert_child(np, before, self) + self._insert_filtered_outline(dest._filtered_children, np, None) + + def close(self) -> None: + """Implemented for API harmonization.""" + return + + def find_outline_item( + self, + outline_item: dict[str, Any], + root: Optional[OutlineType] = None, + ) -> Optional[list[int]]: + if root is None: + o = self.get_outline_root() + else: + o = cast("TreeObject", root) + + i = 0 + while o is not None: + if ( + o.indirect_reference == outline_item + or o.get("/Title", None) == outline_item + ): + return [i] + if "/First" in o: + res = self.find_outline_item( + outline_item, cast(OutlineType, o["/First"]) + ) + if res: + return ([i] if "/Title" in o else []) + res + if "/Next" in o: + i += 1 + o = cast(TreeObject, o["/Next"]) + else: + return None + raise PyPdfError("This line is theoretically unreachable.") # pragma: no cover + + def reset_translation( + self, reader: Union[None, PdfReader, IndirectObject] = None + ) -> None: + """ + Reset the translation table between reader and the writer object. + + Late cloning will create new independent objects. + + Args: + reader: PdfReader or IndirectObject referencing a PdfReader object. + if set to None or omitted, all tables will be reset. + + """ + if reader is None: + self._id_translated = {} + elif isinstance(reader, PdfReader): + try: + del self._id_translated[id(reader)] + except Exception: + pass + elif isinstance(reader, IndirectObject): + try: + del self._id_translated[id(reader.pdf)] + except Exception: + pass + else: + raise Exception("invalid parameter {reader}") + + def set_page_label( + self, + page_index_from: int, + page_index_to: int, + style: Optional[PageLabelStyle] = None, + prefix: Optional[str] = None, + start: Optional[int] = 0, + ) -> None: + """ + Set a page label to a range of pages. + + Page indexes must be given starting from 0. + Labels must have a style, a prefix or both. + If a range is not assigned any page label, a decimal label starting from 1 is applied. + + Args: + page_index_from: page index of the beginning of the range starting from 0 + page_index_to: page index of the beginning of the range starting from 0 + style: The numbering style to be used for the numeric portion of each page label: + + * ``/D`` Decimal Arabic numerals + * ``/R`` Uppercase Roman numerals + * ``/r`` Lowercase Roman numerals + * ``/A`` Uppercase letters (A to Z for the first 26 pages, + AA to ZZ for the next 26, and so on) + * ``/a`` Lowercase letters (a to z for the first 26 pages, + aa to zz for the next 26, and so on) + + prefix: The label prefix for page labels in this range. + start: The value of the numeric portion for the first page label + in the range. + Subsequent pages are numbered sequentially from this value, + which must be greater than or equal to 1. + Default value: 1. + + """ + if style is None and prefix is None: + raise ValueError("At least one of style and prefix must be given") + if page_index_from < 0: + raise ValueError("page_index_from must be greater or equal than 0") + if page_index_to < page_index_from: + raise ValueError( + "page_index_to must be greater or equal than page_index_from" + ) + if page_index_to >= len(self.pages): + raise ValueError("page_index_to exceeds number of pages") + if start is not None and start != 0 and start < 1: + raise ValueError("If given, start must be greater or equal than one") + + self._set_page_label(page_index_from, page_index_to, style, prefix, start) + + def _set_page_label( + self, + page_index_from: int, + page_index_to: int, + style: Optional[PageLabelStyle] = None, + prefix: Optional[str] = None, + start: Optional[int] = 0, + ) -> None: + """ + Set a page label to a range of pages. + + Page indexes must be given starting from 0. + Labels must have a style, a prefix or both. + If a range is not assigned any page label a decimal label starting from 1 is applied. + + Args: + page_index_from: page index of the beginning of the range starting from 0 + page_index_to: page index of the beginning of the range starting from 0 + style: The numbering style to be used for the numeric portion of each page label: + /D Decimal Arabic numerals + /R Uppercase Roman numerals + /r Lowercase Roman numerals + /A Uppercase letters (A to Z for the first 26 pages, + AA to ZZ for the next 26, and so on) + /a Lowercase letters (a to z for the first 26 pages, + aa to zz for the next 26, and so on) + prefix: The label prefix for page labels in this range. + start: The value of the numeric portion for the first page label + in the range. + Subsequent pages are numbered sequentially from this value, + which must be greater than or equal to 1. Default value: 1. + + """ + default_page_label = DictionaryObject() + default_page_label[NameObject("/S")] = NameObject("/D") + + new_page_label = DictionaryObject() + if style is not None: + new_page_label[NameObject("/S")] = NameObject(style) + if prefix is not None: + new_page_label[NameObject("/P")] = TextStringObject(prefix) + if start != 0: + new_page_label[NameObject("/St")] = NumberObject(start) + + if NameObject(CatalogDictionary.PAGE_LABELS) not in self._root_object: + nums = ArrayObject() + nums_insert(NumberObject(0), default_page_label, nums) + page_labels = TreeObject() + page_labels[NameObject("/Nums")] = nums + self._root_object[NameObject(CatalogDictionary.PAGE_LABELS)] = page_labels + + page_labels = cast( + TreeObject, self._root_object[NameObject(CatalogDictionary.PAGE_LABELS)] + ) + nums = cast(ArrayObject, page_labels[NameObject("/Nums")]) + + nums_insert(NumberObject(page_index_from), new_page_label, nums) + nums_clear_range(NumberObject(page_index_from), page_index_to, nums) + next_label_pos, *_ = nums_next(NumberObject(page_index_from), nums) + if next_label_pos != page_index_to + 1 and page_index_to + 1 < len(self.pages): + nums_insert(NumberObject(page_index_to + 1), default_page_label, nums) + + page_labels[NameObject("/Nums")] = nums + self._root_object[NameObject(CatalogDictionary.PAGE_LABELS)] = page_labels + + def _repr_mimebundle_( + self, + include: Union[None, Iterable[str]] = None, + exclude: Union[None, Iterable[str]] = None, + ) -> dict[str, Any]: + """ + Integration into Jupyter Notebooks. + + This method returns a dictionary that maps a mime-type to its + representation. + + .. seealso:: + + https://ipython.readthedocs.io/en/stable/config/integrating.html + """ + pdf_data = BytesIO() + self.write(pdf_data) + data = { + "application/pdf": pdf_data, + } + + if include is not None: + # Filter representations based on include list + data = {k: v for k, v in data.items() if k in include} + + if exclude is not None: + # Remove representations based on exclude list + data = {k: v for k, v in data.items() if k not in exclude} + + return data + + +def _pdf_objectify(obj: Union[dict[str, Any], str, float, list[Any]]) -> PdfObject: + if isinstance(obj, PdfObject): + return obj + if isinstance(obj, dict): + to_add = DictionaryObject() + for key, value in obj.items(): + to_add[NameObject(key)] = _pdf_objectify(value) + return to_add + if isinstance(obj, str): + if obj.startswith("/"): + return NameObject(obj) + return TextStringObject(obj) + if isinstance(obj, (float, int)): + return FloatObject(obj) + if isinstance(obj, list): + return ArrayObject(_pdf_objectify(i) for i in obj) + raise NotImplementedError( + f"{type(obj)=} could not be cast to a PdfObject" + ) + + +def _create_outline_item( + action_ref: Union[None, IndirectObject], + title: str, + color: Union[tuple[float, float, float], str, None], + italic: bool, + bold: bool, +) -> TreeObject: + outline_item = TreeObject() + if action_ref is not None: + outline_item[NameObject("/A")] = action_ref + outline_item.update( + { + NameObject("/Title"): create_string_object(title), + } + ) + if color: + if isinstance(color, str): + color = hex_to_rgb(color) + outline_item.update( + {NameObject("/C"): ArrayObject([FloatObject(c) for c in color])} + ) + if italic or bold: + format_flag = 0 + if italic: + format_flag += OutlineFontFlag.italic + if bold: + format_flag += OutlineFontFlag.bold + outline_item.update({NameObject("/F"): NumberObject(format_flag)}) + return outline_item diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/constants.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..c1069b69ab39cd21e9f8bf39d52056c382946a3f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/constants.py @@ -0,0 +1,814 @@ +"""Various constants, enums, and flags to aid readability.""" + +from enum import Enum, IntFlag, auto, unique + + +class StrEnum(str, Enum): # Once we are on Python 3.11+: enum.StrEnum + def __str__(self) -> str: + return str(self.value) + + +class Core: + """Keywords that don't quite belong anywhere else.""" + + OUTLINES = "/Outlines" + THREADS = "/Threads" + PAGE = "/Page" + PAGES = "/Pages" + CATALOG = "/Catalog" + + +class TrailerKeys: + SIZE = "/Size" + PREV = "/Prev" + ROOT = "/Root" + ENCRYPT = "/Encrypt" + INFO = "/Info" + ID = "/ID" + + +class CatalogAttributes: + NAMES = "/Names" + DESTS = "/Dests" + + +class EncryptionDictAttributes: + """ + Additional encryption dictionary entries for the standard security handler. + + Table 3.19, Page 122. + Table 21 of the 2.0 manual. + """ + + R = "/R" # number, required; revision of the standard security handler + O = "/O" # 32-byte string, required # noqa: E741 + U = "/U" # 32-byte string, required + P = "/P" # integer flag, required; permitted operations + ENCRYPT_METADATA = "/EncryptMetadata" # boolean flag, optional + + +class UserAccessPermissions(IntFlag): + """ + Table 3.20 User access permissions. + Table 22 of the 2.0 manual. + """ + + R1 = 1 + R2 = 2 + PRINT = 4 + MODIFY = 8 + EXTRACT = 16 + ADD_OR_MODIFY = 32 + R7 = 64 + R8 = 128 + FILL_FORM_FIELDS = 256 + EXTRACT_TEXT_AND_GRAPHICS = 512 + ASSEMBLE_DOC = 1024 + PRINT_TO_REPRESENTATION = 2048 + R13 = 2**12 + R14 = 2**13 + R15 = 2**14 + R16 = 2**15 + R17 = 2**16 + R18 = 2**17 + R19 = 2**18 + R20 = 2**19 + R21 = 2**20 + R22 = 2**21 + R23 = 2**22 + R24 = 2**23 + R25 = 2**24 + R26 = 2**25 + R27 = 2**26 + R28 = 2**27 + R29 = 2**28 + R30 = 2**29 + R31 = 2**30 + R32 = 2**31 + + @classmethod + def _is_reserved(cls, name: str) -> bool: + """Check if the given name corresponds to a reserved flag entry.""" + return name.startswith("R") and name[1:].isdigit() + + @classmethod + def _is_active(cls, name: str) -> bool: + """Check if the given reserved name defaults to 1 = active.""" + return name not in {"R1", "R2"} + + def to_dict(self) -> dict[str, bool]: + """Convert the given flag value to a corresponding verbose name mapping.""" + result: dict[str, bool] = {} + for name, flag in UserAccessPermissions.__members__.items(): + if UserAccessPermissions._is_reserved(name): + continue + result[name.lower()] = (self & flag) == flag + return result + + @classmethod + def from_dict(cls, value: dict[str, bool]) -> "UserAccessPermissions": + """Convert the verbose name mapping to the corresponding flag value.""" + value_copy = value.copy() + result = cls(0) + for name, flag in cls.__members__.items(): + if cls._is_reserved(name): + # Reserved names have a required value. Use it. + if cls._is_active(name): + result |= flag + continue + is_active = value_copy.pop(name.lower(), False) + if is_active: + result |= flag + if value_copy: + raise ValueError(f"Unknown dictionary keys: {value_copy!r}") + return result + + @classmethod + def all(cls) -> "UserAccessPermissions": + return cls((2**32 - 1) - cls.R1 - cls.R2) + + +class Resources: + """ + Table 3.30 Entries in a resource dictionary. + Table 34 in the 2.0 reference. + """ + + EXT_G_STATE = "/ExtGState" # dictionary, optional + COLOR_SPACE = "/ColorSpace" # dictionary, optional + PATTERN = "/Pattern" # dictionary, optional + SHADING = "/Shading" # dictionary, optional + XOBJECT = "/XObject" # dictionary, optional + FONT = "/Font" # dictionary, optional + PROC_SET = "/ProcSet" # array, optional + PROPERTIES = "/Properties" # dictionary, optional + + +class PagesAttributes: + """§7.7.3.2 of the 1.7 and 2.0 reference.""" + + TYPE = "/Type" # name, required; must be /Pages + PARENT = "/Parent" # dictionary, required; indirect reference to pages object + KIDS = "/Kids" # array, required; List of indirect references + COUNT = "/Count" + # integer, required; the number of leaf nodes (page objects) + # that are descendants of this node within the page tree + + +class PageAttributes: + """§7.7.3.3 of the 1.7 and 2.0 reference.""" + + TYPE = "/Type" # name, required; must be /Page + PARENT = "/Parent" # dictionary, required; a pages object + LAST_MODIFIED = ( + "/LastModified" # date, optional; date and time of last modification + ) + RESOURCES = "/Resources" # dictionary, required if there are any + MEDIABOX = "/MediaBox" # rectangle, required; rectangle specifying page size + CROPBOX = "/CropBox" # rectangle, optional + BLEEDBOX = "/BleedBox" # rectangle, optional + TRIMBOX = "/TrimBox" # rectangle, optional + ARTBOX = "/ArtBox" # rectangle, optional + BOX_COLOR_INFO = "/BoxColorInfo" # dictionary, optional + CONTENTS = "/Contents" # stream or array, optional + ROTATE = "/Rotate" # integer, optional; page rotation in degrees + GROUP = "/Group" # dictionary, optional; page group + THUMB = "/Thumb" # stream, optional; indirect reference to image of the page + B = "/B" # array, optional + DUR = "/Dur" # number, optional + TRANS = "/Trans" # dictionary, optional + ANNOTS = "/Annots" # array, optional; an array of annotations + AA = "/AA" # dictionary, optional + METADATA = "/Metadata" # stream, optional + PIECE_INFO = "/PieceInfo" # dictionary, optional + STRUCT_PARENTS = "/StructParents" # integer, optional + ID = "/ID" # byte string, optional + PZ = "/PZ" # number, optional + SEPARATION_INFO = "/SeparationInfo" # dictionary, optional + TABS = "/Tabs" # name, optional + TEMPLATE_INSTANTIATED = "/TemplateInstantiated" # name, optional + PRES_STEPS = "/PresSteps" # dictionary, optional + USER_UNIT = "/UserUnit" # number, optional + VP = "/VP" # dictionary, optional + AF = "/AF" # array of dictionaries, optional + OUTPUT_INTENTS = "/OutputIntents" # array, optional + D_PART = "/DPart" # dictionary, required, if this page is within the range of a DPart, not permitted otherwise + + +class FileSpecificationDictionaryEntries: + """Table 3.41 Entries in a file specification dictionary.""" + + Type = "/Type" + FS = "/FS" # The name of the file system to be used to interpret this file specification + F = "/F" # A file specification string of the form described in §3.10.1 + UF = "/UF" # A Unicode string of the file as described in §3.10.1 + DOS = "/DOS" + Mac = "/Mac" + Unix = "/Unix" + ID = "/ID" + V = "/V" + EF = "/EF" # dictionary, containing a subset of the keys F, UF, DOS, Mac, and Unix + RF = "/RF" # dictionary, containing arrays of /EmbeddedFile + DESC = "/Desc" # description of the file + Cl = "/Cl" + + +class StreamAttributes: + """ + Table 4.2. + Table 5 in the 2.0 reference. + """ + + LENGTH = "/Length" # integer, required + FILTER = "/Filter" # name or array of names, optional + DECODE_PARMS = "/DecodeParms" # variable, optional -- 'decodeParams is wrong + + +@unique +class FilterTypes(StrEnum): + """§7.4 of the 1.7 and 2.0 references.""" + + ASCII_HEX_DECODE = "/ASCIIHexDecode" # abbreviation: AHx + ASCII_85_DECODE = "/ASCII85Decode" # abbreviation: A85 + LZW_DECODE = "/LZWDecode" # abbreviation: LZW + FLATE_DECODE = "/FlateDecode" # abbreviation: Fl + RUN_LENGTH_DECODE = "/RunLengthDecode" # abbreviation: RL + CCITT_FAX_DECODE = "/CCITTFaxDecode" # abbreviation: CCF + DCT_DECODE = "/DCTDecode" # abbreviation: DCT + JPX_DECODE = "/JPXDecode" + JBIG2_DECODE = "/JBIG2Decode" + + +class FilterTypeAbbreviations: + """§8.9.7 of the 1.7 and 2.0 references.""" + + AHx = "/AHx" + A85 = "/A85" + LZW = "/LZW" + FL = "/Fl" + RL = "/RL" + CCF = "/CCF" + DCT = "/DCT" + + +class LzwFilterParameters: + """ + Table 4.4. + Table 8 in the 2.0 reference. + """ + + PREDICTOR = "/Predictor" # integer + COLORS = "/Colors" # integer + BITS_PER_COMPONENT = "/BitsPerComponent" # integer + COLUMNS = "/Columns" # integer + EARLY_CHANGE = "/EarlyChange" # integer + + +class CcittFaxDecodeParameters: + """ + Table 4.5. + Table 11 in the 2.0 reference. + """ + + K = "/K" # integer + END_OF_LINE = "/EndOfLine" # boolean + ENCODED_BYTE_ALIGN = "/EncodedByteAlign" # boolean + COLUMNS = "/Columns" # integer + ROWS = "/Rows" # integer + END_OF_BLOCK = "/EndOfBlock" # boolean + BLACK_IS_1 = "/BlackIs1" # boolean + DAMAGED_ROWS_BEFORE_ERROR = "/DamagedRowsBeforeError" # integer + + +class ImageAttributes: + """§11.6.5 of the 1.7 and 2.0 references.""" + + TYPE = "/Type" # name, required; must be /XObject + SUBTYPE = "/Subtype" # name, required; must be /Image + NAME = "/Name" # name, required + WIDTH = "/Width" # integer, required + HEIGHT = "/Height" # integer, required + BITS_PER_COMPONENT = "/BitsPerComponent" # integer, required + COLOR_SPACE = "/ColorSpace" # name, required + DECODE = "/Decode" # array, optional + INTENT = "/Intent" # string, optional + INTERPOLATE = "/Interpolate" # boolean, optional + IMAGE_MASK = "/ImageMask" # boolean, optional + MASK = "/Mask" # 1-bit image mask stream + S_MASK = "/SMask" # dictionary or name, optional + + +class ColorSpaces: + DEVICE_RGB = "/DeviceRGB" + DEVICE_CMYK = "/DeviceCMYK" + DEVICE_GRAY = "/DeviceGray" + + +class TypArguments: + """Table 8.2 of the PDF 1.7 reference.""" + + LEFT = "/Left" + RIGHT = "/Right" + BOTTOM = "/Bottom" + TOP = "/Top" + + +class TypFitArguments: + """Table 8.2 of the PDF 1.7 reference.""" + + XYZ = "/XYZ" + FIT = "/Fit" + FIT_H = "/FitH" + FIT_V = "/FitV" + FIT_R = "/FitR" + FIT_B = "/FitB" + FIT_BH = "/FitBH" + FIT_BV = "/FitBV" + + +class GoToActionArguments: + S = "/S" # name, required: type of action + D = "/D" # name, byte string, or array, required: destination to jump to + SD = "/SD" # array, optional: structure destination to jump to + + +class AnnotationDictionaryAttributes: + """Table 8.15 Entries common to all annotation dictionaries.""" + + Type = "/Type" + Subtype = "/Subtype" + Rect = "/Rect" + Contents = "/Contents" + P = "/P" + NM = "/NM" + M = "/M" + F = "/F" + AP = "/AP" + AS = "/AS" + DA = "/DA" + Border = "/Border" + C = "/C" + StructParent = "/StructParent" + OC = "/OC" + + +class InteractiveFormDictEntries: + Fields = "/Fields" + NeedAppearances = "/NeedAppearances" + SigFlags = "/SigFlags" + CO = "/CO" + DR = "/DR" + DA = "/DA" + Q = "/Q" + XFA = "/XFA" + + +class FieldDictionaryAttributes: + """ + Entries common to all field dictionaries (Table 8.69 PDF 1.7 reference) + (*very partially documented here*). + + FFBits provides the constants used for `/Ff` from Table 8.70/8.75/8.77/8.79 + """ + + FT = "/FT" # name, required for terminal fields + Parent = "/Parent" # dictionary, required for children + Kids = "/Kids" # array, sometimes required + T = "/T" # text string, optional + TU = "/TU" # text string, optional + TM = "/TM" # text string, optional + Ff = "/Ff" # integer, optional + V = "/V" # text string or array, optional + DV = "/DV" # text string, optional + AA = "/AA" # dictionary, optional + Opt = "/Opt" # array, optional + + class FfBits(IntFlag): + """ + Ease building /Ff flags + Some entries may be specific to: + + * Text (Tx) (Table 8.75 PDF 1.7 reference) + * Buttons (Btn) (Table 8.77 PDF 1.7 reference) + * Choice (Ch) (Table 8.79 PDF 1.7 reference) + """ + + ReadOnly = 1 << 0 + """common to Tx/Btn/Ch in Table 8.70""" + Required = 1 << 1 + """common to Tx/Btn/Ch in Table 8.70""" + NoExport = 1 << 2 + """common to Tx/Btn/Ch in Table 8.70""" + + Multiline = 1 << 12 + """Tx""" + Password = 1 << 13 + """Tx""" + + NoToggleToOff = 1 << 14 + """Btn""" + Radio = 1 << 15 + """Btn""" + Pushbutton = 1 << 16 + """Btn""" + + Combo = 1 << 17 + """Ch""" + Edit = 1 << 18 + """Ch""" + Sort = 1 << 19 + """Ch""" + + FileSelect = 1 << 20 + """Tx""" + + MultiSelect = 1 << 21 + """Tx""" + + DoNotSpellCheck = 1 << 22 + """Tx/Ch""" + DoNotScroll = 1 << 23 + """Tx""" + Comb = 1 << 24 + """Tx""" + + RadiosInUnison = 1 << 25 + """Btn""" + + RichText = 1 << 25 + """Tx""" + + CommitOnSelChange = 1 << 26 + """Ch""" + + @classmethod + def attributes(cls) -> tuple[str, ...]: + """ + Get a tuple of all the attributes present in a Field Dictionary. + + This method returns a tuple of all the attribute constants defined in + the FieldDictionaryAttributes class. These attributes correspond to the + entries that are common to all field dictionaries as specified in the + PDF 1.7 reference. + + Returns: + A tuple containing all the attribute constants. + + """ + return ( + cls.TM, + cls.T, + cls.FT, + cls.Parent, + cls.TU, + cls.Ff, + cls.V, + cls.DV, + cls.Kids, + cls.AA, + ) + + @classmethod + def attributes_dict(cls) -> dict[str, str]: + """ + Get a dictionary of attribute keys and their human-readable names. + + This method returns a dictionary where the keys are the attribute + constants defined in the FieldDictionaryAttributes class and the values + are their corresponding human-readable names. These attributes + correspond to the entries that are common to all field dictionaries as + specified in the PDF 1.7 reference. + + Returns: + A dictionary containing attribute keys and their names. + + """ + return { + cls.FT: "Field Type", + cls.Parent: "Parent", + cls.T: "Field Name", + cls.TU: "Alternate Field Name", + cls.TM: "Mapping Name", + cls.Ff: "Field Flags", + cls.V: "Value", + cls.DV: "Default Value", + } + + +class CheckboxRadioButtonAttributes: + """Table 8.76 Field flags common to all field types.""" + + Opt = "/Opt" # Options, Optional + + @classmethod + def attributes(cls) -> tuple[str, ...]: + """ + Get a tuple of all the attributes present in a Field Dictionary. + + This method returns a tuple of all the attribute constants defined in + the CheckboxRadioButtonAttributes class. These attributes correspond to + the entries that are common to all field dictionaries as specified in + the PDF 1.7 reference. + + Returns: + A tuple containing all the attribute constants. + + """ + return (cls.Opt,) + + @classmethod + def attributes_dict(cls) -> dict[str, str]: + """ + Get a dictionary of attribute keys and their human-readable names. + + This method returns a dictionary where the keys are the attribute + constants defined in the CheckboxRadioButtonAttributes class and the + values are their corresponding human-readable names. These attributes + correspond to the entries that are common to all field dictionaries as + specified in the PDF 1.7 reference. + + Returns: + A dictionary containing attribute keys and their names. + + """ + return { + cls.Opt: "Options", + } + + +class FieldFlag(IntFlag): + """Table 8.70 Field flags common to all field types.""" + + READ_ONLY = 1 + REQUIRED = 2 + NO_EXPORT = 4 + + +class DocumentInformationAttributes: + """Table 10.2 Entries in the document information dictionary.""" + + TITLE = "/Title" # text string, optional + AUTHOR = "/Author" # text string, optional + SUBJECT = "/Subject" # text string, optional + KEYWORDS = "/Keywords" # text string, optional + CREATOR = "/Creator" # text string, optional + PRODUCER = "/Producer" # text string, optional + CREATION_DATE = "/CreationDate" # date, optional + MOD_DATE = "/ModDate" # date, optional + TRAPPED = "/Trapped" # name, optional + + +class PageLayouts: + """ + Page 84, PDF 1.4 reference. + Page 115, PDF 2.0 reference. + """ + + SINGLE_PAGE = "/SinglePage" + ONE_COLUMN = "/OneColumn" + TWO_COLUMN_LEFT = "/TwoColumnLeft" + TWO_COLUMN_RIGHT = "/TwoColumnRight" + TWO_PAGE_LEFT = "/TwoPageLeft" # (PDF 1.5) + TWO_PAGE_RIGHT = "/TwoPageRight" # (PDF 1.5) + + +class GraphicsStateParameters: + """Table 58 – Entries in a Graphics State Parameter Dictionary""" + + TYPE = "/Type" # name, optional + LW = "/LW" # number, optional + LC = "/LC" # integer, optional + LJ = "/LJ" # integer, optional + ML = "/ML" # number, optional + D = "/D" # array, optional + RI = "/RI" # name, optional + OP = "/OP" + op = "/op" + OPM = "/OPM" + FONT = "/Font" # array, optional + BG = "/BG" + BG2 = "/BG2" + UCR = "/UCR" + UCR2 = "/UCR2" + TR = "/TR" + TR2 = "/TR2" + HT = "/HT" + FL = "/FL" + SM = "/SM" + SA = "/SA" + BM = "/BM" + S_MASK = "/SMask" # dictionary or name, optional + CA = "/CA" + ca = "/ca" + AIS = "/AIS" + TK = "/TK" + + +class CatalogDictionary: + """§7.7.2 of the 1.7 and 2.0 references.""" + + TYPE = "/Type" # name, required; must be /Catalog + VERSION = "/Version" # name + EXTENSIONS = "/Extensions" # dictionary, optional; ISO 32000-1 + PAGES = "/Pages" # dictionary, required + PAGE_LABELS = "/PageLabels" # number tree, optional + NAMES = "/Names" # dictionary, optional + DESTS = "/Dests" # dictionary, optional + VIEWER_PREFERENCES = "/ViewerPreferences" # dictionary, optional + PAGE_LAYOUT = "/PageLayout" # name, optional + PAGE_MODE = "/PageMode" # name, optional + OUTLINES = "/Outlines" # dictionary, optional + THREADS = "/Threads" # array, optional + OPEN_ACTION = "/OpenAction" # array or dictionary or name, optional + AA = "/AA" # dictionary, optional + URI = "/URI" # dictionary, optional + ACRO_FORM = "/AcroForm" # dictionary, optional + METADATA = "/Metadata" # stream, optional + STRUCT_TREE_ROOT = "/StructTreeRoot" # dictionary, optional + MARK_INFO = "/MarkInfo" # dictionary, optional + LANG = "/Lang" # text string, optional + SPIDER_INFO = "/SpiderInfo" # dictionary, optional + OUTPUT_INTENTS = "/OutputIntents" # array, optional + PIECE_INFO = "/PieceInfo" # dictionary, optional + OC_PROPERTIES = "/OCProperties" # dictionary, optional + PERMS = "/Perms" # dictionary, optional + LEGAL = "/Legal" # dictionary, optional + REQUIREMENTS = "/Requirements" # array, optional + COLLECTION = "/Collection" # dictionary, optional + NEEDS_RENDERING = "/NeedsRendering" # boolean, optional + DSS = "/DSS" # dictionary, optional + AF = "/AF" # array of dictionaries, optional + D_PART_ROOT = "/DPartRoot" # dictionary, optional + + +class OutlineFontFlag(IntFlag): + """A class used as an enumerable flag for formatting an outline font.""" + + italic = 1 + bold = 2 + + +class PageLabelStyle: + """ + Table 8.10 in the 1.7 reference. + Table 161 in the 2.0 reference. + """ + + DECIMAL = "/D" # Decimal Arabic numerals + UPPERCASE_ROMAN = "/R" # Uppercase Roman numerals + LOWERCASE_ROMAN = "/r" # Lowercase Roman numerals + UPPERCASE_LETTER = "/A" # Uppercase letters + LOWERCASE_LETTER = "/a" # Lowercase letters + + +class AnnotationFlag(IntFlag): + """See §12.5.3 "Annotation Flags".""" + + INVISIBLE = 1 + HIDDEN = 2 + PRINT = 4 + NO_ZOOM = 8 + NO_ROTATE = 16 + NO_VIEW = 32 + READ_ONLY = 64 + LOCKED = 128 + TOGGLE_NO_VIEW = 256 + LOCKED_CONTENTS = 512 + + +PDF_KEYS = ( + AnnotationDictionaryAttributes, + CatalogAttributes, + CatalogDictionary, + CcittFaxDecodeParameters, + CheckboxRadioButtonAttributes, + ColorSpaces, + Core, + DocumentInformationAttributes, + EncryptionDictAttributes, + FieldDictionaryAttributes, + FileSpecificationDictionaryEntries, + FilterTypeAbbreviations, + FilterTypes, + GoToActionArguments, + GraphicsStateParameters, + ImageAttributes, + InteractiveFormDictEntries, + LzwFilterParameters, + PageAttributes, + PageLayouts, + PagesAttributes, + Resources, + StreamAttributes, + TrailerKeys, + TypArguments, + TypFitArguments, +) + + +class ImageType(IntFlag): + NONE = 0 + XOBJECT_IMAGES = auto() + INLINE_IMAGES = auto() + DRAWING_IMAGES = auto() + ALL = XOBJECT_IMAGES | INLINE_IMAGES | DRAWING_IMAGES + IMAGES = ALL # for consistency with ObjectDeletionFlag + + +_INLINE_IMAGE_VALUE_MAPPING = { + "/G": "/DeviceGray", + "/RGB": "/DeviceRGB", + "/CMYK": "/DeviceCMYK", + "/I": "/Indexed", + "/AHx": "/ASCIIHexDecode", + "/A85": "/ASCII85Decode", + "/LZW": "/LZWDecode", + "/Fl": "/FlateDecode", + "/RL": "/RunLengthDecode", + "/CCF": "/CCITTFaxDecode", + "/DCT": "/DCTDecode", + "/DeviceGray": "/DeviceGray", + "/DeviceRGB": "/DeviceRGB", + "/DeviceCMYK": "/DeviceCMYK", + "/Indexed": "/Indexed", + "/ASCIIHexDecode": "/ASCIIHexDecode", + "/ASCII85Decode": "/ASCII85Decode", + "/LZWDecode": "/LZWDecode", + "/FlateDecode": "/FlateDecode", + "/RunLengthDecode": "/RunLengthDecode", + "/CCITTFaxDecode": "/CCITTFaxDecode", + "/DCTDecode": "/DCTDecode", + "/RelativeColorimetric": "/RelativeColorimetric", +} + +_INLINE_IMAGE_KEY_MAPPING = { + "/BPC": "/BitsPerComponent", + "/CS": "/ColorSpace", + "/D": "/Decode", + "/DP": "/DecodeParms", + "/F": "/Filter", + "/H": "/Height", + "/W": "/Width", + "/I": "/Interpolate", + "/Intent": "/Intent", + "/IM": "/ImageMask", + "/BitsPerComponent": "/BitsPerComponent", + "/ColorSpace": "/ColorSpace", + "/Decode": "/Decode", + "/DecodeParms": "/DecodeParms", + "/Filter": "/Filter", + "/Height": "/Height", + "/Width": "/Width", + "/Interpolate": "/Interpolate", + "/ImageMask": "/ImageMask", +} + + +class AFRelationship: + """ + Associated file relationship types, defining the relationship between + the PDF component and the associated file. + + Defined in table 43 of the PDF 2.0 reference. + """ + + SOURCE = "/Source" # Original content source + DATA = "/Data" # Base data for visual presentation + ALTERNATIVE = "/Alternative" # Alternative content representation + SUPPLEMENT = "/Supplement" # Supplemental representation of original source/data + ENCRYPTED_PAYLOAD = "/EncryptedPayload" # Encrypted payload document + FORM_DATA = "/FormData" # Data associated with AcroForm of this PDF + SCHEMA = "/Schema" # Schema definition for associated object + UNSPECIFIED = "/Unspecified" # Not known or cannot be described with values + + +class BorderStyles: + """ + A class defining border styles used in PDF documents. + + Defined in table 168 of the PDF 2.0 reference. + """ + + BEVELED = "/B" + DASHED = "/D" + INSET = "/I" + SOLID = "/S" + UNDERLINED = "/U" + + +class FontFlags(IntFlag): + """ + A class defining font flags in PDF document font descriptor resources. + + Defined in table 121 of the PDF 2.0 reference. + """ + + FIXED_PITCH = 1 << 0 + SERIF = 1 << 1 + SYMBOLIC = 1 << 2 + SCRIPT = 1 << 3 + NONSYMBOLIC = 1 << 5 + ITALIC = 1 << 6 + ALL_CAP = 1 << 16 + SMALL_CAP = 1 << 17 + FORCE_BOLD = 1 << 18 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/errors.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..8fec6e13a279b9de013e41c91890d91873fbf1da --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/errors.py @@ -0,0 +1,74 @@ +""" +All errors/exceptions pypdf raises and all of the warnings it uses. + +Please note that broken PDF files might cause other Exceptions. +""" + + +class DeprecationError(Exception): + """Raised when a deprecated feature is used.""" + + +class DependencyError(Exception): + """ + Raised when a required dependency (a library or module that pypdf depends on) + is not available or cannot be imported. + """ + + +class PyPdfError(Exception): + """Base class for all exceptions raised by pypdf.""" + + +class PdfReadError(PyPdfError): + """Raised when there is an issue reading a PDF file.""" + + +class PageSizeNotDefinedError(PyPdfError): + """Raised when the page size of a PDF document is not defined.""" + + +class PdfReadWarning(UserWarning): + """Issued when there is a potential issue reading a PDF file, but it can still be read.""" + + +class PdfStreamError(PdfReadError): + """Raised when there is an issue reading the stream of data in a PDF file.""" + + +class ParseError(PyPdfError): + """ + Raised when there is an issue parsing (analyzing and understanding the + structure and meaning of) a PDF file. + """ + + +class FileNotDecryptedError(PdfReadError): + """ + Raised when a PDF file that has been encrypted + (meaning it requires a password to be accessed) has not been successfully + decrypted. + """ + + +class WrongPasswordError(FileNotDecryptedError): + """Raised when the wrong password is used to try to decrypt an encrypted PDF file.""" + + +class EmptyFileError(PdfReadError): + """Raised when a PDF file is empty or has no content.""" + + +class EmptyImageDataError(PyPdfError): + """Raised when trying to process an image that has no data.""" + + +STREAM_TRUNCATED_PREMATURELY = "Stream has ended unexpectedly" + + +class LimitReachedError(PyPdfError): + """Raised when a limit is reached.""" + + +class XmpDocumentError(PyPdfError, RuntimeError): + """Raised when the XMP XML document context is invalid or missing.""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/filters.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/filters.py new file mode 100644 index 0000000000000000000000000000000000000000..27c573d5c4820b75cbebc432a88f8a9be26973a8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/filters.py @@ -0,0 +1,857 @@ +# Copyright (c) 2006, Mathieu Fenniak +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * The name of the author may not be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + + +""" +Implementation of stream filters; §7.4 Filters of the PDF 2.0 specification. + +§8.9.7 Inline images of the PDF 2.0 specification has abbreviations that can be +used for the names of filters in an inline image object. +""" +__author__ = "Mathieu Fenniak" +__author_email__ = "biziqe@mathieu.fenniak.net" + +import binascii +import math +import os +import shutil +import struct +import subprocess +import zlib +from base64 import a85decode +from dataclasses import dataclass +from pathlib import Path +from tempfile import TemporaryDirectory +from typing import Any, Optional, Union, cast + +from ._codecs._codecs import LzwCodec as _LzwCodec +from ._utils import ( + WHITESPACES_AS_BYTES, + deprecate, + deprecation_with_replacement, + logger_warning, +) +from .constants import CcittFaxDecodeParameters as CCITT +from .constants import FilterTypeAbbreviations as FTA +from .constants import FilterTypes as FT +from .constants import ImageAttributes, StreamAttributes +from .constants import LzwFilterParameters as LZW +from .errors import DependencyError, LimitReachedError, PdfReadError, PdfStreamError +from .generic import ( + ArrayObject, + DictionaryObject, + IndirectObject, + NullObject, + NumberObject, + StreamObject, + is_null_or_none, +) + +MAX_DECLARED_STREAM_LENGTH = 75_000_000 +MAX_ARRAY_BASED_STREAM_OUTPUT_LENGTH = 75_000_000 + +JBIG2_MAX_OUTPUT_LENGTH = 75_000_000 +LZW_MAX_OUTPUT_LENGTH = 75_000_000 +RUN_LENGTH_MAX_OUTPUT_LENGTH = 75_000_000 +ZLIB_MAX_OUTPUT_LENGTH = 75_000_000 +ZLIB_MAX_RECOVERY_INPUT_LENGTH = 5_000_000 +FLATE_MAX_COLUMNS = 250_000 +FLATE_MAX_ROW_LENGTH = 4_000_000 +FLATE_MAX_BUFFER_SIZE = 75_000_000 + +# Reuse cached 1-byte values in the fallback loop to avoid per-byte allocations. +_SINGLE_BYTES = tuple(bytes((i,)) for i in range(256)) + + +def _decompress_with_limit(data: bytes) -> bytes: + decompressor = zlib.decompressobj() + result = decompressor.decompress(data, max_length=ZLIB_MAX_OUTPUT_LENGTH) + if decompressor.unconsumed_tail: + raise LimitReachedError( + f"Limit reached while decompressing. {len(decompressor.unconsumed_tail)} bytes remaining." + ) + return result + + +def decompress(data: bytes) -> bytes: + """ + Decompress the given data using zlib. + + Attempts to decompress the input data using zlib. + If the decompression fails due to a zlib error, it falls back + to using a decompression object with a larger window size. + + Please note that the output length is limited to avoid memory + issues. If you need to process larger content streams, consider + adapting ``pypdf.filters.ZLIB_MAX_OUTPUT_LENGTH``. In case you + are only dealing with trusted inputs and/or want to disable these + limits, set the value to `0`. + + Args: + data: The input data to be decompressed. + + Returns: + The decompressed data. + + """ + try: + return _decompress_with_limit(data) + except zlib.error: + # First quick approach: There are known issues with faulty added bytes to the + # tail of the encoded stream from early Adobe Distiller or Pitstop versions + # with CR char as the default line separator (assumed by reverse engineering) + # that breaks the decoding process in the end. + # + # Try first to cut off some of the tail byte by byte, but limited to not + # iterate through too many loops and kill the performance for large streams, + # to then allow the final fallback to run. Added this intermediate attempt, + # because starting from the head of the stream byte by byte kills completely + # the performance for large streams (e.g., 6 MB) with the tail-byte-issue + # and takes ages. This solution is really fast: + max_tail_cut_off_bytes: int = 8 + for i in range(1, min(max_tail_cut_off_bytes + 1, len(data))): + try: + return _decompress_with_limit(data[:-i]) + except zlib.error: + pass + + # If still failing, then try with increased window size. + decompressor = zlib.decompressobj(zlib.MAX_WBITS | 32) + result_str = b"" + remaining_limit = ZLIB_MAX_OUTPUT_LENGTH + data_length = len(data) + known_errors = set() + for index in range(data_length): + chunk = _SINGLE_BYTES[data[index]] + try: + decompressed = decompressor.decompress(chunk, max_length=remaining_limit) + result_str += decompressed + remaining_limit -= len(decompressed) + if remaining_limit <= 0: + raise LimitReachedError( + f"Limit reached while decompressing. {data_length - index} bytes remaining." + ) + except zlib.error as error: + if index > ZLIB_MAX_RECOVERY_INPUT_LENGTH: + raise LimitReachedError( + f"Recovery limit reached while decompressing. {data_length - index} bytes remaining." + ) + error_str = str(error) + if error_str in known_errors: + continue + logger_warning(error_str, __name__) + known_errors.add(error_str) + return result_str + + +class FlateDecode: + @staticmethod + def decode( + data: bytes, + decode_parms: Optional[DictionaryObject] = None, + **kwargs: Any, + ) -> bytes: + """ + Decode data which is flate-encoded. + + Args: + data: Flate-encoded data. + decode_parms: Additional decoding parameters. + + Returns: + The flate-decoded data. + + Raises: + PdfReadError: Unsupported parameters have been found. + + """ + str_data = decompress(data) + + if isinstance(decode_parms, DictionaryObject): + parameters = decode_parms + else: + parameters = DictionaryObject() + + predictor = parameters.get("/Predictor", 1) + + # predictor 1 == no predictor + if predictor != 1: + columns, colors, bits_per_component = FlateDecode._get_parameters(parameters) + + # PNG predictor can vary by row and so is the lead byte on each row + row_length = ( + math.ceil(columns * colors * bits_per_component / 8) + 1 + ) # number of bytes + if row_length > FLATE_MAX_ROW_LENGTH: + raise LimitReachedError( + f"Row length of {row_length} exceeds defined limit of {FLATE_MAX_ROW_LENGTH}." + ) + + # TIFF prediction: + if predictor == 2: + row_length -= 1 # remove the predictor byte + bpp = row_length // columns + str_data_mut = bytearray(str_data) + for i in range(len(str_data_mut)): + if i % row_length >= bpp: + str_data_mut[i] = (str_data_mut[i] + str_data_mut[i - bpp]) % 256 + str_data = bytes(str_data_mut) + # PNG prediction: + elif 10 <= predictor <= 15: + str_data = FlateDecode._decode_png_prediction( + str_data, columns, row_length + ) + else: + raise PdfReadError(f"Unsupported flatedecode predictor {predictor!r}") + return str_data + + @staticmethod + def _get_parameters(parameters: DictionaryObject) -> tuple[int, int, int]: + # For details, see table 8 of ISO 32000-2:2020. + def get(key: str, default: int) -> int: + _value = parameters.get(key, NumberObject(default)).get_object() + if not isinstance(_value, int) or _value < 1: + raise PdfReadError(f"Expected positive number for {key}, got {_value}!") + return _value + + columns = get(key=LZW.COLUMNS, default=1) + if columns > FLATE_MAX_COLUMNS: + raise LimitReachedError(f"Number of columns {columns} exceeds defined limit of {FLATE_MAX_COLUMNS}.") + + colors = get(key=LZW.COLORS, default=1) + if colors > 16: + raise LimitReachedError( + f"Color value {colors} exceeds limit of 16. " + f"Please open an issue if this limits valid use cases." + ) + + bits_per_component = get(key=LZW.BITS_PER_COMPONENT, default=8) + if bits_per_component > 16: + raise PdfReadError(f"More than 16 bits per component are not allowed: {bits_per_component}") + + return columns, colors, bits_per_component + + @staticmethod + def _decode_png_prediction(data: bytes, columns: int, row_length: int) -> bytes: + # PNG prediction can vary from row to row + if (remainder := len(data) % row_length) != 0: + logger_warning("Image data is not rectangular. Adding padding.", __name__) + data += b"\x00" * (row_length - remainder) + assert len(data) % row_length == 0 + output = [] + previous_row_data = (0,) * row_length + bpp = (row_length - 1) // columns # recomputed locally to not change params + for row in range(0, len(data), row_length): + row_data: list[int] = list(data[row : row + row_length]) + filter_byte = row_data[0] + + if filter_byte == 0: + # PNG None Predictor + pass + elif filter_byte == 1: + # PNG Sub Predictor + for i in range(bpp + 1, row_length): + row_data[i] = (row_data[i] + row_data[i - bpp]) % 256 + elif filter_byte == 2: + # PNG Up Predictor + for i in range(1, row_length): + row_data[i] = (row_data[i] + previous_row_data[i]) % 256 + elif filter_byte == 3: + # PNG Average Predictor + for i in range(1, bpp + 1): + floor = previous_row_data[i] // 2 + row_data[i] = (row_data[i] + floor) % 256 + for i in range(bpp + 1, row_length): + left = row_data[i - bpp] + floor = (left + previous_row_data[i]) // 2 + row_data[i] = (row_data[i] + floor) % 256 + elif filter_byte == 4: + # PNG Paeth Predictor + for i in range(1, bpp + 1): + row_data[i] = (row_data[i] + previous_row_data[i]) % 256 + for i in range(bpp + 1, row_length): + left = row_data[i - bpp] + up = previous_row_data[i] + up_left = previous_row_data[i - bpp] + + p = left + up - up_left + dist_left = abs(p - left) + dist_up = abs(p - up) + dist_up_left = abs(p - up_left) + + if dist_left <= dist_up and dist_left <= dist_up_left: + paeth = left + elif dist_up <= dist_up_left: + paeth = up + else: + paeth = up_left + + row_data[i] = (row_data[i] + paeth) % 256 + else: + raise PdfReadError( + f"Unsupported PNG filter {filter_byte!r}" + ) # pragma: no cover + previous_row_data = tuple(row_data) + output.extend(row_data[1:]) + return bytes(output) + + @staticmethod + def encode(data: bytes, level: int = -1) -> bytes: + """ + Compress the input data using zlib. + + Args: + data: The data to be compressed. + level: See https://docs.python.org/3/library/zlib.html#zlib.compress + + Returns: + The compressed data. + + """ + return zlib.compress(data, level) + + +class ASCIIHexDecode: + """ + The ASCIIHexDecode filter decodes data that has been encoded in ASCII + hexadecimal form into a base-7 ASCII format. + """ + + @staticmethod + def decode( + data: Union[str, bytes], + decode_parms: Optional[DictionaryObject] = None, + **kwargs: Any, + ) -> bytes: + """ + Decode an ASCII-Hex encoded data stream. + + Args: + data: a str sequence of hexadecimal-encoded values to be + converted into a base-7 ASCII string + decode_parms: this filter does not use parameters. + + Returns: + A string conversion in base-7 ASCII, where each of its values + v is such that 0 <= ord(v) <= 127. + + Raises: + PdfStreamError: + + """ + if isinstance(data, str): + data = data.encode() + + # Stop at EOD + eod = data.find(b">") + if eod == -1: + logger_warning( + "missing EOD in ASCIIHexDecode, check if output is OK", + __name__, + ) + hex_data = data + else: + hex_data = data[:eod] + + # Remove whitespace + hex_data = b"".join(hex_data.split()) + + # Pad if odd length + if len(hex_data) % 2 == 1: + hex_data += b"0" + + return binascii.unhexlify(hex_data) + + +class RunLengthDecode: + """ + The RunLengthDecode filter decodes data that has been encoded in a + simple byte-oriented format based on run length. + The encoded data is a sequence of runs, where each run consists of + a length byte followed by 1 to 128 bytes of data. If the length byte is + in the range 0 to 127, + the following length + 1 (1 to 128) bytes are copied literally during + decompression. + If length is in the range 129 to 255, the following single byte is to be + copied 257 − length (2 to 128) times during decompression. A length value + of 128 denotes EOD. + """ + + @staticmethod + def decode( + data: bytes, + decode_parms: Optional[DictionaryObject] = None, + **kwargs: Any, + ) -> bytes: + """ + Decode a run length encoded data stream. + + Args: + data: a bytes sequence of length/data + decode_parms: this filter does not use parameters. + + Returns: + A bytes decompressed sequence. + + Raises: + PdfStreamError: + + """ + lst = [] + index = 0 + data_length = len(data) + total_length = 0 + while True: + if index >= data_length: + logger_warning( + "missing EOD in RunLengthDecode, check if output is OK", __name__ + ) + break # Reached end of string without an EOD + length = data[index] + index += 1 + if length == 128: + if index < data_length: + # We should first check, if we have an inner stream from a multi-encoded + # stream with a faulty trailing newline that we can decode properly. + # We will just ignore the last byte and raise a warning ... + if (index == data_length - 1) and (data[index : index + 1] == b"\n"): + logger_warning( + "Found trailing newline in stream data, check if output is OK", __name__ + ) + break + # Raising an exception here breaks all image extraction for this file, which might + # not be desirable. For this reason, indicate that the output is most likely wrong, + # as processing stopped after the first EOD marker. See issue #3517. + logger_warning( + "Early EOD in RunLengthDecode, check if output is OK", __name__ + ) + break + if length < 128: + length += 1 + lst.append(data[index : (index + length)]) + index += length + else: # >128 + length = 257 - length + lst.append(bytes((data[index],)) * length) + index += 1 + total_length += length + if total_length > RUN_LENGTH_MAX_OUTPUT_LENGTH: + raise LimitReachedError("Limit reached while decompressing.") + return b"".join(lst) + + +class LZWDecode: + class Decoder: + STOP = 257 + CLEARDICT = 256 + + def __init__(self, data: bytes) -> None: + self.data = data + + def decode(self) -> bytes: + return _LzwCodec(max_output_length=LZW_MAX_OUTPUT_LENGTH).decode(self.data) + + @staticmethod + def decode( + data: bytes, + decode_parms: Optional[DictionaryObject] = None, + **kwargs: Any, + ) -> bytes: + """ + Decode an LZW encoded data stream. + + Args: + data: ``bytes`` or ``str`` text to decode. + decode_parms: a dictionary of parameter values. + + Returns: + decoded data. + + """ + # decode_parms is unused here + return LZWDecode.Decoder(data).decode() + + +class ASCII85Decode: + """Decodes string ASCII85-encoded data into a byte format.""" + + @staticmethod + def decode( + data: Union[str, bytes], + decode_parms: Optional[DictionaryObject] = None, + **kwargs: Any, + ) -> bytes: + """ + Decode an Ascii85 encoded data stream. + + Args: + data: ``bytes`` or ``str`` text to decode. + decode_parms: this filter does not use parameters. + + Returns: + decoded data. + + """ + if isinstance(data, str): + data = data.encode() + data = data.strip(WHITESPACES_AS_BYTES) + if len(data) > 2 and data.endswith(b">"): + data = data[:-1].rstrip(WHITESPACES_AS_BYTES) + data[-1:] + try: + return a85decode(data, adobe=True, ignorechars=WHITESPACES_AS_BYTES) + except ValueError as error: + if error.args[0] == "Ascii85 encoded byte sequences must end with b'~>'": + logger_warning("Ignoring missing Ascii85 end marker.", __name__) + return a85decode(data, adobe=False, ignorechars=WHITESPACES_AS_BYTES) + raise + + +class DCTDecode: + @staticmethod + def decode( + data: bytes, + decode_parms: Optional[DictionaryObject] = None, + **kwargs: Any, + ) -> bytes: + """ + Decompresses data encoded using a DCT (discrete cosine transform) + technique based on the JPEG standard (IS0/IEC 10918), + reproducing image sample data that approximates the original data. + + Args: + data: text to decode. + decode_parms: this filter does not use parameters. + + Returns: + decoded data. + + """ + return data + + +class JPXDecode: + @staticmethod + def decode( + data: bytes, + decode_parms: Optional[DictionaryObject] = None, + **kwargs: Any, + ) -> bytes: + """ + Decompresses data encoded using the wavelet-based JPEG 2000 standard, + reproducing the original image data. + + Args: + data: text to decode. + decode_parms: this filter does not use parameters. + + Returns: + decoded data. + + """ + return data + + +@dataclass +class CCITTParameters: + """§7.4.6, optional parameters for the CCITTFaxDecode filter.""" + + K: int = 0 + columns: int = 1728 + rows: int = 0 + EndOfLine: Union[bool, None] = False + EncodedByteAlign: Union[bool, None] = False + EndOfBlock: Union[bool, None] = True + BlackIs1: bool = False + DamagedRowsBeforeError: Union[int, None] = 0 + + @property + def group(self) -> int: + if self.K < 0: + # Pure two-dimensional encoding (Group 4) + CCITTgroup = 4 + else: + # K == 0: Pure one-dimensional encoding (Group 3, 1-D) + # K > 0: Mixed one- and two-dimensional encoding (Group 3, 2-D) + CCITTgroup = 3 + return CCITTgroup + + +def __create_old_class_instance( + K: int = 0, + columns: int = 0, + rows: int = 0 +) -> CCITTParameters: + deprecation_with_replacement("CCITParameters", "CCITTParameters", "6.0.0") + return CCITTParameters(K, columns, rows) + + +# Create an alias for the old class name +CCITParameters = __create_old_class_instance + + +class CCITTFaxDecode: + """ + §7.4.6, CCITTFaxDecode filter (ISO 32000). + + Either Group 3 or Group 4 CCITT facsimile (fax) encoding. + CCITT encoding is bit-oriented, not byte-oriented. + + §7.4.6, optional parameters for the CCITTFaxDecode filter. + """ + + @staticmethod + def _get_parameters( + parameters: Union[None, ArrayObject, DictionaryObject, IndirectObject], + rows: Union[int, IndirectObject], + ) -> CCITTParameters: + ccitt_parameters = CCITTParameters(rows=int(rows)) + if parameters: + parameters_unwrapped = cast( + Union[ArrayObject, DictionaryObject], parameters.get_object() + ) + if isinstance(parameters_unwrapped, ArrayObject): + for decode_parm in parameters_unwrapped: + if CCITT.K in decode_parm: + ccitt_parameters.K = decode_parm[CCITT.K].get_object() + if CCITT.COLUMNS in decode_parm: + ccitt_parameters.columns = decode_parm[CCITT.COLUMNS].get_object() + if CCITT.BLACK_IS_1 in decode_parm: + ccitt_parameters.BlackIs1 = decode_parm[CCITT.BLACK_IS_1].get_object().value + else: + if CCITT.K in parameters_unwrapped: + ccitt_parameters.K = parameters_unwrapped[CCITT.K].get_object() # type: ignore + if CCITT.COLUMNS in parameters_unwrapped: + ccitt_parameters.columns = parameters_unwrapped[CCITT.COLUMNS].get_object() # type: ignore + if CCITT.BLACK_IS_1 in parameters_unwrapped: + ccitt_parameters.BlackIs1 = parameters_unwrapped[CCITT.BLACK_IS_1].get_object().value # type: ignore + return ccitt_parameters + + @staticmethod + def decode( + data: bytes, + decode_parms: Optional[DictionaryObject] = None, + height: int = 0, + **kwargs: Any, + ) -> bytes: + params = CCITTFaxDecode._get_parameters(decode_parms, height) + + img_size = len(data) + tiff_header_struct = "<2shlh" + "hhll" * 8 + "h" + tiff_header = struct.pack( + tiff_header_struct, + b"II", # Byte order indication: Little endian + 42, # Version number (always 42) + 8, # Offset to the first image file directory (IFD) + 8, # Number of tags in IFD + 256, # ImageWidth, LONG, 1, width + 4, + 1, + params.columns, + 257, # ImageLength, LONG, 1, length + 4, + 1, + params.rows, + 258, # BitsPerSample, SHORT, 1, 1 + 3, + 1, + 1, + 259, # Compression, SHORT, 1, compression Type + 3, + 1, + params.group, + 262, # Thresholding, SHORT, 1, 0 = BlackIs1 + 3, + 1, + int(params.BlackIs1), + 273, # StripOffsets, LONG, 1, length of header + 4, + 1, + struct.calcsize( + tiff_header_struct + ), + 278, # RowsPerStrip, LONG, 1, length + 4, + 1, + params.rows, + 279, # StripByteCounts, LONG, 1, size of image + 4, + 1, + img_size, + 0, # last IFD + ) + + return tiff_header + data + + +JBIG2DEC_BINARY = shutil.which("jbig2dec") + + +class JBIG2Decode: + @staticmethod + def decode( + data: bytes, + decode_parms: Optional[DictionaryObject] = None, + **kwargs: Any, + ) -> bytes: + if JBIG2DEC_BINARY is None: + raise DependencyError("jbig2dec binary is not available.") + + with TemporaryDirectory() as tempdir: + directory = Path(tempdir) + paths: list[Path] = [] + + if decode_parms and "/JBIG2Globals" in decode_parms: + jbig2_globals = decode_parms["/JBIG2Globals"] + if not is_null_or_none(jbig2_globals) and not is_null_or_none(pointer := jbig2_globals.get_object()): + assert pointer is not None, "mypy" + if isinstance(pointer, StreamObject): + path = directory.joinpath("globals.jbig2") + path.write_bytes(pointer.get_data()) + paths.append(path) + + path = directory.joinpath("image.jbig2") + path.write_bytes(data) + paths.append(path) + + environment = os.environ.copy() + environment["LC_ALL"] = "C" + result = subprocess.run( # noqa: S603 + [ + JBIG2DEC_BINARY, + "--embedded", + "--format", "png", + "--output", "-", + "-M", str(JBIG2_MAX_OUTPUT_LENGTH), + *paths + ], + capture_output=True, + env=environment, + ) + if b"unrecognized option '--embedded'" in result.stderr or b"unrecognized option '-M'" in result.stderr: + raise DependencyError("jbig2dec>=0.19 is required.") + if b"FATAL ERROR failed to allocate image data buffer" in result.stderr: + raise LimitReachedError( + f"Memory limit reached while reading JBIG2 data:\n{result.stderr.decode('utf-8')}" + ) + if result.stderr: + for line in result.stderr.decode("utf-8").splitlines(): + logger_warning(line, __name__) + if result.returncode != 0: + raise PdfStreamError(f"Unable to decode JBIG2 data. Exit code: {result.returncode}") + return result.stdout + + @staticmethod + def _is_binary_compatible() -> bool: + if not JBIG2DEC_BINARY: # pragma: no cover + return False + result = subprocess.run( # noqa: S603 + [JBIG2DEC_BINARY, "--version"], + capture_output=True, + text=True, + ) + version = result.stdout.split(" ", maxsplit=1)[1] + + from ._utils import Version # noqa: PLC0415 + return Version(version) >= Version("0.19") + + +def _deprecate_inline_image_filters(filter_name: str, old_name: str, new_name: str) -> None: + if filter_name != old_name: + return + deprecate( + f"The filter name {old_name} is deprecated and will be removed in pypdf 7.0.0. Use {new_name} instead.", + 4, + ) + + +def decode_stream_data(stream: StreamObject) -> bytes: + """ + Decode the stream data based on the specified filters. + + This function decodes the stream data using the filters provided in the + stream. + + Args: + stream: The input stream object containing the data and filters. + + Returns: + The decoded stream data. + + Raises: + NotImplementedError: If an unsupported filter type is encountered. + + """ + filters = stream.get(StreamAttributes.FILTER, ()) + if isinstance(filters, IndirectObject): + filters = cast(ArrayObject, filters.get_object()) + if not isinstance(filters, ArrayObject): + # We have a single filter instance + filters = (filters,) + decode_parms = stream.get(StreamAttributes.DECODE_PARMS, ({},) * len(filters)) + if not isinstance(decode_parms, (list, tuple)): + decode_parms = (decode_parms,) + data: bytes = stream._data + # If there is no data to decode, we should not try to decode it. + if not data: + return data + for filter_name, params in zip(filters, decode_parms): + if isinstance(params, NullObject): + params = {} + if filter_name in (FT.ASCII_HEX_DECODE, FTA.AHx): + _deprecate_inline_image_filters(filter_name=filter_name, old_name=FTA.AHx, new_name=FT.ASCII_HEX_DECODE) + data = ASCIIHexDecode.decode(data) + elif filter_name in (FT.ASCII_85_DECODE, FTA.A85): + _deprecate_inline_image_filters(filter_name=filter_name, old_name=FTA.A85, new_name=FT.ASCII_85_DECODE) + data = ASCII85Decode.decode(data) + elif filter_name in (FT.LZW_DECODE, FTA.LZW): + _deprecate_inline_image_filters(filter_name=filter_name, old_name=FTA.LZW, new_name=FT.LZW_DECODE) + data = LZWDecode.decode(data, params) + elif filter_name in (FT.FLATE_DECODE, FTA.FL): + _deprecate_inline_image_filters(filter_name=filter_name, old_name=FTA.FL, new_name=FT.FLATE_DECODE) + data = FlateDecode.decode(data, params) + elif filter_name in (FT.RUN_LENGTH_DECODE, FTA.RL): + _deprecate_inline_image_filters(filter_name=filter_name, old_name=FTA.RL, new_name=FT.RUN_LENGTH_DECODE) + data = RunLengthDecode.decode(data) + elif filter_name in (FT.CCITT_FAX_DECODE, FTA.CCF): + _deprecate_inline_image_filters(filter_name=filter_name, old_name=FTA.CCF, new_name=FT.CCITT_FAX_DECODE) + height = stream.get(ImageAttributes.HEIGHT, ()) + data = CCITTFaxDecode.decode(data, params, height) + elif filter_name in (FT.DCT_DECODE, FTA.DCT): + _deprecate_inline_image_filters(filter_name=filter_name, old_name=FTA.DCT, new_name=FT.DCT_DECODE) + data = DCTDecode.decode(data) + elif filter_name == FT.JPX_DECODE: + data = JPXDecode.decode(data) + elif filter_name == FT.JBIG2_DECODE: + data = JBIG2Decode.decode(data, params) + elif filter_name == "/Crypt": + if "/Name" in params or "/Type" in params: + raise NotImplementedError( + "/Crypt filter with /Name or /Type not supported yet" + ) + else: + raise NotImplementedError(f"Unsupported filter {filter_name}") + return data diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/generic/__pycache__/_appearance_stream.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/generic/__pycache__/_appearance_stream.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27b0ce4c010390025208ab8e36774d7d6ed17103 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/generic/__pycache__/_appearance_stream.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/generic/__pycache__/_base.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/generic/__pycache__/_base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..babab834a410c30f5997610399b43c9de2d7c1f1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/generic/__pycache__/_base.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/pagerange.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/pagerange.py new file mode 100644 index 0000000000000000000000000000000000000000..2ff4613f2de87f964c22edeef4028bdeb28e50d8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/pagerange.py @@ -0,0 +1,200 @@ +""" +Representation and utils for ranges of PDF file pages. + +Copyright (c) 2014, Steve Witham . +All rights reserved. This software is available under a BSD license; +see https://github.com/py-pdf/pypdf/blob/main/LICENSE +""" + +import re +from typing import Any, Union + +from .errors import ParseError + +_INT_RE = r"(0|-?[1-9]\d*)" # A decimal int, don't allow "-0". +PAGE_RANGE_RE = f"^({_INT_RE}|({_INT_RE}?(:{_INT_RE}?(:{_INT_RE}?)?)))$" +# groups: 12 34 5 6 7 8 + + +class PageRange: + """ + A slice-like representation of a range of page indices. + + For example, page numbers, only starting at zero. + + The syntax is like what you would put between brackets [ ]. + The slice is one of the few Python types that can't be subclassed, + but this class converts to and from slices, and allows similar use. + + - PageRange(str) parses a string representing a page range. + - PageRange(slice) directly "imports" a slice. + - to_slice() gives the equivalent slice. + - str() and repr() allow printing. + - indices(n) is like slice.indices(n). + """ + + def __init__(self, arg: Union[slice, "PageRange", str]) -> None: + """ + Initialize with either a slice -- giving the equivalent page range, + or a PageRange object -- making a copy, + or a string like + "int", "[int]:[int]" or "[int]:[int]:[int]", + where the brackets indicate optional ints. + Remember, page indices start with zero. + Page range expression examples: + + : all pages. -1 last page. + 22 just the 23rd page. :-1 all but the last page. + 0:3 the first three pages. -2 second-to-last page. + :3 the first three pages. -2: last two pages. + 5: from the sixth page onward. -3:-1 third & second to last. + The third, "stride" or "step" number is also recognized. + ::2 0 2 4 ... to the end. 3:0:-1 3 2 1 but not 0. + 1:10:2 1 3 5 7 9 2::-1 2 1 0. + ::-1 all pages in reverse order. + Note the difference between this notation and arguments to slice(): + slice(3) means the first three pages; + PageRange("3") means the range of only the fourth page. + However PageRange(slice(3)) means the first three pages. + """ + if isinstance(arg, slice): + self._slice = arg + return + + if isinstance(arg, PageRange): + self._slice = arg.to_slice() + return + + m = isinstance(arg, str) and re.match(PAGE_RANGE_RE, arg) + if not m: + raise ParseError(arg) + if m.group(2): + # Special case: just an int means a range of one page. + start = int(m.group(2)) + stop = start + 1 if start != -1 else None + self._slice = slice(start, stop) + else: + self._slice = slice(*[int(g) if g else None for g in m.group(4, 6, 8)]) + + @staticmethod + def valid(input: Any) -> bool: + """ + True if input is a valid initializer for a PageRange. + + Args: + input: A possible PageRange string or a PageRange object. + + Returns: + True, if the ``input`` is a valid PageRange. + + """ + return isinstance(input, (slice, PageRange)) or ( + isinstance(input, str) and bool(re.match(PAGE_RANGE_RE, input)) + ) + + def to_slice(self) -> slice: + """Return the slice equivalent of this page range.""" + return self._slice + + def __str__(self) -> str: + """A string like "1:2:3".""" + s = self._slice + indices: Union[tuple[int, int], tuple[int, int, int]] + if s.step is None: + if s.start is not None and s.stop == s.start + 1: + return str(s.start) + + indices = s.start, s.stop + else: + indices = s.start, s.stop, s.step + return ":".join("" if i is None else str(i) for i in indices) + + def __repr__(self) -> str: + """A string like "PageRange('1:2:3')".""" + return "PageRange(" + repr(str(self)) + ")" + + def indices(self, n: int) -> tuple[int, int, int]: + """ + Assuming a sequence of length n, calculate the start and stop indices, + and the stride length of the PageRange. + + See help(slice.indices). + + Args: + n: the length of the list of pages to choose from. + + Returns: + Arguments for range(). + + """ + return self._slice.indices(n) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, PageRange): + return False + return self._slice == other._slice + + def __hash__(self) -> int: + return hash((self.__class__, (self._slice.start, self._slice.stop, self._slice.step))) + + def __add__(self, other: "PageRange") -> "PageRange": + if not isinstance(other, PageRange): + raise TypeError(f"Can't add PageRange and {type(other)}") + if self._slice.step is not None or other._slice.step is not None: + raise ValueError("Can't add PageRange with stride") + a = self._slice.start, self._slice.stop + b = other._slice.start, other._slice.stop + + if a[0] > b[0]: + a, b = b, a + + # Now a[0] is the smallest + if b[0] > a[1]: + # There is a gap between a and b. + raise ValueError("Can't add PageRanges with gap") + return PageRange(slice(a[0], max(a[1], b[1]))) + + +PAGE_RANGE_ALL = PageRange(":") # The range of all pages. + + +def parse_filename_page_ranges( + args: list[Union[str, PageRange, None]] +) -> list[tuple[str, PageRange]]: + """ + Given a list of filenames and page ranges, return a list of (filename, page_range) pairs. + + Args: + args: A list where the first element is a filename. The other elements are + filenames, page-range expressions, slice objects, or PageRange objects. + A filename not followed by a page range indicates all pages of the file. + + Returns: + A list of (filename, page_range) pairs. + + """ + pairs: list[tuple[str, PageRange]] = [] + pdf_filename: Union[str, None] = None + did_page_range = False + for arg in [*args, None]: + if PageRange.valid(arg): + if not pdf_filename: + raise ValueError( + "The first argument must be a filename, not a page range." + ) + + assert arg is not None + pairs.append((pdf_filename, PageRange(arg))) + did_page_range = True + else: + # New filename or end of list - use the complete previous file? + if pdf_filename and not did_page_range: + pairs.append((pdf_filename, PAGE_RANGE_ALL)) + + assert not isinstance(arg, PageRange), arg + pdf_filename = arg + did_page_range = False + return pairs + + +PageRangeSpec = Union[str, PageRange, tuple[int, int], tuple[int, int, int], list[int]] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/papersizes.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/papersizes.py new file mode 100644 index 0000000000000000000000000000000000000000..ed09f341f6a27e9805f0b49430bd09d4d24d70a3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/papersizes.py @@ -0,0 +1,52 @@ +"""Helper to get paper sizes.""" + +from typing import NamedTuple + + +class Dimensions(NamedTuple): + width: int + height: int + + +class PaperSize: + """(width, height) of the paper in portrait mode in pixels at 72 ppi.""" + + # Notes of how to calculate it: + # 1. Get the size of the paper in millimeters + # 2. Convert it to inches (25.4 millimeters is equal to 1 inch) + # 3. Convert it to pixels at 72dpi (1 inch is equal to 72 pixels) + + # All Din-A paper sizes follow this pattern: + # 2 x A(n - 1) = A(n) + # So the height of the next bigger one is the width of the smaller one + # The ratio is always approximately 1:2**0.5 + # Additionally, A0 is defined to have an area of 1 m**2 + # https://en.wikipedia.org/wiki/ISO_216 + # Be aware of rounding issues! + A0 = Dimensions(2384, 3370) # 841mm x 1189mm + A1 = Dimensions(1684, 2384) + A2 = Dimensions(1191, 1684) + A3 = Dimensions(842, 1191) + A4 = Dimensions( + 595, 842 + ) # Printer paper, documents - this is by far the most common + A5 = Dimensions(420, 595) # Paperback books + A6 = Dimensions(298, 420) # Postcards + A7 = Dimensions(210, 298) + A8 = Dimensions(147, 210) + + # Envelopes + C4 = Dimensions(649, 918) + + +_din_a = ( + PaperSize.A0, + PaperSize.A1, + PaperSize.A2, + PaperSize.A3, + PaperSize.A4, + PaperSize.A5, + PaperSize.A6, + PaperSize.A7, + PaperSize.A8, +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/py.typed b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/types.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/types.py new file mode 100644 index 0000000000000000000000000000000000000000..a1c4e495a5710812ff122f13a4580599c380f8a3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/types.py @@ -0,0 +1,80 @@ +"""Helpers for working with PDF types.""" + +import sys +from typing import Literal, Union + +if sys.version_info[:2] >= (3, 10): + # Python 3.10+: https://www.python.org/dev/peps/pep-0484 + from typing import TypeAlias +else: + from typing_extensions import TypeAlias + +from .generic._base import NameObject, NullObject, NumberObject +from .generic._data_structures import ArrayObject, Destination +from .generic._outline import OutlineItem + +BorderArrayType: TypeAlias = list[Union[NameObject, NumberObject, ArrayObject]] + +OutlineItemType: TypeAlias = Union[OutlineItem, Destination] + +FitType: TypeAlias = Literal[ + "/XYZ", "/Fit", "/FitH", "/FitV", "/FitR", "/FitB", "/FitBH", "/FitBV" +] +# These go with the FitType, they specify values for the fit +ZoomArgType: TypeAlias = Union[NumberObject, NullObject, float] +ZoomArgsType: TypeAlias = list[ZoomArgType] + +# Recursive types like the following are not yet supported by Sphinx: +# OutlineType = List[Union[Destination, "OutlineType"]] +# Hence use this for the moment: +OutlineType = list[Union[Destination, list[Union[Destination, list[Destination]]]]] + +LayoutType: TypeAlias = Literal[ + "/NoLayout", + "/SinglePage", + "/OneColumn", + "/TwoColumnLeft", + "/TwoColumnRight", + "/TwoPageLeft", + "/TwoPageRight", +] + +PagemodeType: TypeAlias = Literal[ + "/UseNone", + "/UseOutlines", + "/UseThumbs", + "/FullScreen", + "/UseOC", + "/UseAttachments", +] + +AnnotationSubtype: TypeAlias = Literal[ + "/Text", + "/Link", + "/FreeText", + "/Line", + "/Square", + "/Circle", + "/Polygon", + "/PolyLine", + "/Highlight", + "/Underline", + "/Squiggly", + "/StrikeOut", + "/Caret", + "/Stamp", + "/Ink", + "/Popup", + "/FileAttachment", + "/Sound", + "/Movie", + "/Screen", + "/Widget", + "/PrinterMark", + "/TrapNet", + "/Watermark", + "/3D", + "/Redact", + "/Projection", + "/RichMedia", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/xmp.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/xmp.py new file mode 100644 index 0000000000000000000000000000000000000000..8e399a5a990f65dce822acd90b490d502f63f50d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/xmp.py @@ -0,0 +1,778 @@ +""" +Anything related to Extensible Metadata Platform (XMP) metadata. + +https://en.wikipedia.org/wiki/Extensible_Metadata_Platform +""" + +import datetime +import decimal +import re +from collections.abc import Iterator +from typing import ( + Any, + Callable, + Optional, + TypeVar, + Union, + cast, +) +from xml.dom.expatbuilder import ExpatBuilderNS +from xml.dom.minidom import Document +from xml.dom.minidom import Element as XmlElement +from xml.parsers.expat import ExpatError, XMLParserType + +from ._protocols import XmpInformationProtocol +from ._utils import StreamType, deprecate_with_replacement, deprecation_no_replacement +from .errors import PdfReadError, XmpDocumentError +from .generic import ContentStream, PdfObject + +RDF_NAMESPACE = "http://www.w3.org/1999/02/22-rdf-syntax-ns#" +DC_NAMESPACE = "http://purl.org/dc/elements/1.1/" +XMP_NAMESPACE = "http://ns.adobe.com/xap/1.0/" +PDF_NAMESPACE = "http://ns.adobe.com/pdf/1.3/" +XMPMM_NAMESPACE = "http://ns.adobe.com/xap/1.0/mm/" + +# What is the PDFX namespace, you might ask? +# It's documented here: https://github.com/adobe/xmp-docs/raw/master/XMPSpecifications/XMPSpecificationPart3.pdf +# This namespace is used to place "custom metadata" +# properties, which are arbitrary metadata properties with no semantic or +# documented meaning. +# +# Elements in the namespace are key/value-style storage, +# where the element name is the key and the content is the value. The keys +# are transformed into valid XML identifiers by substituting an invalid +# identifier character with \u2182 followed by the unicode hex ID of the +# original character. A key like "my car" is therefore "my\u21820020car". +# +# \u2182 is the unicode character \u{ROMAN NUMERAL TEN THOUSAND} +# +# The pdfx namespace should be avoided. +# A custom data schema and sensical XML elements could be used instead, as is +# suggested by Adobe's own documentation on XMP under "Extensibility of +# Schemas". +PDFX_NAMESPACE = "http://ns.adobe.com/pdfx/1.3/" + +# PDF/A +PDFAID_NAMESPACE = "http://www.aiim.org/pdfa/ns/id/" + +# Internal mapping of namespace URI → prefix +_NAMESPACE_PREFIX_MAP = { + DC_NAMESPACE: "dc", + XMP_NAMESPACE: "xmp", + PDF_NAMESPACE: "pdf", + XMPMM_NAMESPACE: "xmpMM", + PDFAID_NAMESPACE: "pdfaid", + PDFX_NAMESPACE: "pdfx", +} + +iso8601 = re.compile( + """ + (?P[0-9]{4}) + (- + (?P[0-9]{2}) + (- + (?P[0-9]+) + (T + (?P[0-9]{2}): + (?P[0-9]{2}) + (:(?P[0-9]{2}(.[0-9]+)?))? + (?PZ|[-+][0-9]{2}:[0-9]{2}) + )? + )? + )? + """, + re.VERBOSE, +) + + +K = TypeVar("K") + +# Minimal XMP template +_MINIMAL_XMP = f""" + + + + + + +""" + + +def _identity(value: K) -> K: + return value + + +def _converter_date(value: str) -> datetime.datetime: + matches = iso8601.match(value) + if matches is None: + raise ValueError(f"Invalid date format: {value}") + year = int(matches.group("year")) + month = int(matches.group("month") or "1") + day = int(matches.group("day") or "1") + hour = int(matches.group("hour") or "0") + minute = int(matches.group("minute") or "0") + second = decimal.Decimal(matches.group("second") or "0") + seconds_dec = second.to_integral(decimal.ROUND_FLOOR) + milliseconds_dec = (second - seconds_dec) * 1_000_000 + + seconds = int(seconds_dec) + milliseconds = int(milliseconds_dec) + + tzd = matches.group("tzd") or "Z" + dt = datetime.datetime(year, month, day, hour, minute, seconds, milliseconds) + if tzd != "Z": + tzd_hours, tzd_minutes = (int(x) for x in tzd.split(":")) + tzd_hours *= -1 + if tzd_hours < 0: + tzd_minutes *= -1 + dt = dt + datetime.timedelta(hours=tzd_hours, minutes=tzd_minutes) + return dt + + +def _format_datetime_utc(value: datetime.datetime) -> str: + """Format a datetime as UTC with trailing 'Z'. + + - If the input is timezone-aware, convert to UTC first. + - If naive, assume UTC. + """ + if value.tzinfo is not None and value.utcoffset() is not None: + value = value.astimezone(datetime.timezone.utc) + + value = value.replace(tzinfo=None) + return value.strftime("%Y-%m-%dT%H:%M:%S.%fZ") + + +def _generic_get( + element: XmlElement, self: "XmpInformation", list_type: str, converter: Callable[[Any], Any] = _identity +) -> Optional[list[str]]: + containers = element.getElementsByTagNameNS(RDF_NAMESPACE, list_type) + retval: list[Any] = [] + if len(containers): + for container in containers: + for item in container.getElementsByTagNameNS(RDF_NAMESPACE, "li"): + value = self._get_text(item) + value = converter(value) + retval.append(value) + return retval + return None + + +class _XmpBuilder(ExpatBuilderNS): + """ + Custom XML parser denying all entity declarations. + + This is a stripped down and typed version inspired by what *defusedxml* does. + + Why do we need this? The default limits of *libexpat* used by Python only block exponential entity expansion, + but not cases like quadratic entity expansion which can still cause quite some memory usage. + """ + + def custom_entity_declaration_handler( + self, + entity_name: str, + is_parameter_entity: bool, + value: Optional[str], + base: Optional[str], + system_id: str, + public_id: Optional[str], + notation_name: Optional[str], + ) -> None: + raise ExpatError(f"Forbidden entities: {entity_name!r}") + + def install(self, parser: XMLParserType) -> None: + super().install(parser) + + parser.EntityDeclHandler = self.custom_entity_declaration_handler + + +class XmpInformation(XmpInformationProtocol, PdfObject): + """ + An object that represents Extensible Metadata Platform (XMP) metadata. + Usually accessed by :py:attr:`xmp_metadata()`. + + Raises: + PdfReadError: if XML is invalid + + """ + + def __init__(self, stream: ContentStream) -> None: + self.stream = stream + try: + data = self.stream.get_data() + doc_root: Document = _XmpBuilder().parseString(data) + except (AttributeError, ExpatError) as e: + raise PdfReadError(f"XML in XmpInformation was invalid: {e}") + self.rdf_root: XmlElement = doc_root.getElementsByTagNameNS( + RDF_NAMESPACE, "RDF" + )[0] + self.cache: dict[Any, Any] = {} + + @classmethod + def create(cls) -> "XmpInformation": + """ + Create a new XmpInformation object with minimal structure. + + Returns: + A new XmpInformation instance with empty metadata fields. + """ + stream = ContentStream(None, None) + stream.set_data(_MINIMAL_XMP.encode("utf-8")) + return cls(stream) + + def write_to_stream( + self, stream: StreamType, encryption_key: Union[None, str, bytes] = None + ) -> None: + deprecate_with_replacement( + "XmpInformation.write_to_stream", + "PdfWriter.xmp_metadata", + "6.0.0" + ) + if encryption_key is not None: # deprecated + deprecation_no_replacement( + "the encryption_key parameter of write_to_stream", "5.0.0" + ) + self.stream.write_to_stream(stream) + + def get_element(self, about_uri: str, namespace: str, name: str) -> Iterator[Any]: + for desc in self.rdf_root.getElementsByTagNameNS(RDF_NAMESPACE, "Description"): + if desc.getAttributeNS(RDF_NAMESPACE, "about") == about_uri: + attr = desc.getAttributeNodeNS(namespace, name) + if attr is not None: + yield attr + yield from desc.getElementsByTagNameNS(namespace, name) + + def get_nodes_in_namespace(self, about_uri: str, namespace: str) -> Iterator[Any]: + for desc in self.rdf_root.getElementsByTagNameNS(RDF_NAMESPACE, "Description"): + if desc.getAttributeNS(RDF_NAMESPACE, "about") == about_uri: + for i in range(desc.attributes.length): + attr = desc.attributes.item(i) + if attr and attr.namespaceURI == namespace: + yield attr + for child in desc.childNodes: + if child.namespaceURI == namespace: + yield child + + def _get_text(self, element: XmlElement) -> str: + text = "" + for child in element.childNodes: + if child.nodeType == child.TEXT_NODE: + text += child.data + return text + + def _get_single_value( + self, + namespace: str, + name: str, + converter: Callable[[str], Any] = _identity, + ) -> Optional[Any]: + cached = self.cache.get(namespace, {}).get(name) + if cached: + return cached + value = None + for element in self.get_element("", namespace, name): + if element.nodeType == element.ATTRIBUTE_NODE: + value = element.nodeValue + else: + value = self._get_text(element) + break + if value is not None: + value = converter(value) + ns_cache = self.cache.setdefault(namespace, {}) + ns_cache[name] = value + return value + + def _getter_bag(self, namespace: str, name: str) -> Optional[list[str]]: + cached = self.cache.get(namespace, {}).get(name) + if cached: + return cast(list[str], cached) + retval: list[str] = [] + for element in self.get_element("", namespace, name): + if (bags := _generic_get(element, self, list_type="Bag")) is not None: + retval.extend(bags) + else: + value = self._get_text(element) + retval.append(value) + ns_cache = self.cache.setdefault(namespace, {}) + ns_cache[name] = retval + return retval + + def _get_seq_values( + self, + namespace: str, + name: str, + converter: Callable[[Any], Any] = _identity, + ) -> Optional[list[Any]]: + cached = self.cache.get(namespace, {}).get(name) + if cached: + return cast(list[Any], cached) + retval: list[Any] = [] + for element in self.get_element("", namespace, name): + if (seqs := _generic_get(element, self, list_type="Seq", converter=converter)) is not None: + retval.extend(seqs) + elif (bags := _generic_get(element, self, list_type="Bag")) is not None: + # See issue at https://github.com/py-pdf/pypdf/issues/3324 + # Some applications violate the XMP metadata standard regarding `dc:creator` which should + # be an "ordered array" and thus a sequence, but use an unordered array (bag) instead. + # This seems to stem from the fact that the original Dublin Core specification does indeed + # use bags or direct values, while PDFs are expected to follow the XMP standard and ignore + # the plain Dublin Core variant. For this reason, add a fallback here to deal with such + # issues accordingly. + retval.extend(bags) + else: + value = converter(self._get_text(element)) + retval.append(value) + ns_cache = self.cache.setdefault(namespace, {}) + ns_cache[name] = retval + return retval + + def _get_langalt_values(self, namespace: str, name: str) -> Optional[dict[Any, Any]]: + cached = self.cache.get(namespace, {}).get(name) + if cached: + return cast(dict[Any, Any], cached) + retval: dict[Any, Any] = {} + for element in self.get_element("", namespace, name): + alts = element.getElementsByTagNameNS(RDF_NAMESPACE, "Alt") + if len(alts): + for alt in alts: + for item in alt.getElementsByTagNameNS(RDF_NAMESPACE, "li"): + value = self._get_text(item) + retval[item.getAttribute("xml:lang")] = value + else: + retval["x-default"] = self._get_text(element) + ns_cache = self.cache.setdefault(namespace, {}) + ns_cache[name] = retval + return retval + + @property + def dc_contributor(self) -> Optional[list[str]]: + """Contributors to the resource (other than the authors).""" + return self._getter_bag(DC_NAMESPACE, "contributor") + + @dc_contributor.setter + def dc_contributor(self, values: Optional[list[str]]) -> None: + self._set_bag_values(DC_NAMESPACE, "contributor", values) + + @property + def dc_coverage(self) -> Optional[str]: + """Text describing the extent or scope of the resource.""" + return self._get_single_value(DC_NAMESPACE, "coverage") + + @dc_coverage.setter + def dc_coverage(self, value: Optional[str]) -> None: + self._set_single_value(DC_NAMESPACE, "coverage", value) + + @property + def dc_creator(self) -> Optional[list[str]]: + """A sorted array of names of the authors of the resource, listed in order of precedence.""" + return self._get_seq_values(DC_NAMESPACE, "creator") + + @dc_creator.setter + def dc_creator(self, values: Optional[list[str]]) -> None: + self._set_seq_values(DC_NAMESPACE, "creator", values) + + @property + def dc_date(self) -> Optional[list[datetime.datetime]]: + """A sorted array of dates of significance to the resource. The dates and times are in UTC.""" + return self._get_seq_values(DC_NAMESPACE, "date", _converter_date) + + @dc_date.setter + def dc_date(self, values: Optional[list[Union[str, datetime.datetime]]]) -> None: + if values is None: + self._set_seq_values(DC_NAMESPACE, "date", None) + else: + date_strings = [] + for value in values: + if isinstance(value, datetime.datetime): + date_strings.append(_format_datetime_utc(value)) + else: + date_strings.append(str(value)) + self._set_seq_values(DC_NAMESPACE, "date", date_strings) + + @property + def dc_description(self) -> Optional[dict[str, str]]: + """A language-keyed dictionary of textual descriptions of the content of the resource.""" + return self._get_langalt_values(DC_NAMESPACE, "description") + + @dc_description.setter + def dc_description(self, values: Optional[dict[str, str]]) -> None: + self._set_langalt_values(DC_NAMESPACE, "description", values) + + @property + def dc_format(self) -> Optional[str]: + """The mime-type of the resource.""" + return self._get_single_value(DC_NAMESPACE, "format") + + @dc_format.setter + def dc_format(self, value: Optional[str]) -> None: + self._set_single_value(DC_NAMESPACE, "format", value) + + @property + def dc_identifier(self) -> Optional[str]: + """Unique identifier of the resource.""" + return self._get_single_value(DC_NAMESPACE, "identifier") + + @dc_identifier.setter + def dc_identifier(self, value: Optional[str]) -> None: + self._set_single_value(DC_NAMESPACE, "identifier", value) + + @property + def dc_language(self) -> Optional[list[str]]: + """An unordered array specifying the languages used in the resource.""" + return self._getter_bag(DC_NAMESPACE, "language") + + @dc_language.setter + def dc_language(self, values: Optional[list[str]]) -> None: + self._set_bag_values(DC_NAMESPACE, "language", values) + + @property + def dc_publisher(self) -> Optional[list[str]]: + """An unordered array of publisher names.""" + return self._getter_bag(DC_NAMESPACE, "publisher") + + @dc_publisher.setter + def dc_publisher(self, values: Optional[list[str]]) -> None: + self._set_bag_values(DC_NAMESPACE, "publisher", values) + + @property + def dc_relation(self) -> Optional[list[str]]: + """An unordered array of text descriptions of relationships to other documents.""" + return self._getter_bag(DC_NAMESPACE, "relation") + + @dc_relation.setter + def dc_relation(self, values: Optional[list[str]]) -> None: + self._set_bag_values(DC_NAMESPACE, "relation", values) + + @property + def dc_rights(self) -> Optional[dict[str, str]]: + """A language-keyed dictionary of textual descriptions of the rights the user has to this resource.""" + return self._get_langalt_values(DC_NAMESPACE, "rights") + + @dc_rights.setter + def dc_rights(self, values: Optional[dict[str, str]]) -> None: + self._set_langalt_values(DC_NAMESPACE, "rights", values) + + @property + def dc_source(self) -> Optional[str]: + """Unique identifier of the work from which this resource was derived.""" + return self._get_single_value(DC_NAMESPACE, "source") + + @dc_source.setter + def dc_source(self, value: Optional[str]) -> None: + self._set_single_value(DC_NAMESPACE, "source", value) + + @property + def dc_subject(self) -> Optional[list[str]]: + """An unordered array of descriptive phrases or keywords that specify the topic of the content.""" + return self._getter_bag(DC_NAMESPACE, "subject") + + @dc_subject.setter + def dc_subject(self, values: Optional[list[str]]) -> None: + self._set_bag_values(DC_NAMESPACE, "subject", values) + + @property + def dc_title(self) -> Optional[dict[str, str]]: + """A language-keyed dictionary of the title of the resource.""" + return self._get_langalt_values(DC_NAMESPACE, "title") + + @dc_title.setter + def dc_title(self, values: Optional[dict[str, str]]) -> None: + self._set_langalt_values(DC_NAMESPACE, "title", values) + + @property + def dc_type(self) -> Optional[list[str]]: + """An unordered array of textual descriptions of the document type.""" + return self._getter_bag(DC_NAMESPACE, "type") + + @dc_type.setter + def dc_type(self, values: Optional[list[str]]) -> None: + self._set_bag_values(DC_NAMESPACE, "type", values) + + @property + def pdf_keywords(self) -> Optional[str]: + """An unformatted text string representing document keywords.""" + return self._get_single_value(PDF_NAMESPACE, "Keywords") + + @pdf_keywords.setter + def pdf_keywords(self, value: Optional[str]) -> None: + self._set_single_value(PDF_NAMESPACE, "Keywords", value) + + @property + def pdf_pdfversion(self) -> Optional[str]: + """The PDF file version, for example 1.0 or 1.3.""" + return self._get_single_value(PDF_NAMESPACE, "PDFVersion") + + @pdf_pdfversion.setter + def pdf_pdfversion(self, value: Optional[str]) -> None: + self._set_single_value(PDF_NAMESPACE, "PDFVersion", value) + + @property + def pdf_producer(self) -> Optional[str]: + """The name of the tool that saved the document as a PDF.""" + return self._get_single_value(PDF_NAMESPACE, "Producer") + + @pdf_producer.setter + def pdf_producer(self, value: Optional[str]) -> None: + self._set_single_value(PDF_NAMESPACE, "Producer", value) + + @property + def xmp_create_date(self) -> Optional[datetime.datetime]: + """The date and time the resource was originally created. Returned as a UTC datetime object.""" + return self._get_single_value(XMP_NAMESPACE, "CreateDate", _converter_date) + + @xmp_create_date.setter + def xmp_create_date(self, value: Optional[datetime.datetime]) -> None: + if value: + date_str = _format_datetime_utc(value) + self._set_single_value(XMP_NAMESPACE, "CreateDate", date_str) + else: + self._set_single_value(XMP_NAMESPACE, "CreateDate", None) + + @property + def xmp_modify_date(self) -> Optional[datetime.datetime]: + """The date and time the resource was last modified. Returned as a UTC datetime object.""" + return self._get_single_value(XMP_NAMESPACE, "ModifyDate", _converter_date) + + @xmp_modify_date.setter + def xmp_modify_date(self, value: Optional[datetime.datetime]) -> None: + if value: + date_str = _format_datetime_utc(value) + self._set_single_value(XMP_NAMESPACE, "ModifyDate", date_str) + else: + self._set_single_value(XMP_NAMESPACE, "ModifyDate", None) + + @property + def xmp_metadata_date(self) -> Optional[datetime.datetime]: + """The date and time that any metadata for this resource was last changed. Returned as a UTC datetime object.""" + return self._get_single_value(XMP_NAMESPACE, "MetadataDate", _converter_date) + + @xmp_metadata_date.setter + def xmp_metadata_date(self, value: Optional[datetime.datetime]) -> None: + if value: + date_str = _format_datetime_utc(value) + self._set_single_value(XMP_NAMESPACE, "MetadataDate", date_str) + else: + self._set_single_value(XMP_NAMESPACE, "MetadataDate", None) + + @property + def xmp_creator_tool(self) -> Optional[str]: + """The name of the first known tool used to create the resource.""" + return self._get_single_value(XMP_NAMESPACE, "CreatorTool") + + @xmp_creator_tool.setter + def xmp_creator_tool(self, value: Optional[str]) -> None: + self._set_single_value(XMP_NAMESPACE, "CreatorTool", value) + + @property + def xmpmm_document_id(self) -> Optional[str]: + """The common identifier for all versions and renditions of this resource.""" + return self._get_single_value(XMPMM_NAMESPACE, "DocumentID") + + @xmpmm_document_id.setter + def xmpmm_document_id(self, value: Optional[str]) -> None: + self._set_single_value(XMPMM_NAMESPACE, "DocumentID", value) + + @property + def xmpmm_instance_id(self) -> Optional[str]: + """An identifier for a specific incarnation of a document, updated each time a file is saved.""" + return self._get_single_value(XMPMM_NAMESPACE, "InstanceID") + + @xmpmm_instance_id.setter + def xmpmm_instance_id(self, value: Optional[str]) -> None: + self._set_single_value(XMPMM_NAMESPACE, "InstanceID", value) + + @property + def pdfaid_part(self) -> Optional[str]: + """The part of the PDF/A standard that the document conforms to (e.g., 1, 2, 3).""" + return self._get_single_value(PDFAID_NAMESPACE, "part") + + @pdfaid_part.setter + def pdfaid_part(self, value: Optional[str]) -> None: + self._set_single_value(PDFAID_NAMESPACE, "part", value) + + @property + def pdfaid_conformance(self) -> Optional[str]: + """The conformance level within the PDF/A standard (e.g., 'A', 'B', 'U').""" + return self._get_single_value(PDFAID_NAMESPACE, "conformance") + + @pdfaid_conformance.setter + def pdfaid_conformance(self, value: Optional[str]) -> None: + self._set_single_value(PDFAID_NAMESPACE, "conformance", value) + + @property + def custom_properties(self) -> dict[Any, Any]: + """ + Retrieve custom metadata properties defined in the undocumented pdfx + metadata schema. + + Returns: + A dictionary of key/value items for custom metadata properties. + + """ + if not hasattr(self, "_custom_properties"): + self._custom_properties = {} + for node in self.get_nodes_in_namespace("", PDFX_NAMESPACE): + key = node.localName + while True: + # see documentation about PDFX_NAMESPACE earlier in file + idx = key.find("\u2182") + if idx == -1: + break + key = ( + key[:idx] + + chr(int(key[idx + 1 : idx + 5], base=16)) + + key[idx + 5 :] + ) + if node.nodeType == node.ATTRIBUTE_NODE: + value = node.nodeValue + else: + value = self._get_text(node) + self._custom_properties[key] = value + return self._custom_properties + + def _get_or_create_description(self, about_uri: str = "") -> XmlElement: + """Get or create an rdf:Description element with the given about URI.""" + for desc in self.rdf_root.getElementsByTagNameNS(RDF_NAMESPACE, "Description"): + if desc.getAttributeNS(RDF_NAMESPACE, "about") == about_uri: + return desc + + doc = self.rdf_root.ownerDocument + if doc is None: + raise XmpDocumentError("XMP Document is None") + desc = doc.createElementNS(RDF_NAMESPACE, "rdf:Description") + desc.setAttributeNS(RDF_NAMESPACE, "rdf:about", about_uri) + self.rdf_root.appendChild(desc) + return desc + + def _clear_cache_entry(self, namespace: str, name: str) -> None: + """Remove a cached value for a given namespace/name if present.""" + ns_cache = self.cache.get(namespace) + if ns_cache and name in ns_cache: + del ns_cache[name] + + def _set_single_value(self, namespace: str, name: str, value: Optional[str]) -> None: + """Set or remove a single metadata value.""" + self._clear_cache_entry(namespace, name) + desc = self._get_or_create_description() + + existing_elements = list(desc.getElementsByTagNameNS(namespace, name)) + for elem in existing_elements: + desc.removeChild(elem) + + if existing_attr := desc.getAttributeNodeNS(namespace, name): + desc.removeAttributeNode(existing_attr) + + if value is not None: + doc = self.rdf_root.ownerDocument + if doc is None: + raise XmpDocumentError("XMP Document is None") + prefix = self._get_namespace_prefix(namespace) + elem = doc.createElementNS(namespace, f"{prefix}:{name}") + text_node = doc.createTextNode(str(value)) + elem.appendChild(text_node) + desc.appendChild(elem) + + self._update_stream() + + def _set_bag_values(self, namespace: str, name: str, values: Optional[list[str]]) -> None: + """Set or remove bag values (unordered array).""" + self._clear_cache_entry(namespace, name) + desc = self._get_or_create_description() + + existing_elements = list(desc.getElementsByTagNameNS(namespace, name)) + for elem in existing_elements: + desc.removeChild(elem) + + if values: + doc = self.rdf_root.ownerDocument + if doc is None: + raise XmpDocumentError("XMP Document is None") + prefix = self._get_namespace_prefix(namespace) + elem = doc.createElementNS(namespace, f"{prefix}:{name}") + bag = doc.createElementNS(RDF_NAMESPACE, "rdf:Bag") + + for value in values: + li = doc.createElementNS(RDF_NAMESPACE, "rdf:li") + text_node = doc.createTextNode(str(value)) + li.appendChild(text_node) + bag.appendChild(li) + + elem.appendChild(bag) + desc.appendChild(elem) + + self._update_stream() + + def _set_seq_values(self, namespace: str, name: str, values: Optional[list[str]]) -> None: + """Set or remove sequence values (ordered array).""" + self._clear_cache_entry(namespace, name) + desc = self._get_or_create_description() + + existing_elements = list(desc.getElementsByTagNameNS(namespace, name)) + for elem in existing_elements: + desc.removeChild(elem) + + if values: + doc = self.rdf_root.ownerDocument + if doc is None: + raise XmpDocumentError("XMP Document is None") + prefix = self._get_namespace_prefix(namespace) + elem = doc.createElementNS(namespace, f"{prefix}:{name}") + seq = doc.createElementNS(RDF_NAMESPACE, "rdf:Seq") + + for value in values: + li = doc.createElementNS(RDF_NAMESPACE, "rdf:li") + text_node = doc.createTextNode(str(value)) + li.appendChild(text_node) + seq.appendChild(li) + + elem.appendChild(seq) + desc.appendChild(elem) + + self._update_stream() + + def _set_langalt_values(self, namespace: str, name: str, values: Optional[dict[str, str]]) -> None: + """Set or remove language alternative values.""" + self._clear_cache_entry(namespace, name) + desc = self._get_or_create_description() + + existing_elements = list(desc.getElementsByTagNameNS(namespace, name)) + for elem in existing_elements: + desc.removeChild(elem) + + if values: + doc = self.rdf_root.ownerDocument + if doc is None: + raise XmpDocumentError("XMP Document is None") + prefix = self._get_namespace_prefix(namespace) + elem = doc.createElementNS(namespace, f"{prefix}:{name}") + alt = doc.createElementNS(RDF_NAMESPACE, "rdf:Alt") + + for lang, value in values.items(): + li = doc.createElementNS(RDF_NAMESPACE, "rdf:li") + li.setAttribute("xml:lang", lang) + text_node = doc.createTextNode(str(value)) + li.appendChild(text_node) + alt.appendChild(li) + + elem.appendChild(alt) + desc.appendChild(elem) + + self._update_stream() + + def _get_namespace_prefix(self, namespace: str) -> str: + """Get the appropriate namespace prefix for a given namespace URI.""" + return _NAMESPACE_PREFIX_MAP.get(namespace, "unknown") + + def _update_stream(self) -> None: + """Update the stream with the current XML content.""" + doc = self.rdf_root.ownerDocument + if doc is None: + raise XmpDocumentError("XMP Document is None") + + xml_data = doc.toxml(encoding="utf-8") + self.stream.set_data(xml_data) diff --git a/python/_asyncio.pyd b/python/_asyncio.pyd new file mode 100644 index 0000000000000000000000000000000000000000..c5cfdb024a176a9b7a7395fec0747f8ee2edecab Binary files /dev/null and b/python/_asyncio.pyd differ diff --git a/python/_bz2.pyd b/python/_bz2.pyd new file mode 100644 index 0000000000000000000000000000000000000000..ee443b90e6e44b9c1f14fb71d253ff1a7e697cd1 Binary files /dev/null and b/python/_bz2.pyd differ diff --git a/python/_hashlib.pyd b/python/_hashlib.pyd new file mode 100644 index 0000000000000000000000000000000000000000..52926dee13e488d131a7fc920b044176f6c80357 Binary files /dev/null and b/python/_hashlib.pyd differ diff --git a/python/_multiprocessing.pyd b/python/_multiprocessing.pyd new file mode 100644 index 0000000000000000000000000000000000000000..caf4504f45b77c325f47eff55dbf959ebc7663c4 Binary files /dev/null and b/python/_multiprocessing.pyd differ diff --git a/python/_overlapped.pyd b/python/_overlapped.pyd new file mode 100644 index 0000000000000000000000000000000000000000..6b05f02e3cce87d9497f9014b8a8515a588b02a8 Binary files /dev/null and b/python/_overlapped.pyd differ diff --git a/python/_queue.pyd b/python/_queue.pyd new file mode 100644 index 0000000000000000000000000000000000000000..e29b666041a130c9f1a50c3d949cdcc2a4b47c53 Binary files /dev/null and b/python/_queue.pyd differ diff --git a/python/vcruntime140_1.dll b/python/vcruntime140_1.dll new file mode 100644 index 0000000000000000000000000000000000000000..2071f2814bbc6dac9a18b32c77ca86da09d579c3 Binary files /dev/null and b/python/vcruntime140_1.dll differ diff --git a/python/winsound.pyd b/python/winsound.pyd new file mode 100644 index 0000000000000000000000000000000000000000..8c1b9a4e23a7b32f8dcea374826a98e87c2676d4 Binary files /dev/null and b/python/winsound.pyd differ