App-perlimports-0.000067000755001750001751 015261510577 14103 5ustar00olafolaf000000000000LICENSE100644001750001751 4627615261510577 15230 0ustar00olafolaf000000000000App-perlimports-0.000067This software is copyright (c) 2020 by Olaf Alders. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Terms of the Perl programming language system itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" --- The GNU General Public License, Version 1, February 1989 --- This software is Copyright (c) 2020 by Olaf Alders. This is free software, licensed under: The GNU General Public License, Version 1, February 1989 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 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 license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our 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. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, 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 a 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 tell them 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. 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 Agreement 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 work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 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 General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual 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 General Public License. d) 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. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 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 Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying 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. 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. 7. 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 the 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 the license, you may choose any version ever published by the Free Software Foundation. 8. 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 9. 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. 10. 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 Appendix: 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 humanity, 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) 19yy 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 1, 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 is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx 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 a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Moe Ghoul, President of Vice That's all there is to it! --- The Perl Artistic License 1.0 --- This software is Copyright (c) 2020 by Olaf Alders. This is free software, licensed under: The Perl Artistic License 1.0 The "Artistic License" Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder as specified below. "Copyright Holder" is whoever is named in the copyright or copyrights for the package. "You" is you, if you're thinking about copying or distributing this Package. "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as uunet.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) give non-standard executables non-standard names, and clearly document the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. You may embed this Package's interpreter within an executable of yours (by linking); this shall be construed as a mere form of aggregation, provided that the complete Standard Version of the interpreter is so embedded. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whoever generated them, and may be sold commercially, and may be aggregated with this Package. If such scripts or library files are aggregated with this Package via the so-called "undump" or "unexec" methods of producing a binary executable image, then distribution of such an image shall neither be construed as a distribution of this Package nor shall it fall under the restrictions of Paragraphs 3 and 4, provided that you do not represent such an executable image as a Standard Version of this Package. 7. C subroutines (or comparably compiled subroutines in other languages) supplied by you and linked into this Package in order to emulate subroutines and variables of the language defined by this Package shall not be considered part of this Package, but are the equivalent of input as in Paragraph 6, provided these subroutines do not change the language in any way that would cause it to fail the regression tests for the language. 8. Aggregation of this Package with a commercial distribution is always permitted provided that the use of this Package is embedded; that is, when no overt attempt is made to make this Package's interfaces visible to the end user of the commercial distribution. Such use shall not be construed as a distribution of this Package. 9. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 10. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End INSTALL100644001750001751 460015261510577 15215 0ustar00olafolaf000000000000App-perlimports-0.000067This is the Perl distribution App-perlimports. Installing App-perlimports is straightforward. ## Installation with cpanm If you have cpanm, you only need one line: % cpanm App::perlimports If it does not have permission to install modules to the current perl, cpanm will automatically set up and install to a local::lib in your home directory. See the local::lib documentation (https://metacpan.org/pod/local::lib) for details on enabling it in your environment. ## Installing with the CPAN shell Alternatively, if your CPAN shell is set up, you should just be able to do: % cpan App::perlimports ## Manual installation As a last resort, you can manually install it. If you have not already downloaded the release tarball, you can find the download link on the module's MetaCPAN page: https://metacpan.org/pod/App::perlimports Untar the tarball, install configure prerequisites (see below), then build it: % perl Makefile.PL % make && make test Then install it: % make install On Windows platforms, you should use `dmake` or `nmake`, instead of `make`. If your perl is system-managed, you can create a local::lib in your home directory to install modules to. For details, see the local::lib documentation: https://metacpan.org/pod/local::lib The prerequisites of this distribution will also have to be installed manually. The prerequisites are listed in one of the files: `MYMETA.yml` or `MYMETA.json` generated by running the manual build process described above. ## Configure Prerequisites This distribution requires other modules to be installed before this distribution's installer can be run. They can be found under the "configure_requires" key of META.yml or the "{prereqs}{configure}{requires}" key of META.json. ## Other Prerequisites This distribution may require additional modules to be installed after running Makefile.PL. Look for prerequisites in the following phases: * to run make, PHASE = build * to use the module code itself, PHASE = runtime * to run tests, PHASE = test They can all be found in the "PHASE_requires" key of MYMETA.yml or the "{prereqs}{PHASE}{requires}" key of MYMETA.json. ## Documentation App-perlimports documentation is available as POD. You can run `perldoc` from a shell to read the documentation: % perldoc App::perlimports For more information on installing Perl modules via CPAN, please see: https://www.cpan.org/modules/INSTALL.html Changes100644001750001751 3531015261510577 15501 0ustar00olafolaf000000000000App-perlimports-0.000067Revision history for App-perlimports 0.000067 2026-10-07 18:37:39Z - Ignore `use LWP::ConsoleLogger::Everywhere` by default. It is loaded only for its import-time side effect of logging every LWP::UserAgent and HTTP::Tiny request, exports nothing, and was previously stripped entirely, silently disabling the logging (GH#195) (Olaf Alders) - Tidy imports from MooseX::Types type libraries even when the library has a Moose metaclass, as with MooseX::Types 0.50. Previously such `use` statements were ignored, so missing imports were not added (GH#202) (Olaf Alders) - Skip t/env.t when Env is not installed, e.g. on Fedora, which ships it in a separate perl-Env package (GH#200) (Olaf Alders) - Keep a symbol imported when the same symbol is imported from more than one module. Previously, removing an unused `use` statement could cause the symbol to also be dropped from a later `use` statement, and the linter could recommend dropping it from every `use` statement. The linter now also agrees with tidying about which imports to keep (GH#197) (Olaf Alders) 0.000066 2026-10-05 15:56:06Z - Update the example precious config in the docs to use dashed keys (e.g. `lint-flags` rather than `lint_flags`) and to add `lint-failure-exit-codes = 1` for perlimports (GH#196) (Dave Rolsky) 0.000065 2026-09-10 14:43:00Z - Preserve `require Module;` statements by default rather than rewriting them to `use Module ();`. The two are not equivalent (`require` loads at runtime, `use` at compile time) and a `require` is frequently deliberate. Disable the new `preserve_require` option (`--no-preserve-require`) to restore the previous translate-to-`use` behaviour (GH#76) (Olaf Alders) - Handle `Env` instead of ignoring it: prune unused variables from a `use Env qw( ... )` statement and keep the ones which are actually used (including interpolated and bareword-scalar forms), rather than leaving every `use Env` untouched. A bare `use Env;` is still left alone (GH#23) (Olaf Alders) - Preserve an explicitly-imported typeglob slot (e.g. `use English qw( $PROGRAM_NAME )`) instead of normalizing it to the `*PROGRAM_NAME` typeglob form (GH#97) (Olaf Alders) - Recognize indirect object syntax (e.g. `new File $path`) as a use of the named module, so a module used only that way is no longer reported as unused and removed (GH#99) (Olaf Alders) - Preserve comments embedded in `use` statements (e.g. a `## no critic` annotation between the module name and the import list), which were previously dropped when the statement was rebuilt (GH#50) (Olaf Alders) - Ignore `use Test::NoWarnings` by default. It exists purely for its side-effecting END block and was previously stripped entirely; loading it also registered a stray test on the Test::Builder singleton (GH#44) (Olaf Alders) - Ignore `use local::lib` by default. It manipulates @INC as a side effect and exports nothing worth managing, but was previously stripped entirely (GH#117) (Olaf Alders) 0.000064 2026-09-09 14:10:05Z - Write the " OK" --lint success summary to STDOUT instead of STDERR, so a clean run leaves STDERR empty, and add a --quiet/-q flag that suppresses the success summary and quiets info/notice-level console log noise; genuine warnings and errors still reach STDERR (GH#163) (Olaf Alders) - Also suppress the Sandbox::eval_pkg trial-load warning under its Perl 5.44 wording ("Attempt to call missing import method"), which the 5.44 dev cycle renamed from "undefined"; fixes a t/never-exports.t failure on Fedora 45 (GH#181) (reported by @mavit) 0.000063 2026-09-08 21:15:32Z - Suppress warnings leaked to STDERR when trial-loading modules in Sandbox::eval_pkg (e.g. "Attempt to call undefined import method" for modules with no import()) (GH#180) (Olaf Alders) - Include the "location" and "diff" fields in --json output when --sort reports unsorted includes; previously only "reason" and "filename" were emitted (GH#178) 0.000062 2026-09-08 13:34:54Z - Add an experimental --sort flag to sort contiguous include statements into a deterministic order (GH#14) 0.000061 2026-08-06 20:49:42Z - Fix a crash caused by Sub::HandlesVia::XS stack-pointer corruption in Document by removing the remaining Sub::HandlesVia Array delegations (GH#171) (Olaf Alders) (reported by H.Merijn Brand) - Skip t/memoize.t on macOS, where loading the UUID XS module hangs prove at exit (Olaf Alders) 0.000060 2026-05-06 16:10:42Z - Drop Perl 5.18, 5.20, 5.22 from CI matrix - Add Perl 5.42 to CI matrix - Remove Test::Most integration test (Test::Most 0.39 broke import => [...] support) (GH#159) 0.000059 2026-04-24 12:47:09Z - Add `pad_brackets` and `indent` formatting options (GH#151) (Paul Johnson) - Recognize constants defined with `use constant` as importable symbols (GH#141) (pyrrhlin) - Fix crash when parsing double-quoted strings containing "q" or "qq" (GH#133) (Copilot) - Rename `original_imports` attribute to `found_imports` (GH#140) (pyrrhlin) - Ensure `original_imports` does not contain duplicated symbols (GH#139) (pyrrhlin) - Avoid wasted effort when linting includes that would not change (GH#138) (pyrrhlin) - Clean up `maybe_new_include` and related lint-or-tidy code paths (GH#143) (pyrrhlin) - Use bare values for simple Bool defaults in Moo attributes (GH#157) (Olaf Alders) - Remove duplicate STDERR assertion in t/cli.t (GH#156) (Olaf Alders) - Add CLAUDE.md and update CONTRIBUTING.md (GH#153) (Olaf Alders) 0.000058 2025-10-28 17:06:33Z - Fix: Recognize function references (\&Module::func) as valid module usage (GH#131) (Copilot) 0.000057 2025-04-30 12:12:23Z - Update test expectations for MooseX::Types::Moose 0.51 (GH#122) (Olaf Alders) 0.000056 2025-03-02 23:34:13Z - Update example path for` XDG_CONFIG_HOME` in CLI.pm (GH#120) (Nelo Onyiah 0.000055 2024-07-04 16:16:22Z - Document that Emacs users can get "perlimports --lint" via Flycheck (GH#112) (Peter Oliver) 0.000054 2024-06-29 19:32:58Z - Don't treat locally defined subs as importable symbols (GH#110) (Olaf Alders). Reported by Glenn Rice. 0.000053 2024-01-13 20:12:59Z - Don't log a non-JSON message to STDERR on linting success when --json is enabled (GH#107) (Olaf Alders) 0.000052 2023-08-19 19:03:55Z - Allow PPI::Statement::Expression in hash key (GH#102) (José Manuel Rodríguez D.) - Fix the never-exports test for machines with older LWP::UserAgent (GH#101) (E. Choroba) 0.000051 2023-06-01 15:52:09Z - Bump TOML::Tiny version from 0 to 0.16 (GH#98) (Olaf Alders) 0.000050 2023-02-14 19:50:33Z - Add experimental --range-begin and --range-end flags, to be used for editor integration (GH#93) (Olaf Alders) - Remove unused variables (GH#95) (Olaf Alders) - Ignore more modules which don't eval (GH#94) (Olaf Alders) 0.000049 2022-10-24 21:19:17Z - Add an experimental --json flag to be used when --lint is enabled (GH#90) (Olaf Alders) - Ignore Filter::Simple (GH#91) (Olaf Alders) 0.000048 2022-09-13 21:49:19Z - Make diagnostic message from linter less confusing (GH#88) (Olaf Alders) 0.000047 2022-09-12 15:31:01Z - Bump PPI from 1.274 to 1.276 (GH#87) (Olaf Alders) 0.000046 2022-09-09 22:26:52Z - Add a --lint flag to force perlimports to behave as a linter (GH#85) (Olaf Alders) 0.000045 2022-06-16 21:18:31Z - Document config file creation and Vim + ALE configuration (GH#83) (Olaf Alders) - Flush memoize cache on object creation (GH#82) (Olaf Alders) - Apply perltidy 20220613 (GH#81) (Olaf Alders) 0.000044 2022-05-27 18:01:51Z - Add log_filename to default config file content (GH#79) (Olaf Alders) - Don't raise some expected Mojo eval problems to the warning level (GH#80) (Olaf Alders) 0.000043 2022-05-18 13:28:01Z - Relax TOML::Tiny version (GH#78) (James Raspass) 0.000042 2022-05-10 19:24:12Z - Fix exception which was thrown when only global config existed (GH#77) (Olaf Alders) 0.000041 2022-05-10 15:19:34Z - exit() from script rather than from module (GH#74) (Olaf Alders) - Find Perl files present in dirs, if they are passed as filename args (GH#75) (Olaf Alders) 0.000040 2022-05-06 13:25:15Z - Set minimum version of File::XDG to 1.01 (GH#73) (Olaf Alders) 0.000039 2022-05-05 21:55:32Z - Remove coercion which broke environments without config files (GH#71) (Olaf Alders) 0.000038 2022-05-05 20:45:48Z - This release adds (experimental and underdocumented) support for TOML config files (GH#69) (Olaf Alders) - The use of TOML::Tiny means we're bumping the minimum Perl to 5.18 0.000037 2022-05-02 20:58:40Z - This distribution no longer includes a fatpacked PPI (GH#70) (Olaf Alders) 0.000036 2022-04-29 13:09:44Z - Bump PPI from 1.272 to 1.273 - Allow multiple filenames to be passed to CLI (GH#68) (Olaf Alders) 0.000035 2022-02-23 00:35:26Z - Bump Perl::Tidy from 20211029 to 20220217 (GH#67) (Olaf Alders) - Bump PPI from 1.270 to 1.272 - Try to fix failures in t/never-exports.t 0.000034 2022-02-14 18:26:15Z - Don't try to rewrite an import that we can't eval (GH#66) (Olaf Alders) 0.000033 2022-02-11 23:20:52Z - Update forked PPI to include PPI 1.272 (GH#64) (Olaf Alders) - Avoid exceptions when trying to unnest quotes (GH#65) (Olaf Alders) 0.000032 2022-01-15 03:41:49Z - Require Perl::Tidy version 20211029 0.000031 2022-01-13 21:05:01Z - Ignore PerlIO::gzip and Modern::Perl - Rework formatting of Test::Builder modules (GH#61) (Olaf Alders) 0.000030 2021-12-21 22:55:49Z - Avoid calling methods on undef variable (GH#59) (Olaf Alders) - Preserve some arbitrary padding. It may have been added by a tidier. (GH#60) (Olaf Alders) 0.000029 2021-12-20 19:24:54Z - Improve import sort order (GH#58) (Olaf Alders) 0.000028 2021-12-18 02:26:13Z - Maintain stable sort order for lists which include sigils (GH#57) (Olaf Alders) 0.000027 2021-11-29 22:29:05Z - Detect Test::Builder objects used in import() (GH#56) (Olaf Alders) - Require Test::Script 1.29 0.000026 2021-11-26 21:35:12Z - Ignore Env.pm for the time being (GH#47) (Olaf Alders) - Allow module name to be passed to dump-perl-exports without flag (GH#46) (Olaf Alders) - Ignore Constant::Generate and Git::Sub (GH#46) (Olaf Alders) - Bump minimum Perl to 5.12.0 (GH#46) (Olaf Alders) - Ignore modules which we cannot eval (GH#49) (Olaf Alders) - Ignore Sort::ByExample and MLDBM - Ensure --no-tidy-whitespace is passed as a CLI param (GH#53) (Olaf Alders) - Ignore Import::Into (GH#52) (Olaf Alders) - Ignore more whitespace changes (GH#54) (Olaf Alders) 0.000025 2021-10-13 21:42:40Z - Add another minimum version to t/with-version.t (GH#43) (Olaf Alders) 0.000024 2021-10-12 15:58:08Z - Fix t/with-version.t on some machines by requiring the correct minimum needed module version via Test::Needs (GH#42) (Olaf Alders) 0.000023 2021-09-29 18:50:41Z - Eval import() statements before changing them (GH#40) (Olaf Alders) - Don't consider "my @Foo" to be a use of an imported "@Foo" (GH#40) (Olaf Alders) 0.000022 2021-09-27 01:31:43Z - Ensure PPI 1.270 is required in cpanfile (Reported by Slaven Rezić in #39) 0.000021 2021-09-25 23:51:02Z - Document how to configure Code::TidyAll and precious - Add Carp::Always to ignored modules - Require Log::Dispatch 2.70 0.000020 2021-09-23 22:49:41Z - Add a --log-filename parameter (GH#37) (Olaf Alders) - Add a --[no-]tidy-whitespace param (GH#38) (Olaf Alders) - Fix disappearing module version numbers (GH#38) (Olaf Alders) 0.000019 2021-09-17 19:20:44Z - Ignore modules with import errors (GH#35) (Olaf Alders) - Stop special-casing Import::Into (GH#35) (Olaf Alders) - Reduce required dependencies (GH#36) (Olaf Alders) - Add an examples folder (GH#36) (Olaf Alders) 0.000018 2021-09-07 18:41:28Z - Cover more object oriented modules (GH#32) (Olaf Alders) 0.000017 2021-07-17 15:54:27Z - Bump version of IP::Random used in tests. Fixes #30. (GH#31) (Olaf Alders) 0.000016 2021-07-09 17:54:06Z - Detect Module::->new syntax (GH#29) (Olaf Alders) - Fix some regex parsing behaviour (GH#29) (Olaf Alders) 0.000015 2021-07-08 22:35:18Z - Reduce false positives introduced by 0.000014 (GH#28) (Olaf Alders) 0.000014 2021-07-08 19:47:54Z - Detect symbols in nested quotes (GH#27) (Olaf Alders) 0.000013 2021-07-08 14:54:28Z - Detect functions used in regex replacements (GH#26) (Olaf Alders) 0.000012 2021-06-23 17:52:22Z - Fix a warning that was being triggered by the logger 0.000011 2021-06-14 20:24:05Z - Fix export tag test 0.000010 2021-06-12 03:25:27Z - Detect fully qualified symbol name interpolated in quotes - Ignore HTTP::Message::PSGI - Include docs for regex patterns which should have been included in 0.000009 0.000009 2021-06-10 18:41:59Z - Remove dependency on Data::Printer - Add support for ignoring modules via regular expression pattern (GH#16) (Nicolas Mendoza) - Silence "Use of uninitialized value" warning (GH#21) (Kenichi Ishigaki) - Export tag are now converted to symbols 0.000008 2021-06-08 10:42:56Z - Detect imported symbols used in prototypes - Ignore more modules - Make annotation regex less restrictive - Add --libs arg to dump-perl-exports - Detect when modules are only used via package variables - Detect subs which are only re-exported via Sub::Exporter - Optimize for speed a little bit more 0.000007 2021-05-27 15:24:53Z - Add an experimental --cache flag - Experiment with parsing signatures - Optimize (a little bit) for speed 0.000006 2021-05-04 22:28:39Z - Support ## no perlimports and ## use perlimports annotations (GH#5) (Olaf Alders) - Update docs to include --[no-]preserve-duplicates and --[no-]preserve-unused - Update docs on log-level - Remove FindBin as a runtime dependency 0.000005 2021-05-01 16:49:07Z - Require a minimum Data::Printer version of 0.36. 0.000004 2021-04-30 21:40:35Z - Be explicit about more module versions in tests. 0.000003 2021-04-29 03:00:10Z - Fix t/dump-perl-exports.t, which was sometimes testing against the wrong perl. 0.000002 2021-04-22 20:35:47Z - Add test-data to no_index directories. 0.000001 2021-04-22 20:10:45Z - Initial release. Caveat emptor. t000755001750001751 015261510577 14267 5ustar00olafolaf000000000000App-perlimports-0.000067cli.t100644001750001751 5262615261510577 15416 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!perl use strict; use warnings; use lib 'test-data/lib', 't/lib'; use App::perlimports::CLI (); use Capture::Tiny qw( capture ); use Cpanel::JSON::XS qw( decode_json ); use File::pushd qw( pushd ); use Path::Tiny (); use TestHelper qw( logger ); use Test::Differences qw( eq_or_diff ); use Test::Fatal qw( exception ); use Test::More import => [qw( diag done_testing is like ok subtest )]; use Test::Needs qw( Perl::Critic::Utils ); subtest 'bad path to config file' => sub { local @ARGV = ( '--config-file', 'test-data/XXX', 'test-data/a.pl', ); ok( App::perlimports::CLI->new, '_config_file builder is lazy' ); like( exception { App::perlimports::CLI->new->run }, qr{XXX not found}, 'not found' ); }; # Emulate a user with no local or global config file subtest 'no config files' => sub { my $dir = Path::Tiny->tempdir('testconfigXXXXXXXX'); local $ENV{XDG_CONFIG_HOME} = "$dir"; local @ARGV = ('--version'); my $pushd = pushd("$dir"); my $cli = App::perlimports::CLI->new; my ($stdout) = capture { $cli->run }; like( $stdout, qr{$App::perlimports::CLI::VERSION}, 'prints version' ); }; # Emulate a user with only a global config file subtest 'no local config file' => sub { my $xdg_config_home = Path::Tiny->tempdir('testconfigXXXXXXXX'); local $ENV{XDG_CONFIG_HOME} = $xdg_config_home->stringify; my $global_config_dir = $xdg_config_home->child('perlimports'); $global_config_dir->mkpath; my $global_config = $global_config_dir->child('perlimports.toml'); local @ARGV = ( '--create-config-file', $global_config ); is( App::perlimports::CLI->new->run, '0', 'clean exit code' ); ok( -e $global_config, 'file created' ); my $project_dir = Path::Tiny->tempdir('testconfigXXXXXXXX'); my $pushd = pushd("$project_dir"); my $cli = App::perlimports::CLI->new; is( $cli->_config_file, $global_config, 'config file found' ); # Try to recreate config file local @ARGV = ( '--create-config-file', $global_config ); my $exit_code; my ( undef, $stderr ) = capture { $exit_code = App::perlimports::CLI->new->run }; like( $stderr, qr{perlimports.toml already exists}, 'perlimports.toml already exists' ); is( $exit_code, 1, 'non-zero exit code' ); }; subtest 'help' => sub { local @ARGV = ('--help'); my $cli = App::perlimports::CLI->new; my ($stdout) = capture { $cli->run }; like( $stdout, qr{filename STR}, 'prints help' ); }; subtest 'verbose help' => sub { local @ARGV = ('--verbose-help'); # Verbose text on $0, which will differ when this is called from # script/perlimports local $0 = 'script/perlimports'; my $cli = App::perlimports::CLI->new; my ($stdout) = capture { $cli->run }; like( $stdout, qr{Create a sample config file}, 'prints help' ); }; subtest filter_paths => sub { ## no critic (Subroutines::ProtectPrivateSubs) my @paths = App::perlimports::CLI::_filter_paths( 'test-data/filter-paths', 'test-data/filter-paths/foo.t' ); ## use critic eq_or_diff( [ sort @paths ], [ 'test-data/filter-paths/Foo.pl', 'test-data/filter-paths/Foo.pm', 'test-data/filter-paths/foo', 'test-data/filter-paths/foo.t', ] ); }; subtest '--filename' => sub { my $expected = <<'EOF'; use strict; use warnings; use Perl::Critic::Utils qw( $QUOTE ); my %foo = ( $QUOTE => q{description}, ); EOF local @ARGV = ( '--no-config-file', '-f' => 'test-data/var-in-hash-key.pl', ); my $cli = App::perlimports::CLI->new( logger => logger( [] ) ); my ($stdout) = capture { $cli->run; }; is( $stdout, $expected, 'parses filename' ); }; subtest 'invalid --filename' => sub { local @ARGV = ( '--no-config-file', '-f' => 'test-data/does-not-exist.pl', ); my $cli = App::perlimports::CLI->new(); my ( $stdout, $stderr, $exit_code ) = capture { $cli->run; }; is( $stdout, q{}, 'no STDOUT' ); like( $stderr, qr{test-data/does-not-exist.pl does not appear to be a file}, 'STDERR contains appropriate error message' ); is( $exit_code, 1, 'exit code is error' ); }; subtest '--lint success' => sub { local @ARGV = ( '--lint', '--no-config-file', '-f' => 'test-data/lint-success.pl', ); my $cli = App::perlimports::CLI->new; my ( $stdout, $stderr, $exit ) = capture { $cli->run; }; is( $stdout, "test-data/lint-success.pl OK\n", 'success message on STDOUT' ); is( $stderr, q{}, 'no STDERR on a clean run (GH #163)' ); is( $exit, 0, 'exit code is success' ); }; subtest '--lint --json success' => sub { local @ARGV = ( '--lint', '--json', '--no-config-file', '-f' => 'test-data/lint-success.pl', ); my $cli = App::perlimports::CLI->new; my ( $stdout, $stderr, $exit ) = capture { $cli->run; }; is( $stderr, q{}, 'success message on STDERR' ); is( $stdout, q{}, 'no STDOUT' ); is( $exit, 0, 'exit code is success' ); }; subtest '--lint failure import args' => sub { local @ARGV = ( '--lint', '--no-config-file', '-f' => 'test-data/lint-failure-import-args.pl', ); my $cli = App::perlimports::CLI->new; my ( $stdout, $stderr, $exit ) = capture { $cli->run; }; is( $stdout, q{}, 'no STDOUT' ); my $expected = <<'EOF'; ❌ Perl::Critic::Utils (import arguments need tidying) at test-data/lint-failure-import-args.pl line 4 @@ -4 +4 @@ -use Perl::Critic::Utils; +use Perl::Critic::Utils qw( $QUOTE ); EOF is( $stderr, $expected, 'STDERR' ); is( $exit, 1, 'exit code is error' ); }; subtest '--lint --quiet success' => sub { local @ARGV = ( '--lint', '--quiet', '--no-config-file', '-f' => 'test-data/lint-success.pl', ); my $cli = App::perlimports::CLI->new; my ( $stdout, $stderr, $exit ) = capture { $cli->run; }; is( $stdout, q{}, 'no STDOUT with --quiet on a clean run' ); is( $stderr, q{}, 'no STDERR with --quiet on a clean run' ); is( $exit, 0, 'exit code is success' ); }; subtest '--lint -q success' => sub { local @ARGV = ( '--lint', '-q', '--no-config-file', '-f' => 'test-data/lint-success.pl', ); my $cli = App::perlimports::CLI->new; my ( $stdout, $stderr, $exit ) = capture { $cli->run; }; is( $stdout, q{}, 'no STDOUT with -q on a clean run' ); is( $stderr, q{}, 'no STDERR with -q on a clean run' ); is( $exit, 0, 'exit code is success' ); }; subtest '--lint --quiet failure still reports diagnostics' => sub { local @ARGV = ( '--lint', '--quiet', '--no-config-file', '-f' => 'test-data/lint-failure-import-args.pl', ); my $cli = App::perlimports::CLI->new; my ( $stdout, $stderr, $exit ) = capture { $cli->run; }; my $expected = <<'EOF'; ❌ Perl::Critic::Utils (import arguments need tidying) at test-data/lint-failure-import-args.pl line 4 @@ -4 +4 @@ -use Perl::Critic::Utils; +use Perl::Critic::Utils qw( $QUOTE ); EOF is( $stdout, q{}, 'no STDOUT' ); # --quiet suppresses the success summary and info/notice noise, but must # not swallow genuine failure diagnostics (logged at the error level). is( $stderr, $expected, 'failure diagnostics survive --quiet (GH #163)' ); is( $exit, 1, 'exit code is error' ); }; subtest '--lint --json --quiet failure still reports JSON' => sub { local @ARGV = ( '--lint', '--json', '--quiet', '--no-config-file', '-f' => 'test-data/lint-failure-import-args.pl', ); my $cli = App::perlimports::CLI->new; my ( $stdout, $stderr, $exit ) = capture { $cli->run; }; is( $stdout, q{}, 'no STDOUT' ); is( $exit, 1, 'exit code is error' ); # The machine-readable JSON diagnostic is logged at the error level, so # --quiet must not discard it -- a CI consumer needs the payload. like( $stderr, qr{"diff"}, 'JSON failure diagnostic survives --json --quiet (GH #163)' ); my $decoded; is( exception { $decoded = decode_json($stderr) }, undef, 'STDERR is valid JSON' ) or diag($stderr); is( $decoded->{module}, 'Perl::Critic::Utils', 'JSON reports the offending module' ); }; subtest '--lint --json --quiet success' => sub { local @ARGV = ( '--lint', '--json', '--quiet', '--no-config-file', '-f' => 'test-data/lint-success.pl', ); my $cli = App::perlimports::CLI->new; my ( $stdout, $stderr, $exit ) = capture { $cli->run; }; is( $stdout, q{}, 'no STDOUT with --json --quiet' ); is( $stderr, q{}, 'no STDERR with --json --quiet' ); is( $exit, 0, 'exit code is success' ); }; subtest '--lint --log-level=notice noise (control)' => sub { local @ARGV = ( '--lint', '--log-level' => 'notice', '--no-config-file', '-f' => 'test-data/lint-success.pl', ); my $cli = App::perlimports::CLI->new; my ( undef, $stderr, $exit ) = capture { $cli->run; }; like( $stderr, qr{Starting file}, 'notice-level log noise appears without --quiet' ); is( $exit, 0, 'exit code is success' ); }; subtest '--lint --log-level=notice --quiet suppresses log noise' => sub { local @ARGV = ( '--lint', '--log-level' => 'notice', '--quiet', '--no-config-file', '-f' => 'test-data/lint-success.pl', ); my $cli = App::perlimports::CLI->new; my ( $stdout, $stderr, $exit ) = capture { $cli->run; }; is( $stdout, q{}, 'no STDOUT with --quiet' ); is( $stderr, q{}, 'notice noise and OK line both suppressed by --quiet' ); is( $exit, 0, 'exit code is success' ); }; subtest '--quiet does not silence an explicit --log-filename' => sub { my $log = Path::Tiny->tempfile('perlimports-logXXXXXX'); local @ARGV = ( '--lint', '--log-level' => 'notice', '--quiet', '--log-filename' => "$log", '--no-config-file', '-f' => 'test-data/lint-success.pl', ); my $cli = App::perlimports::CLI->new; my ( $stdout, $stderr, $exit ) = capture { $cli->run; }; is( $stdout, q{}, 'no STDOUT' ); is( $stderr, q{}, 'no STDERR (logging is redirected to the file)' ); like( $log->slurp_utf8, qr{Starting file}, 'file log keeps notice-level messages despite --quiet' ); is( $exit, 0, 'exit code is success' ); }; subtest '--lint failure unused import' => sub { local @ARGV = ( '--lint', '--no-config-file', '--no-preserve-unused', '-f' => 'test-data/lint-failure-unused-import.pl', ); my $cli = App::perlimports::CLI->new; my ( $stdout, $stderr, $exit ) = capture { $cli->run; }; is( $stdout, q{}, 'no STDOUT' ); my $expected = <<'EOF'; ❌ Carp (appears to be unused and should be removed) at test-data/lint-failure-unused-import.pl line 6 @@ -6 +5,0 @@ -use Carp; EOF is( $stderr, $expected, 'STDERR' ); is( $exit, 1, 'exit code is error' ); }; subtest '--lint failure duplicate import' => sub { local @ARGV = ( '--lint', '--no-config-file', '--no-preserve-duplicates', '-f' => 'test-data/lint-failure-duplicate-import.pl', ); my $cli = App::perlimports::CLI->new; my ( $stdout, $stderr, $exit ) = capture { $cli->run; }; is( $stdout, q{}, 'no STDOUT' ); my $expected = <<'EOF'; ❌ Carp (has already been used and should be removed) at test-data/lint-failure-duplicate-import.pl line 7 @@ -7 +6,0 @@ -use Carp; EOF is( $stderr, $expected, 'STDERR' ); is( $exit, 1, 'exit code is error' ); }; subtest '--lint --json failure duplicate import' => sub { local @ARGV = ( '--lint', '--json', '--no-config-file', '--no-preserve-duplicates', '-f' => 'test-data/lint-failure-duplicate-import.pl', ); my $cli = App::perlimports::CLI->new; my ( $stdout, $stderr, $exit ) = capture { $cli->run; }; is( $stdout, q{}, 'no STDOUT' ); my $parsed_stderr = decode_json($stderr); eq_or_diff( $parsed_stderr, { diff => "@@ -7 +6,0 @@\n-use Carp;\n", filename => 'test-data/lint-failure-duplicate-import.pl', location => { end => { column => 9, line => 7, }, start => { column => 1, line => 7, }, }, module => 'Carp', reason => 'has already been used and should be removed', }, 'lint failure as JSON' ); is( $exit, 1, 'exit code is error' ); }; subtest '--lint --json location reports the true column of an indented include' => sub { local @ARGV = ( '--lint', '--json', '--no-config-file', '--no-preserve-duplicates', '-f' => 'test-data/lint-failure-indented-duplicate.pl', ); my $cli = App::perlimports::CLI->new; my ( $stdout, $stderr, $exit ) = capture { $cli->run; }; is( $stdout, q{}, 'no STDOUT' ); my $parsed_stderr = decode_json($stderr); # The redundant `use Carp;` is indented four spaces inside a block, so the # start column is 5 (not 1) and the end column is 13 (inclusive). eq_or_diff( $parsed_stderr->{location}, { start => { line => 8, column => 5 }, end => { line => 8, column => 13 }, }, 'location reflects the indentation of the include' ); is( $exit, 1, 'exit code is error' ); }; subtest '--sort --json failure reports location and diff' => sub { local @ARGV = ( '--lint', '--json', '--sort', '--no-config-file', '-f' => 'test-data/sort-includes.pl', ); my $cli = App::perlimports::CLI->new; my ( $stdout, $stderr, $exit ) = capture { $cli->run; }; is( $stdout, q{}, 'no STDOUT' ); my $parsed_stderr = decode_json($stderr); is( $parsed_stderr->{reason}, 'includes are not sorted', 'reason is present' ); is( $parsed_stderr->{filename}, 'test-data/sort-includes.pl', 'filename is present' ); eq_or_diff( $parsed_stderr->{location}, { start => { line => 2, column => 1 }, end => { line => 4, column => 8 }, }, 'location spans the changed includes' ); ok( length $parsed_stderr->{diff}, 'diff is present and non-empty' ); ok( !exists $parsed_stderr->{module}, 'module is omitted' ); is( $exit, 1, 'exit code is error' ); }; subtest '--log-filename' => sub { my $expected = <<'EOF'; use strict; use warnings; use Perl::Critic::Utils qw( $QUOTE ); my %foo = ( $QUOTE => q{description}, ); EOF my $file = Path::Tiny->tempfile; local @ARGV = ( '-f' => 'test-data/var-in-hash-key.pl', '--log-filename' => "$file", '--log-level' => 'info', '--no-config-file', ); my $cli = App::perlimports::CLI->new; my ($stdout) = capture { $cli->run; }; is( $stdout, $expected, 'parses filename' ); ok( $file->lines, 'something was logged to file' ); }; subtest 'no filename' => sub { local @ARGV = (); my $cli = App::perlimports::CLI->new; my ( undef, $stderr ) = capture { $cli->run; }; like( $stderr, qr{Mandatory parameter 'filename' missing}, 'filename missing' ); }; subtest '--json without --lint' => sub { local @ARGV = ( '--json', 'test-data/var-in-hash-key.pl' ); my $cli = App::perlimports::CLI->new; my ( undef, $stderr ) = capture { $cli->run; }; like( $stderr, qr{--json can only be used with --lint}, 'meaningless --json flag' ); }; subtest '--lint with -i' => sub { local @ARGV = ( '--lint', '-i', 'test-data/var-in-hash-key.pl' ); my $cli = App::perlimports::CLI->new; my ( undef, $stderr ) = capture { $cli->run; }; like( $stderr, qr{Cannot lint if inplace edit has been enabled}, 'trying to edit and lint at once' ); }; subtest '--ignore-modules' => sub { my $expected = <<'EOF'; use strict; use warnings; use Perl::Critic::Utils; my %foo = ( $QUOTE => q{description}, ); EOF local @ARGV = ( '--no-config-file', '--ignore-modules' => 'Perl::Critic::Utils', '-f' => 'test-data/var-in-hash-key.pl', ); my $cli = App::perlimports::CLI->new; my ($stdout) = capture { $cli->run }; is( $stdout, $expected, 'stdout' ); }; subtest '--ignore-modules-pattern' => sub { my $expected = <<'EOF'; use strict; use warnings; use Perl::Critic::Utils; my %foo = ( $QUOTE => q{description}, ); EOF local @ARGV = ( '--no-config-file', '--ignore-modules-pattern' => '^Perl::.*', '-f' => 'test-data/var-in-hash-key.pl', ); my $cli = App::perlimports::CLI->new; my ($stdout) = capture { $cli->run }; is( $stdout, $expected, 'stdout' ); }; subtest '--never-export-modules' => sub { my $expected = <<'EOF'; use strict; use warnings; use Perl::Critic::Utils (); my %foo = ( $QUOTE => q{description}, ); EOF local @ARGV = ( '--no-config-file', '--never-export-modules' => 'Perl::Critic::Utils', '-f' => 'test-data/var-in-hash-key.pl', ); my $cli = App::perlimports::CLI->new; my ($stdout) = capture { $cli->run }; is( $stdout, $expected, 'stdout' ); }; subtest '--no-padding' => sub { my $expected = <<'EOF'; use strict; use warnings; use Perl::Critic::Utils qw($QUOTE); my %foo = ( $QUOTE => q{description}, ); EOF local @ARGV = ( '--no-config-file', '--no-padding', '-f' => 'test-data/var-in-hash-key.pl', ); my $cli = App::perlimports::CLI->new; my ( $stdout, $stderr ) = capture { $cli->run }; is( $stderr, q{}, 'no STDERR' ); is( $stdout, $expected, 'stdout' ); }; subtest '--stdout' => sub { my $expected = <<'EOF'; use strict; use warnings; use Local::STDOUT (); BEGIN { print "perlimports should trap this"; } EOF local @ARGV = ( '--no-config-file', '--libs' => 'test-data/lib', '-f' => 'test-data/stdout.pl', ); my $cli = App::perlimports::CLI->new; my ( $stdout, $stderr ) = capture { $cli->run }; is( $stderr, q{}, 'no STDERR' ); eq_or_diff( $stdout, $expected ); }; subtest 'range without end' => sub { local @ARGV = ( '--range-begin', 1, 'test-data/stdout.pl', ); my $expected = 'You must supply both range_begin and range_end'; my $cli = App::perlimports::CLI->new; my ( $stdout, $stderr ) = capture { $cli->run }; is( $stdout, q{}, 'no STDOUT' ); chomp($stderr); eq_or_diff( $stderr, $expected ); }; subtest 'range without begin' => sub { local @ARGV = ( '--range-end', 1, 'test-data/stdout.pl', ); my $expected = 'You must supply both range_begin and range_end'; my $cli = App::perlimports::CLI->new; my ( $stdout, $stderr ) = capture { $cli->run }; is( $stdout, q{}, 'no STDOUT' ); chomp($stderr); eq_or_diff( $stderr, $expected ); }; subtest 'range without --read-stdin' => sub { local @ARGV = ( '--range-begin', 1, '--range-end', 1, 'test-data/stdout.pl', ); my $expected = 'You must specify --read-stdin if you provide a range'; my $cli = App::perlimports::CLI->new; my ( $stdout, $stderr ) = capture { $cli->run }; is( $stdout, q{}, 'no STDOUT' ); chomp($stderr); eq_or_diff( $stderr, $expected ); }; subtest 'range correct' => sub { local @ARGV = ( '--range-begin', 1, '--range-end', 1, '--read-stdin', 'test-data/stdout.pl', ); my $cli = App::perlimports::CLI->new; my ( $stdout, $stderr ) = capture { $cli->run }; eq_or_diff( $stderr, q{}, 'no STDERR' ); eq_or_diff( $stdout, 'use strict;', 'range returned on STDOUT' ); }; subtest 'entire document range' => sub { local @ARGV = ( '--range-begin', 1, '--range-end', 8, '--read-stdin', 'test-data/stdout.pl', ); my $cli = App::perlimports::CLI->new; my ( $stdout, $stderr ) = capture { $cli->run }; my $expected = <<'EOF'; use strict; use warnings; BEGIN { print "perlimports should trap this"; } EOF chomp $expected; eq_or_diff( $stderr, q{}, 'no STDERR' ); eq_or_diff( $stdout, $expected, 'range returned on STDOUT' ); }; subtest 'STDIN without document range' => sub { local @ARGV = ( '--read-stdin', '--filename', 'test-data/stdout.pl', ); my $cli = App::perlimports::CLI->new; my ( $stdout, $stderr ) = capture { $cli->run }; my $expected = <<'EOF'; use strict; use warnings; BEGIN { print "perlimports should trap this"; } EOF eq_or_diff( $stderr, q{}, 'no STDERR' ); eq_or_diff( $stdout, $expected, 'range returned on STDOUT' ); }; done_testing(); env.t100644001750001751 761215261510577 15412 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!/usr/bin/env perl use strict; use warnings; use lib 't/lib'; use Test::Differences qw( eq_or_diff ); use TestHelper qw( doc ); use Test::More import => [qw( done_testing subtest )]; use Test::Needs qw( Env ); # Env ties environment variables to Perl variables. There is no @EXPORT to # discover: whatever you import is exactly what you asked for. So perlimports # treats the arguments of each "use Env" statement as its own exportable # symbols and prunes the ones which are not used. See GH #23. subtest 'used array import is preserved' => sub { my ($doc) = doc( filename => 'test-data/env.pl' ); my $expected = <<'EOF'; use strict; use warnings; use Env qw( @PATH ); my @copy = @PATH; EOF eq_or_diff( $doc->tidied_document, $expected, '@PATH is kept because it is used', ); }; subtest 'unused import is pruned to an empty list' => sub { my ($doc) = doc( filename => 'test-data/env-unused.pl' ); my $expected = <<'EOF'; use strict; use warnings; use Env (); my $x = 1; EOF eq_or_diff( $doc->tidied_document, $expected, 'unused @PATH becomes use Env ()', ); }; subtest 'mixed imports keep only the used symbol' => sub { my ($doc) = doc( filename => 'test-data/env-mixed.pl' ); my $expected = <<'EOF'; use strict; use warnings; use Env qw( @PATH ); my @copy = @PATH; EOF eq_or_diff( $doc->tidied_document, $expected, 'unused $HOME is dropped, used @PATH is kept', ); }; subtest 'bareword scalar import is preserved as written' => sub { my ($doc) = doc( filename => 'test-data/env-scalar.pl' ); my $expected = <<'EOF'; use strict; use warnings; use Env qw( HOME ); my $h = $HOME; EOF eq_or_diff( $doc->tidied_document, $expected, 'bareword HOME is kept (and not rewritten to $HOME) because $HOME is used', ); }; subtest 'interpolated scalar counts as used' => sub { my ($doc) = doc( filename => 'test-data/env-interpolated.pl' ); my $expected = <<'EOF'; use strict; use warnings; use Env qw( HOME ); print "home is $HOME\n"; EOF eq_or_diff( $doc->tidied_document, $expected, 'HOME is kept because $HOME is interpolated into a string', ); }; subtest 'module version is preserved while pruning' => sub { my ($doc) = doc( filename => 'test-data/env-version.pl' ); my $expected = <<'EOF'; use strict; use warnings; use Env 1.00 qw( @PATH ); my @copy = @PATH; EOF eq_or_diff( $doc->tidied_document, $expected, 'the version stays, unused $HOME is dropped, used @PATH is kept', ); }; subtest 'comma-separated (non-qw) args are handled' => sub { my ($doc) = doc( filename => 'test-data/env-comma.pl' ); my $expected = <<'EOF'; use strict; use warnings; use Env qw( @PATH ); my @copy = @PATH; EOF eq_or_diff( $doc->tidied_document, $expected, q{'HOME', '@PATH' list drops unused HOME and normalizes to qw()}, ); }; subtest 'preserve_unused => 0 removes an entirely unused use Env' => sub { my ($doc) = doc( filename => 'test-data/env-unused.pl', preserve_unused => 0 ); # The whole statement is removed (this is the general unused-module # removal path, not specific to Env); the surrounding blank lines are # left as-is, as they are for any other removed import. my $expected = <<'EOF'; use strict; use warnings; my $x = 1; EOF eq_or_diff( $doc->tidied_document, $expected, 'an unused use Env line is deleted, not left as use Env ()', ); }; subtest 'bare use Env is left untouched' => sub { my ($doc) = doc( filename => 'test-data/env-bare.pl' ); my $expected = <<'EOF'; use strict; use warnings; use Env; my $h = $HOME; EOF eq_or_diff( $doc->tidied_document, $expected, 'a bare "use Env;" imports everything and has no args to prune', ); }; done_testing(); moo.t100755001750001751 234315261510577 15413 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!/usr/bin/env perl use strict; use warnings; use lib 'test-data/lib', 't/lib'; use TestHelper qw( doc ); use Test::More import => [qw( done_testing is subtest )]; use Test::Needs qw( Import::Into ); subtest 'Moo' => sub { my ($doc) = doc( filename => 'test-data/lib/Local/UsesMoo.pm', selection => 'use Moo;' ); is( $doc->tidied_document, 'use Moo;', 'document unchanged' ); }; subtest 'Import::Into' => sub { my ($doc) = doc( filename => 'test-data/lib/Local/MyOwnMoo.pm', preserve_unused => 0, ); my $expected = <<'EOF'; package Local::MyOwnMoo; use strict; use warnings; use Import::Into; sub import { $_->import::into( scalar caller ) for qw( Moo ); } 1; EOF is( $doc->tidied_document, $expected, 'tidied_document' ); }; subtest 'Uses MyOwnMoo' => sub { my ($doc) = doc( filename => 'test-data/lib/Local/UsesMyOwnMoo.pm', preserve_unused => 0, ); my $expected = <<'EOF'; package Local::UsesMyOwnMoo; use strict; use warnings; use Local::MyOwnMoo; 1; EOF is( $doc->tidied_document, $expected, 'tidied_document' ); }; done_testing(); tie.t100644001750001751 65415261510577 15362 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use lib 't/lib'; use Path::Tiny qw( path ); use TestHelper qw( doc ); use Test::More import => [qw( done_testing is $TODO )]; my $filename = 'test-data/tie.pl'; my ($doc) = doc( filename => $filename, preserve_unused => 0, ); TODO: { local $TODO = 'Cannot yet see packages used by tie'; is( $doc->tidied_document, path($filename)->slurp, 'tie observed' ); } done_testing(); cpanfile100644001750001751 657715261510577 15707 0ustar00olafolaf000000000000App-perlimports-0.000067# This file is generated by Dist::Zilla::Plugin::CPANFile v6.037 # Do not edit this file directly. To change prereqs, edit the `dist.ini` file. requires "Capture::Tiny" => "0"; requires "Class::Inspector" => "1.36"; requires "Cpanel::JSON::XS" => "0"; requires "Data::Dumper" => "0"; requires "Data::UUID" => "0"; requires "File::Basename" => "0"; requires "File::XDG" => "1.01"; requires "Getopt::Long::Descriptive" => "0"; requires "List::Util" => "0"; requires "Log::Dispatch" => "2.70"; requires "Memoize" => "0"; requires "Module::Runtime" => "0"; requires "Moo" => "0"; requires "Moo::Role" => "0"; requires "MooX::StrictConstructor" => "0"; requires "PPI" => "1.276"; requires "PPI::Document" => "0"; requires "PPIx::Utils::Classification" => "0"; requires "PPIx::Utils::Traversal" => "0"; requires "Path::Iterator::Rule" => "0"; requires "Path::Tiny" => "0"; requires "Perl::Tidy" => "20220613"; requires "Pod::Usage" => "0"; requires "Ref::Util" => "0"; requires "Scalar::Util" => "0"; requires "Sereal::Decoder" => "0"; requires "Sereal::Encoder" => "0"; requires "Sub::HandlesVia" => "0"; requires "Symbol::Get" => "0.10"; requires "TOML::Tiny" => "0.16"; requires "Text::Diff" => "0"; requires "Text::SimpleTable::AutoWidth" => "0"; requires "Try::Tiny" => "0"; requires "Types::Common::Numeric" => "0"; requires "Types::Standard" => "0"; requires "feature" => "0"; requires "perl" => "v5.18.0"; requires "strict" => "0"; requires "utf8" => "0"; requires "warnings" => "0"; on 'test' => sub { requires "ExtUtils::MakeMaker" => "0"; requires "File::Spec" => "0"; requires "File::pushd" => "0"; requires "Log::Dispatch::Array" => "0"; requires "PPI::Dumper" => "0"; requires "Sub::Exporter" => "0"; requires "Test::Differences" => "0"; requires "Test::Fatal" => "0"; requires "Test::More" => "0"; requires "Test::Needs" => "0"; requires "Test::RequiresInternet" => "0"; requires "Test::Script" => "1.29"; requires "Test::Warnings" => "0"; requires "lib" => "0"; requires "perl" => "v5.18.0"; }; on 'test' => sub { recommends "CPAN::Meta" => "2.120900"; }; on 'configure' => sub { requires "ExtUtils::MakeMaker" => "0"; requires "perl" => "5.013002"; }; on 'develop' => sub { requires "Code::TidyAll" => "0.71"; requires "Code::TidyAll::Plugin::SortLines::Naturally" => "0.000003"; requires "Code::TidyAll::Plugin::Test::Vars" => "0.04"; requires "Code::TidyAll::Plugin::UniqueLines" => "0.000003"; requires "Parallel::ForkManager" => "1.19"; requires "Perl::Critic" => "1.132"; requires "Perl::Critic::Bangs" => "1.10"; requires "Perl::Critic::Freenode" => "0"; requires "Perl::Critic::Moose" => "0"; requires "Perl::Critic::Policy::ValuesAndExpressions::ProhibitAccessOfPrivateData" => "v1.0.0"; requires "Perl::Critic::Policy::Variables::ProhibitUnusedVarsStricter" => "0.116"; requires "Perl::Tidy" => "20180220"; requires "Pod::Coverage::TrustPod" => "0"; requires "Pod::Wordlist" => "0"; requires "Test::CPAN::Changes" => "0.19"; requires "Test::EOL" => "0"; requires "Test::Mojibake" => "0"; requires "Test::More" => "0.96"; requires "Test::Pod" => "1.41"; requires "Test::Pod::Coverage" => "1.08"; requires "Test::Portability::Files" => "0"; requires "Test::Spelling" => "0.17"; requires "Test::Vars" => "0.014"; requires "Test::Version" => "1"; }; on 'develop' => sub { recommends "Dist::Zilla::PluginBundle::Git::VersionManager" => "0.007"; }; META.yml100644001750001751 4545515261510577 15472 0ustar00olafolaf000000000000App-perlimports-0.000067--- abstract: 'Make implicit imports explicit' author: - 'Olaf Alders ' build_requires: ExtUtils::MakeMaker: '0' File::Spec: '0' File::pushd: '0' Log::Dispatch::Array: '0' PPI::Dumper: '0' Sub::Exporter: '0' Test::Differences: '0' Test::Fatal: '0' Test::More: '0' Test::Needs: '0' Test::RequiresInternet: '0' Test::Script: '1.29' Test::Warnings: '0' lib: '0' perl: v5.18.0 configure_requires: ExtUtils::MakeMaker: '0' perl: '5.013002' dynamic_config: 0 generated_by: 'Dist::Zilla version 6.037, CPAN::Meta::Converter version 2.150013' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: App-perlimports no_index: directory: - examples - t - test-data - xt requires: Capture::Tiny: '0' Class::Inspector: '1.36' Cpanel::JSON::XS: '0' Data::Dumper: '0' Data::UUID: '0' File::Basename: '0' File::XDG: '1.01' Getopt::Long::Descriptive: '0' List::Util: '0' Log::Dispatch: '2.70' Memoize: '0' Module::Runtime: '0' Moo: '0' Moo::Role: '0' MooX::StrictConstructor: '0' PPI: '1.276' PPI::Document: '0' PPIx::Utils::Classification: '0' PPIx::Utils::Traversal: '0' Path::Iterator::Rule: '0' Path::Tiny: '0' Perl::Tidy: '20220613' Pod::Usage: '0' Ref::Util: '0' Scalar::Util: '0' Sereal::Decoder: '0' Sereal::Encoder: '0' Sub::HandlesVia: '0' Symbol::Get: '0.10' TOML::Tiny: '0.16' Text::Diff: '0' Text::SimpleTable::AutoWidth: '0' Try::Tiny: '0' Types::Common::Numeric: '0' Types::Standard: '0' feature: '0' perl: v5.18.0 strict: '0' utf8: '0' warnings: '0' resources: bugtracker: https://github.com/perl-ide/App-perlimports/issues homepage: https://github.com/perl-ide/App-perlimports repository: https://github.com/perl-ide/App-perlimports.git version: '0.000067' x_Dist_Zilla: perl: version: '5.042002' plugins: - class: Dist::Zilla::Plugin::PromptIfStale config: Dist::Zilla::Plugin::PromptIfStale: check_all_plugins: 0 check_all_prereqs: 0 modules: - Dist::Zilla::PluginBundle::Author::OALDERS phase: build run_under_travis: 0 skip: [] name: '@Author::OALDERS/stale modules, build' version: '0.060' - class: Dist::Zilla::Plugin::PromptIfStale config: Dist::Zilla::Plugin::PromptIfStale: check_all_plugins: 1 check_all_prereqs: 1 modules: [] phase: release run_under_travis: 0 skip: [] name: '@Author::OALDERS/stale modules, release' version: '0.060' - class: Dist::Zilla::Plugin::AutoPrereqs name: '@Author::OALDERS/AutoPrereqs' version: '6.037' - class: Dist::Zilla::Plugin::CheckChangesHasContent name: '@Author::OALDERS/CheckChangesHasContent' version: '0.011' - class: Dist::Zilla::Plugin::MakeMaker config: Dist::Zilla::Role::TestRunner: default_jobs: '8' name: '@Author::OALDERS/MakeMaker' version: '6.037' - class: Dist::Zilla::Plugin::CPANFile name: '@Author::OALDERS/CPANFile' version: '6.037' - class: Dist::Zilla::Plugin::ContributorsFile name: '@Author::OALDERS/ContributorsFile' version: 0.4.0 - class: Dist::Zilla::Plugin::MetaJSON name: '@Author::OALDERS/MetaJSON' version: '6.037' - class: Dist::Zilla::Plugin::MetaYAML name: '@Author::OALDERS/MetaYAML' version: '6.037' - class: Dist::Zilla::Plugin::Manifest name: '@Author::OALDERS/Manifest' version: '6.037' - class: Dist::Zilla::Plugin::MetaNoIndex name: '@Author::OALDERS/MetaNoIndex' version: '6.037' - class: Dist::Zilla::Plugin::MetaConfig name: '@Author::OALDERS/MetaConfig' version: '6.037' - class: Dist::Zilla::Plugin::MetaResources name: '@Author::OALDERS/MetaResources' version: '6.037' - class: Dist::Zilla::Plugin::License name: '@Author::OALDERS/License' version: '6.037' - class: Dist::Zilla::Plugin::InstallGuide config: Dist::Zilla::Role::ModuleMetadata: Module::Metadata: '1.000038' version: '0.006' name: '@Author::OALDERS/InstallGuide' version: '1.200014' - class: Dist::Zilla::Plugin::Prereqs config: Dist::Zilla::Plugin::Prereqs: phase: develop type: requires name: '@Author::OALDERS/Modules for use with tidyall' version: '6.037' - class: Dist::Zilla::Plugin::ExecDir name: '@Author::OALDERS/ExecDir' version: '6.037' - class: Dist::Zilla::Plugin::Test::PodSpelling config: Dist::Zilla::Plugin::Test::PodSpelling: directories: - bin - lib spell_cmd: '' stopwords: - Alders - "Alders'" - PPI - sandboxed wordlist: Pod::Wordlist name: '@Author::OALDERS/Test::PodSpelling' version: '2.007006' - class: Dist::Zilla::Plugin::MojibakeTests name: '@Author::OALDERS/MojibakeTests' version: '0.8' - class: Dist::Zilla::Plugin::PodSyntaxTests name: '@Author::OALDERS/PodSyntaxTests' version: '6.037' - class: Dist::Zilla::Plugin::Test::CPAN::Changes config: Dist::Zilla::Plugin::Test::CPAN::Changes: changelog: Changes filename: xt/release/cpan-changes.t name: '@Author::OALDERS/Test::CPAN::Changes' version: '0.013' - class: Dist::Zilla::Plugin::Test::EOL config: Dist::Zilla::Plugin::Test::EOL: filename: xt/author/eol.t finder: - ':ExecFiles' - ':InstallModules' - ':TestFiles' trailing_whitespace: 1 name: '@Author::OALDERS/Test::EOL' version: '0.19' - class: Dist::Zilla::Plugin::Test::Pod::Coverage::Configurable name: '@Author::OALDERS/Test::Pod::Coverage::Configurable' version: '0.07' - class: Dist::Zilla::Plugin::Test::Portability config: Dist::Zilla::Plugin::Test::Portability: options: '' name: '@Author::OALDERS/Test::Portability' version: '2.001003' - class: Dist::Zilla::Plugin::TestRelease name: '@Author::OALDERS/TestRelease' version: '6.037' - class: Dist::Zilla::Plugin::Test::ReportPrereqs name: '@Author::OALDERS/Test::ReportPrereqs' version: '0.029' - class: Dist::Zilla::Plugin::Test::Version name: '@Author::OALDERS/Test::Version' version: '1.09' - class: Dist::Zilla::Plugin::RunExtraTests config: Dist::Zilla::Role::TestRunner: default_jobs: '8' name: '@Author::OALDERS/RunExtraTests' version: '0.029' - class: Dist::Zilla::Plugin::MinimumPerl name: '@Author::OALDERS/MinimumPerl' version: '1.006' - class: Dist::Zilla::Plugin::PodWeaver config: Dist::Zilla::Plugin::PodWeaver: finder: - ':InstallModules' - ':PerlExecFiles' plugins: - class: Pod::Weaver::Plugin::EnsurePod5 name: '@CorePrep/EnsurePod5' version: '4.020' - class: Pod::Weaver::Plugin::H1Nester name: '@CorePrep/H1Nester' version: '4.020' - class: Pod::Weaver::Plugin::SingleEncoding name: '@Default/SingleEncoding' version: '4.020' - class: Pod::Weaver::Section::Name name: '@Default/Name' version: '4.020' - class: Pod::Weaver::Section::Version name: '@Default/Version' version: '4.020' - class: Pod::Weaver::Section::Region name: '@Default/prelude' version: '4.020' - class: Pod::Weaver::Section::Generic name: SYNOPSIS version: '4.020' - class: Pod::Weaver::Section::Generic name: DESCRIPTION version: '4.020' - class: Pod::Weaver::Section::Generic name: OVERVIEW version: '4.020' - class: Pod::Weaver::Section::Collect name: ATTRIBUTES version: '4.020' - class: Pod::Weaver::Section::Collect name: METHODS version: '4.020' - class: Pod::Weaver::Section::Collect name: FUNCTIONS version: '4.020' - class: Pod::Weaver::Section::Leftovers name: '@Default/Leftovers' version: '4.020' - class: Pod::Weaver::Section::Region name: '@Default/postlude' version: '4.020' - class: Pod::Weaver::Section::Authors name: '@Default/Authors' version: '4.020' - class: Pod::Weaver::Section::Legal name: '@Default/Legal' version: '4.020' name: '@Author::OALDERS/PodWeaver' version: '4.010' - class: Dist::Zilla::Plugin::PruneCruft name: '@Author::OALDERS/PruneCruft' version: '6.037' - class: Dist::Zilla::Plugin::CopyFilesFromBuild name: '@Author::OALDERS/CopyFilesFromBuild' version: '0.170880' - class: Dist::Zilla::Plugin::GithubMeta name: '@Author::OALDERS/GithubMeta' version: '0.58' - class: Dist::Zilla::Plugin::Git::GatherDir config: Dist::Zilla::Plugin::GatherDir: exclude_filename: - Install - LICENSE - META.json - Makefile.PL - README.md - cpanfile exclude_match: [] include_dotfiles: 0 prefix: '' prune_directory: [] root: . Dist::Zilla::Plugin::Git::GatherDir: include_untracked: 0 name: '@Author::OALDERS/Git::GatherDir' version: '2.052' - class: Dist::Zilla::Plugin::CopyFilesFromRelease config: Dist::Zilla::Plugin::CopyFilesFromRelease: filename: - Install match: [] name: '@Author::OALDERS/CopyFilesFromRelease' version: '0.007' - class: Dist::Zilla::Plugin::Git::Check config: Dist::Zilla::Plugin::Git::Check: untracked_files: die Dist::Zilla::Role::Git::DirtyFiles: allow_dirty: - Changes - Install - LICENSE - META.json - Makefile.PL - README.md - cpanfile - dist.ini allow_dirty_match: [] changelog: Changes Dist::Zilla::Role::Git::Repo: git_version: 2.43.0 repo_root: . name: '@Author::OALDERS/Git::Check' version: '2.052' - class: Dist::Zilla::Plugin::Git::Contributors config: Dist::Zilla::Plugin::Git::Contributors: git_version: 2.43.0 include_authors: 0 include_releaser: 1 order_by: name paths: [] name: '@Author::OALDERS/Git::Contributors' version: '0.039' - class: Dist::Zilla::Plugin::ReadmeAnyFromPod config: Dist::Zilla::Role::FileWatcher: version: '0.006' name: '@Author::OALDERS/ReadmeMdInBuild' version: '0.163250' - class: Dist::Zilla::Plugin::StaticInstall config: Dist::Zilla::Plugin::StaticInstall: dry_run: 0 mode: on name: '@Author::OALDERS/StaticInstall' version: '0.012' - class: Dist::Zilla::Plugin::ShareDir name: '@Author::OALDERS/ShareDir' version: '6.037' - class: Dist::Zilla::Plugin::CheckIssues name: '@Author::OALDERS/CheckIssues' version: '0.011' - class: Dist::Zilla::Plugin::ConfirmRelease name: '@Author::OALDERS/ConfirmRelease' version: '6.037' - class: Dist::Zilla::Plugin::UploadToCPAN name: '@Author::OALDERS/UploadToCPAN' version: '6.037' - class: Dist::Zilla::Plugin::Prereqs config: Dist::Zilla::Plugin::Prereqs: phase: develop type: recommends name: '@Author::OALDERS/@Git::VersionManager/pluginbundle version' version: '6.037' - class: Dist::Zilla::Plugin::RewriteVersion::Transitional config: Dist::Zilla::Plugin::RewriteVersion: add_tarball_name: 0 finders: - ':ExecFiles' - ':InstallModules' global: 0 skip_version_provider: 0 Dist::Zilla::Plugin::RewriteVersion::Transitional: {} name: '@Author::OALDERS/@Git::VersionManager/RewriteVersion::Transitional' version: '0.009' - class: Dist::Zilla::Plugin::MetaProvides::Update name: '@Author::OALDERS/@Git::VersionManager/MetaProvides::Update' version: '0.007' - class: Dist::Zilla::Plugin::CopyFilesFromRelease config: Dist::Zilla::Plugin::CopyFilesFromRelease: filename: - Changes match: [] name: '@Author::OALDERS/@Git::VersionManager/CopyFilesFromRelease' version: '0.007' - class: Dist::Zilla::Plugin::Git::Commit config: Dist::Zilla::Plugin::Git::Commit: add_files_in: [] commit_msg: v%V%n%n%c signoff: 0 Dist::Zilla::Role::Git::DirtyFiles: allow_dirty: - Changes - Install - LICENSE - META.json - Makefile.PL - README.md - cpanfile - dist.ini allow_dirty_match: [] changelog: Changes Dist::Zilla::Role::Git::Repo: git_version: 2.43.0 repo_root: . Dist::Zilla::Role::Git::StringFormatter: time_zone: local name: '@Author::OALDERS/@Git::VersionManager/release snapshot' version: '2.052' - class: Dist::Zilla::Plugin::Git::Tag config: Dist::Zilla::Plugin::Git::Tag: branch: ~ changelog: Changes signed: 0 tag: v0.000067 tag_format: v%V tag_message: v%V Dist::Zilla::Role::Git::Repo: git_version: 2.43.0 repo_root: . Dist::Zilla::Role::Git::StringFormatter: time_zone: local name: '@Author::OALDERS/@Git::VersionManager/Git::Tag' version: '2.052' - class: Dist::Zilla::Plugin::BumpVersionAfterRelease::Transitional config: Dist::Zilla::Plugin::BumpVersionAfterRelease: finders: - ':ExecFiles' - ':InstallModules' global: 0 munge_makefile_pl: 1 Dist::Zilla::Plugin::BumpVersionAfterRelease::Transitional: {} name: '@Author::OALDERS/@Git::VersionManager/BumpVersionAfterRelease::Transitional' version: '0.009' - class: Dist::Zilla::Plugin::NextRelease name: '@Author::OALDERS/@Git::VersionManager/NextRelease' version: '6.037' - class: Dist::Zilla::Plugin::Git::Commit config: Dist::Zilla::Plugin::Git::Commit: add_files_in: [] commit_msg: 'increment $VERSION after %v release' signoff: 0 Dist::Zilla::Role::Git::DirtyFiles: allow_dirty: - Build.PL - Changes - Makefile.PL allow_dirty_match: - (?^:^lib/.*\.pm$) changelog: Changes Dist::Zilla::Role::Git::Repo: git_version: 2.43.0 repo_root: . Dist::Zilla::Role::Git::StringFormatter: time_zone: local name: '@Author::OALDERS/@Git::VersionManager/post-release commit' version: '2.052' - class: Dist::Zilla::Plugin::Git::Push config: Dist::Zilla::Plugin::Git::Push: push_to: - origin remotes_must_exist: 1 Dist::Zilla::Role::Git::Repo: git_version: 2.43.0 repo_root: . name: '@Author::OALDERS/Git::Push' version: '2.052' - class: Dist::Zilla::Plugin::PruneFiles name: PruneFiles version: '6.037' - class: Dist::Zilla::Plugin::GitHubREADME::Badge name: GitHubREADME::Badge version: '0.35' - class: Dist::Zilla::Plugin::Prereqs config: Dist::Zilla::Plugin::Prereqs: phase: runtime type: requires name: RuntimeRequires version: '6.037' - class: Dist::Zilla::Plugin::Prereqs config: Dist::Zilla::Plugin::Prereqs: phase: test type: requires name: TestRequires version: '6.037' - class: Dist::Zilla::Plugin::Prereqs config: Dist::Zilla::Plugin::Prereqs: phase: develop type: requires name: DevelopRequires version: '6.037' - class: Dist::Zilla::Plugin::FinderCode name: ':InstallModules' version: '6.037' - class: Dist::Zilla::Plugin::FinderCode name: ':IncModules' version: '6.037' - class: Dist::Zilla::Plugin::FinderCode name: ':TestFiles' version: '6.037' - class: Dist::Zilla::Plugin::FinderCode name: ':ExtraTestFiles' version: '6.037' - class: Dist::Zilla::Plugin::FinderCode name: ':ExecFiles' version: '6.037' - class: Dist::Zilla::Plugin::FinderCode name: ':PerlExecFiles' version: '6.037' - class: Dist::Zilla::Plugin::FinderCode name: ':ShareFiles' version: '6.037' - class: Dist::Zilla::Plugin::FinderCode name: ':MainModule' version: '6.037' - class: Dist::Zilla::Plugin::FinderCode name: ':AllFiles' version: '6.037' - class: Dist::Zilla::Plugin::FinderCode name: ':NoFiles' version: '6.037' zilla: class: Dist::Zilla::Dist::Builder config: is_trial: 0 version: '6.037' x_contributors: - 'Copilot <198982749+Copilot@users.noreply.github.com>' - 'Dave Rolsky ' - 'dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>' - 'E. Choroba ' - 'James Raspass ' - 'José Manuel Rodríguez D ' - 'Kenichi Ishigaki ' - 'Nelo Onyiah ' - 'Nicolas Mendoza ' - 'Olaf Alders ' - 'Paul Johnson ' - 'Peter Oliver ' - 'pyrrhlin <1197072+myrrhlin@users.noreply.github.com>' x_generated_by_perl: v5.42.2 x_serialization_backend: 'YAML::Tiny version 1.76' x_spdx_expression: 'Artistic-1.0-Perl OR GPL-1.0-or-later' x_static_install: 1 MANIFEST100644001750001751 1541615261510577 15344 0ustar00olafolaf000000000000App-perlimports-0.000067# This file was automatically generated by Dist::Zilla::Plugin::Manifest v6.037 CLAUDE.md CONTRIBUTING.md CONTRIBUTORS Changes INSTALL LICENSE MANIFEST META.json META.yml Makefile.PL README.md cpanfile dist.ini git/hooks/pre-commit git/setup.sh lib/App/perlimports.pm lib/App/perlimports/Annotations.pm lib/App/perlimports/CLI.pm lib/App/perlimports/Config.pm lib/App/perlimports/Document.pm lib/App/perlimports/ExportInspector.pm lib/App/perlimports/Include.pm lib/App/perlimports/Role/Logger.pm lib/App/perlimports/Sandbox.pm lib/App/perlimports/Sorter.pm perlcriticrc perlimports.toml perltidyrc precious.toml script/dump-perl-exports script/perlimports t/00-report-prereqs.dd t/00-report-prereqs.t t/Config.t t/Document.t t/ExportInspector/SubExporter.t t/ExportInspector/load.t t/Sandbox.t t/after.t t/annotations.t t/args-in-import.t t/builtin.t t/carp.t t/cast-in-regex.t t/cast.t t/cli-args.t t/cli.t t/config-in-import.t t/constants.t t/cpan-modules/pithub.t t/cpan-modules/test2-v0.t t/datetime.t t/do-block.t t/doc-imports.t t/double-quoted-q.t t/dump-perl-exports.t t/dupes.t t/english-program-name.t t/english.t t/env.t t/explodes.t t/export-tags.t t/exported-variables.t t/find-bin.t t/fully-qualified.t t/func-in-use.t t/func-in-var.t t/function-reference.t t/geo-ip.t t/hash-in-regex.t t/hash-key-expression.t t/hash-key.t t/hash-unquoted-key.t t/heredoc.t t/ignored-modules.t t/import-error.t t/indent.t t/indirect-object-syntax.t t/interpolation.t t/is-ignored.t t/lib/TestHelper.pm t/local-lib.t t/locally-defined-sub.t t/lookalike-words.t t/maybe-new-include.t t/memoize.t t/meta.t t/method.t t/missing-semicolon-in-import.t t/module-with-inner-packages.t t/moo.t t/moose-type-library-with-meta.t t/moose-types.t t/moose.t t/moosex-types-moose.t t/nested-quotes.t t/never-exports.t t/original-imports.t t/pad-brackets.t t/padding.t t/perl-imports.t t/perl.t t/perlimports.t t/pragma.t t/preserve-include-comments.t t/preserve-some-padding.t t/preserve-spaces.t t/qualified-bareword.t t/quoted-var.t t/re-export-via-sub-exporter.t t/regex-replacement.t t/require.t t/same-symbol-different-modules.t t/script-with-inner-packages.t t/signatures.t t/skip-all.t t/socket.t t/sort-imports.t t/sort-includes.t t/sorter.t t/switches-in-import.t t/symbol-as-method-call.t t/symbol-in-export.t t/test-builder.t t/tie.t t/typeglob.t t/unnest-quotes.t t/use-and-require.t t/var-in-hash-key.t t/var-in-regex.t t/variable.t t/via-sub-exporter-exception.pl t/warning.t t/with-version.t test-data/a.pl test-data/annotate-everything.pl test-data/annotation.pl test-data/args-in-import.t test-data/b.pl test-data/builtin.pl test-data/carp-with-no-imports.pl test-data/carp-without-verbose.pl test-data/carp.pl test-data/cast-in-regex.pl test-data/cast.pl test-data/config-in-import.pl test-data/datetime.pl test-data/doc-imports.pl test-data/double-quoted-q.pl test-data/dupes.pl test-data/english-program-name.pl test-data/english.pl test-data/env-bare.pl test-data/env-comma.pl test-data/env-interpolated.pl test-data/env-mixed.pl test-data/env-scalar.pl test-data/env-unused.pl test-data/env-version.pl test-data/env.pl test-data/exceptional.pl test-data/explodes.pl test-data/export-tags.pl test-data/exported-variables.pl test-data/filter-paths/Foo.pl test-data/filter-paths/Foo.pm test-data/filter-paths/foo test-data/filter-paths/foo.py test-data/filter-paths/foo.t test-data/filter-paths/foo.txt test-data/find-bin.pl test-data/foo.pl test-data/foo.t test-data/fully-qualified.pl test-data/func-in-use-2.pl test-data/func-in-use.pl test-data/func-in-var.pl test-data/function-reference.pl test-data/geo-ip.pl test-data/getopt-long.pl test-data/getopt.pl test-data/hash-in-regex.pl test-data/hash-key-expression.pl test-data/hash-unquoted-key.pl test-data/heredoc.pl test-data/http-status.pl test-data/ignore-modules-pattern.txt test-data/ignore-modules.txt test-data/indirect-object-syntax-preserved.pl test-data/indirect-object-syntax.pl test-data/inner-package.pl test-data/interpolation.pl test-data/lib/Local/After.pm test-data/lib/Local/CustomImport.pm test-data/lib/Local/Explodes.pm test-data/lib/Local/ImportException.pm test-data/lib/Local/LongList.pm test-data/lib/Local/MaxA.pm test-data/lib/Local/MaxB.pm test-data/lib/Local/MaxFacade.pm test-data/lib/Local/MooseTypeLibrary.pm test-data/lib/Local/MooseTypeLibraryWithMeta.pm test-data/lib/Local/MyOwnMoo.pm test-data/lib/Local/MyOwnMoose.pm test-data/lib/Local/NoImport.pm test-data/lib/Local/ReExportViaSubExporter.pm test-data/lib/Local/RequireExporter.pm test-data/lib/Local/Round.pm test-data/lib/Local/STDOUT.pm test-data/lib/Local/Sort.pm test-data/lib/Local/SymbolInExport.pm test-data/lib/Local/UsesMoo.pm test-data/lib/Local/UsesMoose.pm test-data/lib/Local/UsesMyOwnMoo.pm test-data/lib/Local/UsesMyOwnMoose.pm test-data/lib/Local/UsesTypesStandard.pm test-data/lib/Local/UsesUsesImportInto.pm test-data/lib/Local/ViaExporter.pm test-data/lib/Local/ViaSubExporter.pm test-data/lib/Local/ViaSubExporter/Exception.pm test-data/lib/Local/WithInnerPkg.pm test-data/lint-failure-duplicate-import.pl test-data/lint-failure-import-args.pl test-data/lint-failure-indented-duplicate.pl test-data/lint-failure-unused-import.pl test-data/lint-success.pl test-data/local-lib.pl test-data/long-list.pl test-data/long-test-more.pl test-data/lookalike-words.pl test-data/messy-imports.pl test-data/meta.t test-data/method.pl test-data/missing-semicolon-in-import.pl test-data/mojo-url.pl test-data/moose-type-library-with-meta.pl test-data/moosex-types-moose.pl test-data/more-find-bin.pl test-data/nested-quotes.pl test-data/never-export-modules.txt test-data/noop.t test-data/original-imports.pl test-data/pack-qq.pl test-data/perl-version.pl test-data/perlimports.toml test-data/pithub.pl test-data/pragma.t test-data/preserve-some-padding.pl test-data/preserve-spaces.pl test-data/qualified-bareword.pl test-data/quoted-var.pl test-data/regex-replacement.pl test-data/require.pl test-data/same-import.pl test-data/signatures.pl test-data/skip-all.t test-data/socket.pl test-data/sort-includes-comments.pl test-data/sort-includes-multi.pl test-data/sort-includes-noncontiguous.pl test-data/sort-includes-sorted.pl test-data/sort-includes.pl test-data/sort.pl test-data/stdout.pl test-data/switches-in-import.pl test-data/symbol-as-method-call.pl test-data/symbol-in-signature.pl test-data/test-html-lint.t test-data/test-more.t test-data/tie.pl test-data/typeglob.pl test-data/unnest-quotes.pl test-data/use-and-require.pl test-data/use-constant.pm test-data/var-in-hash-key.pl test-data/var-in-regex.pl test-data/variable.pl test-data/various-quote-strings.pl test-data/via-exporter.pl test-data/via-sub-exporter-exception.pl test-data/with-version.pl test-needs-cpanfile xt/author/eol.t xt/author/mojibake.t xt/author/pod-coverage.t xt/author/pod-spell.t xt/author/pod-syntax.t xt/author/portability.t xt/author/test-version.t xt/release/cpan-changes.t dist.ini100644001750001751 332215261510577 15630 0ustar00olafolaf000000000000App-perlimports-0.000067name = App-perlimports author = Olaf Alders license = Perl_5 copyright_holder = Olaf Alders copyright_year = 2020 main_module = lib/App/perlimports.pm [@Author::OALDERS] MetaNoIndex.directory[] = test-data StaticInstall.mode = on StaticInstall.dry_run = 0 ; The trailing names are explicit list-accessor subs that replaced Sub::HandlesVia ; 'Array' delegations (issue #171). The generated delegations looked imported to ; Pod::Coverage; the hand-written replacements are native to their files and ; would otherwise be flagged as undocumented. Test::Pod::Coverage::Configurable.also_private = qr/^(?:BUILD|BUILDARGS|all_includes|possibly_imported_tokens|sub_exporter_export_list|has_at_export|has_at_export_ok|has_import_flags)$/ Test::Pod::Coverage::Configurable.trustme = App::perlimports::Role::Logger => qr/.*/ -remove = Test::Synopsis -remove = Test::TidyAll [PruneFiles] match = ^author/ match = ^inc/ [GitHubREADME::Badge] badges = github_actions/dzil-build-and-test.yml badges = codecov badges = cpants badges = github_tag badges = license place = top phase = build [Prereqs / RuntimeRequires] Class::Inspector = 1.36 File::XDG = 1.01 Log::Dispatch = 2.70 perl = 5.18.0 Perl::Tidy = 20220613 PPI = 1.276 Symbol::Get = 0.10 TOML::Tiny = 0.16 ; Mostly needed for files in ./test-data [Prereqs / TestRequires] Test::RequiresInternet = 0 Test::Script = 1.29 [Prereqs / DevelopRequires] ; Policy distributions enabled in perlcriticrc. Bangs 1.10 added ; ProhibitDebuggingModules. Perl::Critic::Bangs = 1.10 Perl::Critic::Freenode = 0 Perl::Critic::Moose = 0 Perl::Critic::Policy::ValuesAndExpressions::ProhibitAccessOfPrivateData = v1.0.0 Perl::Critic::Policy::Variables::ProhibitUnusedVarsStricter = 0.116 carp.t100755001750001751 251115261510577 15543 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!/usr/bin/env perl use strict; use warnings; use lib 't/lib'; use Test::Differences qw( eq_or_diff ); use TestHelper qw( doc ); use Test::More import => [qw( done_testing is_deeply subtest )]; subtest 'verbose' => sub { my ($doc) = doc( filename => 'test-data/carp.pl' ); my $expected = <<'EOF'; use strict; use warnings; use Carp qw( croak verbose ); croak('oof'); EOF eq_or_diff( $doc->tidied_document, $expected, 'verbose is preserved' ); }; subtest 'no verbose' => sub { my ($doc) = doc( filename => 'test-data/carp-without-verbose.pl' ); my $expected = <<'EOF'; use strict; use warnings; use Carp qw( croak ); croak('oof'); EOF eq_or_diff( $doc->tidied_document, $expected, 'verbose is not inserted' ); }; subtest 'no imports' => sub { my ($doc) = doc( filename => 'test-data/carp-with-no-imports.pl' ); my $expected = <<'EOF'; use strict; use warnings; use Carp qw( croak ); croak('oof'); EOF is_deeply( $doc->found_imports->{Carp}, undef, 'found imports' ); eq_or_diff( $doc->tidied_document, $expected, 'verbose is not inserted' ); is_deeply( $doc->found_imports, { Carp => ['croak'] }, 'found imports updated' ); }; done_testing(); cast.t100755001750001751 56415261510577 15536 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use lib 't/lib'; use TestHelper qw( doc ); use Test::More import => [qw( done_testing is )]; use Test::Needs qw( Mojo::Util ); my ($doc) = doc( filename => 'test-data/cast.pl', selection => 'use Mojo::Util;', ); is( $doc->tidied_document, 'use Mojo::Util qw( split_header );', 'interpolated func found' ); done_testing; meta.t100755001750001751 65615261510577 15534 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use lib 't/lib'; use TestHelper qw( doc ); use Test::More import => [qw( done_testing is )]; use Test::Needs qw( Test2::V0 ); my ($doc) = doc( filename => 'test-data/meta.t', ); my $expected = <<'EOF'; use strict; use warnings; use Test2::V0 qw( !meta done_testing ok ); ok(1); done_testing; EOF is( $doc->tidied_document, $expected, '!meta preserved in import' ); done_testing; perl.t100644001750001751 52215261510577 15535 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use lib 't/lib'; use TestHelper qw( doc ); use Test::More import => [qw( done_testing is )]; my ($doc) = doc( filename => 'test-data/perl-version.pl' ); my $expected = <<'EOF'; use strict; use warnings; use 5.008001; EOF is( $doc->tidied_document, $expected, 'perl use statement ignored' ); done_testing(); META.json100644001750001751 7364115261510577 15640 0ustar00olafolaf000000000000App-perlimports-0.000067{ "abstract" : "Make implicit imports explicit", "author" : [ "Olaf Alders " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 6.037, CPAN::Meta::Converter version 2.150013", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : 2 }, "name" : "App-perlimports", "no_index" : { "directory" : [ "examples", "t", "test-data", "xt" ] }, "prereqs" : { "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0", "perl" : "5.013002" } }, "develop" : { "recommends" : { "Dist::Zilla::PluginBundle::Git::VersionManager" : "0.007" }, "requires" : { "Code::TidyAll" : "0.71", "Code::TidyAll::Plugin::SortLines::Naturally" : "0.000003", "Code::TidyAll::Plugin::Test::Vars" : "0.04", "Code::TidyAll::Plugin::UniqueLines" : "0.000003", "Parallel::ForkManager" : "1.19", "Perl::Critic" : "1.132", "Perl::Critic::Bangs" : "1.10", "Perl::Critic::Freenode" : "0", "Perl::Critic::Moose" : "0", "Perl::Critic::Policy::ValuesAndExpressions::ProhibitAccessOfPrivateData" : "v1.0.0", "Perl::Critic::Policy::Variables::ProhibitUnusedVarsStricter" : "0.116", "Perl::Tidy" : "20180220", "Pod::Coverage::TrustPod" : "0", "Pod::Wordlist" : "0", "Test::CPAN::Changes" : "0.19", "Test::EOL" : "0", "Test::Mojibake" : "0", "Test::More" : "0.96", "Test::Pod" : "1.41", "Test::Pod::Coverage" : "1.08", "Test::Portability::Files" : "0", "Test::Spelling" : "0.17", "Test::Vars" : "0.014", "Test::Version" : "1" } }, "runtime" : { "requires" : { "Capture::Tiny" : "0", "Class::Inspector" : "1.36", "Cpanel::JSON::XS" : "0", "Data::Dumper" : "0", "Data::UUID" : "0", "File::Basename" : "0", "File::XDG" : "1.01", "Getopt::Long::Descriptive" : "0", "List::Util" : "0", "Log::Dispatch" : "2.70", "Memoize" : "0", "Module::Runtime" : "0", "Moo" : "0", "Moo::Role" : "0", "MooX::StrictConstructor" : "0", "PPI" : "1.276", "PPI::Document" : "0", "PPIx::Utils::Classification" : "0", "PPIx::Utils::Traversal" : "0", "Path::Iterator::Rule" : "0", "Path::Tiny" : "0", "Perl::Tidy" : "20220613", "Pod::Usage" : "0", "Ref::Util" : "0", "Scalar::Util" : "0", "Sereal::Decoder" : "0", "Sereal::Encoder" : "0", "Sub::HandlesVia" : "0", "Symbol::Get" : "0.10", "TOML::Tiny" : "0.16", "Text::Diff" : "0", "Text::SimpleTable::AutoWidth" : "0", "Try::Tiny" : "0", "Types::Common::Numeric" : "0", "Types::Standard" : "0", "feature" : "0", "perl" : "v5.18.0", "strict" : "0", "utf8" : "0", "warnings" : "0" } }, "test" : { "recommends" : { "CPAN::Meta" : "2.120900" }, "requires" : { "ExtUtils::MakeMaker" : "0", "File::Spec" : "0", "File::pushd" : "0", "Log::Dispatch::Array" : "0", "PPI::Dumper" : "0", "Sub::Exporter" : "0", "Test::Differences" : "0", "Test::Fatal" : "0", "Test::More" : "0", "Test::Needs" : "0", "Test::RequiresInternet" : "0", "Test::Script" : "1.29", "Test::Warnings" : "0", "lib" : "0", "perl" : "v5.18.0" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/perl-ide/App-perlimports/issues" }, "homepage" : "https://github.com/perl-ide/App-perlimports", "repository" : { "type" : "git", "url" : "https://github.com/perl-ide/App-perlimports.git", "web" : "https://github.com/perl-ide/App-perlimports" } }, "version" : "0.000067", "x_Dist_Zilla" : { "perl" : { "version" : "5.042002" }, "plugins" : [ { "class" : "Dist::Zilla::Plugin::PromptIfStale", "config" : { "Dist::Zilla::Plugin::PromptIfStale" : { "check_all_plugins" : 0, "check_all_prereqs" : 0, "modules" : [ "Dist::Zilla::PluginBundle::Author::OALDERS" ], "phase" : "build", "run_under_travis" : 0, "skip" : [] } }, "name" : "@Author::OALDERS/stale modules, build", "version" : "0.060" }, { "class" : "Dist::Zilla::Plugin::PromptIfStale", "config" : { "Dist::Zilla::Plugin::PromptIfStale" : { "check_all_plugins" : 1, "check_all_prereqs" : 1, "modules" : [], "phase" : "release", "run_under_travis" : 0, "skip" : [] } }, "name" : "@Author::OALDERS/stale modules, release", "version" : "0.060" }, { "class" : "Dist::Zilla::Plugin::AutoPrereqs", "name" : "@Author::OALDERS/AutoPrereqs", "version" : "6.037" }, { "class" : "Dist::Zilla::Plugin::CheckChangesHasContent", "name" : "@Author::OALDERS/CheckChangesHasContent", "version" : "0.011" }, { "class" : "Dist::Zilla::Plugin::MakeMaker", "config" : { "Dist::Zilla::Role::TestRunner" : { "default_jobs" : "8" } }, "name" : "@Author::OALDERS/MakeMaker", "version" : "6.037" }, { "class" : "Dist::Zilla::Plugin::CPANFile", "name" : "@Author::OALDERS/CPANFile", "version" : "6.037" }, { "class" : "Dist::Zilla::Plugin::ContributorsFile", "name" : "@Author::OALDERS/ContributorsFile", "version" : "0.4.0" }, { "class" : "Dist::Zilla::Plugin::MetaJSON", "name" : "@Author::OALDERS/MetaJSON", "version" : "6.037" }, { "class" : "Dist::Zilla::Plugin::MetaYAML", "name" : "@Author::OALDERS/MetaYAML", "version" : "6.037" }, { "class" : "Dist::Zilla::Plugin::Manifest", "name" : "@Author::OALDERS/Manifest", "version" : "6.037" }, { "class" : "Dist::Zilla::Plugin::MetaNoIndex", "name" : "@Author::OALDERS/MetaNoIndex", "version" : "6.037" }, { "class" : "Dist::Zilla::Plugin::MetaConfig", "name" : "@Author::OALDERS/MetaConfig", "version" : "6.037" }, { "class" : "Dist::Zilla::Plugin::MetaResources", "name" : "@Author::OALDERS/MetaResources", "version" : "6.037" }, { "class" : "Dist::Zilla::Plugin::License", "name" : "@Author::OALDERS/License", "version" : "6.037" }, { "class" : "Dist::Zilla::Plugin::InstallGuide", "config" : { "Dist::Zilla::Role::ModuleMetadata" : { "Module::Metadata" : "1.000038", "version" : "0.006" } }, "name" : "@Author::OALDERS/InstallGuide", "version" : "1.200014" }, { "class" : "Dist::Zilla::Plugin::Prereqs", "config" : { "Dist::Zilla::Plugin::Prereqs" : { "phase" : "develop", "type" : "requires" } }, "name" : "@Author::OALDERS/Modules for use with tidyall", "version" : "6.037" }, { "class" : "Dist::Zilla::Plugin::ExecDir", "name" : "@Author::OALDERS/ExecDir", "version" : "6.037" }, { "class" : "Dist::Zilla::Plugin::Test::PodSpelling", "config" : { "Dist::Zilla::Plugin::Test::PodSpelling" : { "directories" : [ "bin", "lib" ], "spell_cmd" : "", "stopwords" : [ "Alders", "Alders'", "PPI", "sandboxed" ], "wordlist" : "Pod::Wordlist" } }, "name" : "@Author::OALDERS/Test::PodSpelling", "version" : "2.007006" }, { "class" : "Dist::Zilla::Plugin::MojibakeTests", "name" : "@Author::OALDERS/MojibakeTests", "version" : "0.8" }, { "class" : "Dist::Zilla::Plugin::PodSyntaxTests", "name" : "@Author::OALDERS/PodSyntaxTests", "version" : "6.037" }, { "class" : "Dist::Zilla::Plugin::Test::CPAN::Changes", "config" : { "Dist::Zilla::Plugin::Test::CPAN::Changes" : { "changelog" : "Changes", "filename" : "xt/release/cpan-changes.t" } }, "name" : "@Author::OALDERS/Test::CPAN::Changes", "version" : "0.013" }, { "class" : "Dist::Zilla::Plugin::Test::EOL", "config" : { "Dist::Zilla::Plugin::Test::EOL" : { "filename" : "xt/author/eol.t", "finder" : [ ":ExecFiles", ":InstallModules", ":TestFiles" ], "trailing_whitespace" : 1 } }, "name" : "@Author::OALDERS/Test::EOL", "version" : "0.19" }, { "class" : "Dist::Zilla::Plugin::Test::Pod::Coverage::Configurable", "name" : "@Author::OALDERS/Test::Pod::Coverage::Configurable", "version" : "0.07" }, { "class" : "Dist::Zilla::Plugin::Test::Portability", "config" : { "Dist::Zilla::Plugin::Test::Portability" : { "options" : "" } }, "name" : "@Author::OALDERS/Test::Portability", "version" : "2.001003" }, { "class" : "Dist::Zilla::Plugin::TestRelease", "name" : "@Author::OALDERS/TestRelease", "version" : "6.037" }, { "class" : "Dist::Zilla::Plugin::Test::ReportPrereqs", "name" : "@Author::OALDERS/Test::ReportPrereqs", "version" : "0.029" }, { "class" : "Dist::Zilla::Plugin::Test::Version", "name" : "@Author::OALDERS/Test::Version", "version" : "1.09" }, { "class" : "Dist::Zilla::Plugin::RunExtraTests", "config" : { "Dist::Zilla::Role::TestRunner" : { "default_jobs" : "8" } }, "name" : "@Author::OALDERS/RunExtraTests", "version" : "0.029" }, { "class" : "Dist::Zilla::Plugin::MinimumPerl", "name" : "@Author::OALDERS/MinimumPerl", "version" : "1.006" }, { "class" : "Dist::Zilla::Plugin::PodWeaver", "config" : { "Dist::Zilla::Plugin::PodWeaver" : { "finder" : [ ":InstallModules", ":PerlExecFiles" ], "plugins" : [ { "class" : "Pod::Weaver::Plugin::EnsurePod5", "name" : "@CorePrep/EnsurePod5", "version" : "4.020" }, { "class" : "Pod::Weaver::Plugin::H1Nester", "name" : "@CorePrep/H1Nester", "version" : "4.020" }, { "class" : "Pod::Weaver::Plugin::SingleEncoding", "name" : "@Default/SingleEncoding", "version" : "4.020" }, { "class" : "Pod::Weaver::Section::Name", "name" : "@Default/Name", "version" : "4.020" }, { "class" : "Pod::Weaver::Section::Version", "name" : "@Default/Version", "version" : "4.020" }, { "class" : "Pod::Weaver::Section::Region", "name" : "@Default/prelude", "version" : "4.020" }, { "class" : "Pod::Weaver::Section::Generic", "name" : "SYNOPSIS", "version" : "4.020" }, { "class" : "Pod::Weaver::Section::Generic", "name" : "DESCRIPTION", "version" : "4.020" }, { "class" : "Pod::Weaver::Section::Generic", "name" : "OVERVIEW", "version" : "4.020" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "ATTRIBUTES", "version" : "4.020" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "METHODS", "version" : "4.020" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "FUNCTIONS", "version" : "4.020" }, { "class" : "Pod::Weaver::Section::Leftovers", "name" : "@Default/Leftovers", "version" : "4.020" }, { "class" : "Pod::Weaver::Section::Region", "name" : "@Default/postlude", "version" : "4.020" }, { "class" : "Pod::Weaver::Section::Authors", "name" : "@Default/Authors", "version" : "4.020" }, { "class" : "Pod::Weaver::Section::Legal", "name" : "@Default/Legal", "version" : "4.020" } ] } }, "name" : "@Author::OALDERS/PodWeaver", "version" : "4.010" }, { "class" : "Dist::Zilla::Plugin::PruneCruft", "name" : "@Author::OALDERS/PruneCruft", "version" : "6.037" }, { "class" : "Dist::Zilla::Plugin::CopyFilesFromBuild", "name" : "@Author::OALDERS/CopyFilesFromBuild", "version" : "0.170880" }, { "class" : "Dist::Zilla::Plugin::GithubMeta", "name" : "@Author::OALDERS/GithubMeta", "version" : "0.58" }, { "class" : "Dist::Zilla::Plugin::Git::GatherDir", "config" : { "Dist::Zilla::Plugin::GatherDir" : { "exclude_filename" : [ "Install", "LICENSE", "META.json", "Makefile.PL", "README.md", "cpanfile" ], "exclude_match" : [], "include_dotfiles" : 0, "prefix" : "", "prune_directory" : [], "root" : "." }, "Dist::Zilla::Plugin::Git::GatherDir" : { "include_untracked" : 0 } }, "name" : "@Author::OALDERS/Git::GatherDir", "version" : "2.052" }, { "class" : "Dist::Zilla::Plugin::CopyFilesFromRelease", "config" : { "Dist::Zilla::Plugin::CopyFilesFromRelease" : { "filename" : [ "Install" ], "match" : [] } }, "name" : "@Author::OALDERS/CopyFilesFromRelease", "version" : "0.007" }, { "class" : "Dist::Zilla::Plugin::Git::Check", "config" : { "Dist::Zilla::Plugin::Git::Check" : { "untracked_files" : "die" }, "Dist::Zilla::Role::Git::DirtyFiles" : { "allow_dirty" : [ "Changes", "Install", "LICENSE", "META.json", "Makefile.PL", "README.md", "cpanfile", "dist.ini" ], "allow_dirty_match" : [], "changelog" : "Changes" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.43.0", "repo_root" : "." } }, "name" : "@Author::OALDERS/Git::Check", "version" : "2.052" }, { "class" : "Dist::Zilla::Plugin::Git::Contributors", "config" : { "Dist::Zilla::Plugin::Git::Contributors" : { "git_version" : "2.43.0", "include_authors" : 0, "include_releaser" : 1, "order_by" : "name", "paths" : [] } }, "name" : "@Author::OALDERS/Git::Contributors", "version" : "0.039" }, { "class" : "Dist::Zilla::Plugin::ReadmeAnyFromPod", "config" : { "Dist::Zilla::Role::FileWatcher" : { "version" : "0.006" } }, "name" : "@Author::OALDERS/ReadmeMdInBuild", "version" : "0.163250" }, { "class" : "Dist::Zilla::Plugin::StaticInstall", "config" : { "Dist::Zilla::Plugin::StaticInstall" : { "dry_run" : 0, "mode" : "on" } }, "name" : "@Author::OALDERS/StaticInstall", "version" : "0.012" }, { "class" : "Dist::Zilla::Plugin::ShareDir", "name" : "@Author::OALDERS/ShareDir", "version" : "6.037" }, { "class" : "Dist::Zilla::Plugin::CheckIssues", "name" : "@Author::OALDERS/CheckIssues", "version" : "0.011" }, { "class" : "Dist::Zilla::Plugin::ConfirmRelease", "name" : "@Author::OALDERS/ConfirmRelease", "version" : "6.037" }, { "class" : "Dist::Zilla::Plugin::UploadToCPAN", "name" : "@Author::OALDERS/UploadToCPAN", "version" : "6.037" }, { "class" : "Dist::Zilla::Plugin::Prereqs", "config" : { "Dist::Zilla::Plugin::Prereqs" : { "phase" : "develop", "type" : "recommends" } }, "name" : "@Author::OALDERS/@Git::VersionManager/pluginbundle version", "version" : "6.037" }, { "class" : "Dist::Zilla::Plugin::RewriteVersion::Transitional", "config" : { "Dist::Zilla::Plugin::RewriteVersion" : { "add_tarball_name" : 0, "finders" : [ ":ExecFiles", ":InstallModules" ], "global" : 0, "skip_version_provider" : 0 }, "Dist::Zilla::Plugin::RewriteVersion::Transitional" : {} }, "name" : "@Author::OALDERS/@Git::VersionManager/RewriteVersion::Transitional", "version" : "0.009" }, { "class" : "Dist::Zilla::Plugin::MetaProvides::Update", "name" : "@Author::OALDERS/@Git::VersionManager/MetaProvides::Update", "version" : "0.007" }, { "class" : "Dist::Zilla::Plugin::CopyFilesFromRelease", "config" : { "Dist::Zilla::Plugin::CopyFilesFromRelease" : { "filename" : [ "Changes" ], "match" : [] } }, "name" : "@Author::OALDERS/@Git::VersionManager/CopyFilesFromRelease", "version" : "0.007" }, { "class" : "Dist::Zilla::Plugin::Git::Commit", "config" : { "Dist::Zilla::Plugin::Git::Commit" : { "add_files_in" : [], "commit_msg" : "v%V%n%n%c", "signoff" : 0 }, "Dist::Zilla::Role::Git::DirtyFiles" : { "allow_dirty" : [ "Changes", "Install", "LICENSE", "META.json", "Makefile.PL", "README.md", "cpanfile", "dist.ini" ], "allow_dirty_match" : [], "changelog" : "Changes" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.43.0", "repo_root" : "." }, "Dist::Zilla::Role::Git::StringFormatter" : { "time_zone" : "local" } }, "name" : "@Author::OALDERS/@Git::VersionManager/release snapshot", "version" : "2.052" }, { "class" : "Dist::Zilla::Plugin::Git::Tag", "config" : { "Dist::Zilla::Plugin::Git::Tag" : { "branch" : null, "changelog" : "Changes", "signed" : 0, "tag" : "v0.000067", "tag_format" : "v%V", "tag_message" : "v%V" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.43.0", "repo_root" : "." }, "Dist::Zilla::Role::Git::StringFormatter" : { "time_zone" : "local" } }, "name" : "@Author::OALDERS/@Git::VersionManager/Git::Tag", "version" : "2.052" }, { "class" : "Dist::Zilla::Plugin::BumpVersionAfterRelease::Transitional", "config" : { "Dist::Zilla::Plugin::BumpVersionAfterRelease" : { "finders" : [ ":ExecFiles", ":InstallModules" ], "global" : 0, "munge_makefile_pl" : 1 }, "Dist::Zilla::Plugin::BumpVersionAfterRelease::Transitional" : {} }, "name" : "@Author::OALDERS/@Git::VersionManager/BumpVersionAfterRelease::Transitional", "version" : "0.009" }, { "class" : "Dist::Zilla::Plugin::NextRelease", "name" : "@Author::OALDERS/@Git::VersionManager/NextRelease", "version" : "6.037" }, { "class" : "Dist::Zilla::Plugin::Git::Commit", "config" : { "Dist::Zilla::Plugin::Git::Commit" : { "add_files_in" : [], "commit_msg" : "increment $VERSION after %v release", "signoff" : 0 }, "Dist::Zilla::Role::Git::DirtyFiles" : { "allow_dirty" : [ "Build.PL", "Changes", "Makefile.PL" ], "allow_dirty_match" : [ "(?^:^lib/.*\\.pm$)" ], "changelog" : "Changes" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.43.0", "repo_root" : "." }, "Dist::Zilla::Role::Git::StringFormatter" : { "time_zone" : "local" } }, "name" : "@Author::OALDERS/@Git::VersionManager/post-release commit", "version" : "2.052" }, { "class" : "Dist::Zilla::Plugin::Git::Push", "config" : { "Dist::Zilla::Plugin::Git::Push" : { "push_to" : [ "origin" ], "remotes_must_exist" : 1 }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.43.0", "repo_root" : "." } }, "name" : "@Author::OALDERS/Git::Push", "version" : "2.052" }, { "class" : "Dist::Zilla::Plugin::PruneFiles", "name" : "PruneFiles", "version" : "6.037" }, { "class" : "Dist::Zilla::Plugin::GitHubREADME::Badge", "name" : "GitHubREADME::Badge", "version" : "0.35" }, { "class" : "Dist::Zilla::Plugin::Prereqs", "config" : { "Dist::Zilla::Plugin::Prereqs" : { "phase" : "runtime", "type" : "requires" } }, "name" : "RuntimeRequires", "version" : "6.037" }, { "class" : "Dist::Zilla::Plugin::Prereqs", "config" : { "Dist::Zilla::Plugin::Prereqs" : { "phase" : "test", "type" : "requires" } }, "name" : "TestRequires", "version" : "6.037" }, { "class" : "Dist::Zilla::Plugin::Prereqs", "config" : { "Dist::Zilla::Plugin::Prereqs" : { "phase" : "develop", "type" : "requires" } }, "name" : "DevelopRequires", "version" : "6.037" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":InstallModules", "version" : "6.037" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":IncModules", "version" : "6.037" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":TestFiles", "version" : "6.037" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ExtraTestFiles", "version" : "6.037" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ExecFiles", "version" : "6.037" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":PerlExecFiles", "version" : "6.037" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ShareFiles", "version" : "6.037" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":MainModule", "version" : "6.037" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":AllFiles", "version" : "6.037" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":NoFiles", "version" : "6.037" } ], "zilla" : { "class" : "Dist::Zilla::Dist::Builder", "config" : { "is_trial" : 0 }, "version" : "6.037" } }, "x_contributors" : [ "Copilot <198982749+Copilot@users.noreply.github.com>", "Dave Rolsky ", "dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>", "E. Choroba ", "James Raspass ", "Jos\u00e9 Manuel Rodri\u0301guez D ", "Kenichi Ishigaki ", "Nelo Onyiah ", "Nicolas Mendoza ", "Olaf Alders ", "Paul Johnson ", "Peter Oliver ", "pyrrhlin <1197072+myrrhlin@users.noreply.github.com>" ], "x_generated_by_perl" : "v5.42.2", "x_serialization_backend" : "Cpanel::JSON::XS version 4.40", "x_spdx_expression" : "Artistic-1.0-Perl OR GPL-1.0-or-later", "x_static_install" : 1 } CLAUDE.md100644001750001751 723115261510577 15446 0ustar00olafolaf000000000000App-perlimports-0.000067# CLAUDE.md This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. ## Project Overview `App::perlimports` is a Perl CLI tool and library that automates cleanup of Perl `use` import statements — making implicit imports explicit and removing unused ones. It requires Perl 5.18+. ## Commands **Run all tests:** ```bash prove -lr -j2 t ``` **Run a single test file:** ```bash prove -l t/cli.t ``` **Lint all code:** ```bash precious lint --all ``` **Tidy all code:** ```bash precious tidy --all ``` **Build the distribution (requires Dist::Zilla):** ```bash dzil build ``` ## Code Quality Tools `precious.toml` configures: - `perlimports` — run via `perl -Ilib script/perlimports`, with `--lint` for linting or `-i` for tidying - `perltidy` — formatter governed by `perltidyrc` (4-space indent, 78-char lines) - `perlcritic` — style checker governed by `perlcriticrc` (severity 3) - `omegasort` — sorts `.gitignore` and `.stopwords` ## Architecture The tool is built on [PPI](https://metacpan.org/pod/PPI) (Perl Parse Interface) and uses [Moo](https://metacpan.org/pod/Moo) for its object system with [Types::Standard](https://metacpan.org/pod/Types::Standard) for validation. **Data flow:** ``` CLI -> Document -> Include -> ExportInspector -> Sandbox |-> Config |-> Annotations |-> PPI (parse tree) ``` **Key modules in `lib/App/perlimports/`:** - **CLI.pm** — Parses CLI arguments, manages I/O (file or stdin), dispatches to Document. Handles `--inplace-edit`, `--json`, `--lint`, `--config`. Discovers config via `XDG_CONFIG_HOME` when `--config` is not specified. - **Document.pm** — Core logic. Wraps `PPI::Document`, identifies all imports in a file, determines which symbols are actually used, and coordinates rewriting. - **Include.pm** — Represents a single `use Module ...` statement. Tracks which exported symbols are used and formats the corrected import line. - **ExportInspector.pm** — Inspects a module's `@EXPORT`, `@EXPORT_OK`, and `@EXPORT_TAGS` by loading it in a sandboxed `eval`. Handles both `Exporter` and `Sub::Exporter` styles. - **Config.pm** — Reads `perlimports.toml`. Manages ignore lists, lib paths, logging, and output format. - **Annotations.pm** — Parses `## no perlimports` / `## use perlimports` inline comment directives that let users disable or re-enable the tool for ranges of code. - **Sandbox.pm** — Provides an isolated environment for safely evaluating module exports without polluting the main namespace. **Entry points:** - `script/perlimports` — Thin CLI script that delegates to `App::perlimports::CLI`. - `script/dump-perl-exports` — Utility to inspect a module's exports directly. ## Test Layout - `t/*.t` — Main test suite (~85 files) - `t/ExportInspector/` — Tests specific to export inspection logic - `t/cpan-modules/` — Integration tests against real CPAN modules - `t/lib/` — Shared test utilities (`TestHelper.pm`) - `test-data/lib/` — Sample Perl modules used as test fixtures ## Dependencies Declared in `cpanfile`. The build is managed by [Dist::Zilla](https://metacpan.org/pod/Dist::Zilla) via `dist.ini` — **do not edit `Makefile.PL` directly**, it is generated. ## Development Notes - The `perlimports.toml` at the repo root configures the tool for its own source (libs: `lib` and `t/lib`). - Attributes in the Moo classes use lazy initialization extensively — be careful when adding new attributes that existing tests may not exercise lazy code paths. - A pre-commit hook (`git/hooks/pre-commit`) runs `precious lint --staged`; install it with `bash git/setup.sh`. - PPI is a regular CPAN dependency (version 1.276 minimum), not a fork. after.t100755001750001751 106015261510577 15715 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!perl use strict; use warnings; use lib 't/lib', 'test-data/lib'; use TestHelper qw( doc ); use Test::More import => [qw( done_testing is )]; use Test::Needs qw( List::AllUtils ); my ($doc) = doc( filename => 'test-data/lib/Local/After.pm', ); my $expected = <<'EOF'; package Local::After; use Moose; use List::AllUtils qw( uniq ); my @foo = uniq { 1..10 }; after run => sub { my @foo = uniq ( 1..9 ) }; sub run { 1; } 1; EOF is( $doc->tidied_document, $expected, 'Moose::after() is not assigned to List::AllUtils' ); done_testing; dupes.t100755001750001751 221215261510577 15734 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use lib 't/lib'; use TestHelper qw( doc ); use Test::More import => [qw( done_testing is subtest )]; subtest 'preserve duplicates' => sub { my ($doc) = doc( filename => 'test-data/dupes.pl', ); my $expected = <<'EOF'; use strict; use warnings; use File::Temp qw( tempdir tempfile ); use List::Util qw( any ); use File::Temp qw( tempdir tempfile ); # some comments sub foo { my $dir = tempdir(); my $file = tempfile(); return any { $_ > 1 } ( 0 .. 2 ); } EOF my $got = $doc->tidied_document; is( $got, $expected, 'duplicate use statement removed' ); }; subtest 'strip duplicates' => sub { my ($doc) = doc( filename => 'test-data/dupes.pl', preserve_duplicates => 0, ); my $expected = <<'EOF'; use strict; use warnings; use File::Temp qw( tempdir tempfile ); use List::Util qw( any ); sub foo { my $dir = tempdir(); my $file = tempfile(); return any { $_ > 1 } ( 0 .. 2 ); } EOF is( $doc->tidied_document, $expected, 'duplicate use statement removed' ); }; done_testing; moose.t100755001750001751 264015261510577 15743 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!/usr/bin/env perl use strict; use warnings; use lib 'test-data/lib', 't/lib'; use TestHelper qw( doc ); use Test::More import => [qw( done_testing is subtest )]; use Test::Needs qw( Import::Into Moose ); subtest 'Moose' => sub { my ($doc) = doc( filename => 'test-data/lib/Local/UsesMoose.pm', preserve_unused => 1, ); my $expected = <<'EOF'; package Local::UsesMoose; use Moose; has foo => ( is => 'ro', isa => 'Str', ); __PACKAGE__->meta->make_immutable; 1; EOF is( $doc->tidied_document, $expected, 'document unchanged' ); }; subtest 'Import::Into' => sub { my ($doc) = doc( filename => 'test-data/lib/Local/MyOwnMoose.pm', preserve_unused => 1, ); my $expected = <<'EOF'; package Local::MyOwnMoose; use strict; use warnings; use Import::Into; sub import { $_->import::into( scalar caller ) for qw( Moose ); } 1; EOF is( $doc->tidied_document, $expected, 'tidied_document' ); }; subtest 'Uses MyOwnMoose' => sub { my ($doc) = doc( filename => 'test-data/lib/Local/UsesMyOwnMoose.pm', preserve_unused => 1, ); my $expected = <<'EOF'; package Local::UsesMyOwnMoose; use strict; use warnings; use Local::MyOwnMoose; 1; EOF is( $doc->tidied_document, $expected, 'tidied_document' ); }; done_testing(); README.md100644001750001751 122615261510577 15444 0ustar00olafolaf000000000000App-perlimports-0.000067# NAME App::perlimports - Make implicit imports explicit # VERSION version 0.000067 # DESCRIPTION This distribution provides the [perlimports](https://metacpan.org/pod/perlimports) command line interface (CLI), which aims to automate the cleanup and maintenance of Perl import statements. See [perlimports](https://metacpan.org/pod/perlimports) for detailed information on how to use this tool. # AUTHOR Olaf Alders # COPYRIGHT AND LICENSE This software is copyright (c) 2020 by Olaf Alders. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. perltidyrc100644001750001751 36215261510577 16251 0ustar00olafolaf000000000000App-perlimports-0.000067--blank-lines-before-packages=0 --iterations=2 --no-outdent-long-comments --character-encoding=none -b -bar -boc -ci=4 -i=4 -l=78 -nolq -se -wbb="% + - * / x != == >= <= =~ !~ < > | & >= < = **= += *= &= <<= &&= -= /= |= >>= ||= .= %= ^= x=" Config.t100755001750001751 364115261510577 16030 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!/usr/bin/env perl use strict; use warnings; use App::perlimports::Config (); use Path::Tiny (); use Test::Differences qw( eq_or_diff ); use Test::Fatal qw( exception ); use Test::More import => [qw( done_testing is like ok subtest )]; use TOML::Tiny qw( from_toml ); my $dir = Path::Tiny->tempdir('testconfigXXXXXXXX'); my $file = $dir->child('perlimports.toml'); ok( App::perlimports::Config->create_config($file), 'create_config' ); { my $config = from_toml( $file->slurp ); eq_or_diff( $config->{libs}, [ 'lib', 't/lib' ], 'default libs' ); } like( exception { App::perlimports::Config->create_config($file) }, qr{already exists}, 'file already exists' ); subtest 'defaults' => sub { # Isolate from a user ~/.perltidyrc that could change the indent # default asserted below. my $home = Path::Tiny->tempdir; local $ENV{HOME} = "$home"; delete local $ENV{PERLTIDY}; # Ensure defaults don't throw exceptions my $config = App::perlimports::Config->new; ok( !$config->cache, 'no cache' ); eq_or_diff( $config->ignore, [], 'empty ignore' ); eq_or_diff( $config->ignore_pattern, [], 'empty ignore_pattern' ); eq_or_diff( $config->libs, [], 'empty libs' ); is( $config->log_filename, q{}, 'empty log_filename' ); is( $config->log_level, 'error', 'log_level is error' ); eq_or_diff( $config->never_export, [], 'empty never_export' ); ok( $config->padding, 'padding on' ); ok( $config->preserve_duplicates, 'preserve_duplicates on' ); ok( $config->preserve_require, 'preserve_require on' ); ok( $config->preserve_unused, 'preserve_unused on' ); ok( $config->tidy_whitespace, 'tidy_whitespace on' ); ok( !$config->pad_brackets, 'pad_brackets off by default' ); is( $config->indent, 4, 'indent defaults to 4 (from perltidy)' ); }; done_testing; geo-ip.t100755001750001751 101615261510577 15775 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!/usr/bin/env perl use strict; use warnings; # misses import in ternary use lib 't/lib'; use TestHelper qw( source2pi ); use Test::More import => [qw( done_testing is is_deeply )]; use Test::Needs qw( Geo::IP ); my $e = source2pi( 'test-data/geo-ip.pl', 'use Geo::IP;', ); is_deeply( $e->_imports, [ 'GEOIP_MEMORY_CACHE', 'GEOIP_STANDARD' ], '_imports' ); is( $e->formatted_ppi_statement, 'use Geo::IP qw( GEOIP_MEMORY_CACHE GEOIP_STANDARD );', 'formatted_ppi_statement' ); done_testing(); indent.t100644001750001751 414515261510577 16101 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!/usr/bin/env perl use strict; use warnings; use lib 't/lib', 'test-data/lib'; use TestHelper qw( doc ); use Test::More import => [qw( done_testing is like subtest unlike )]; subtest 'default indent' => sub { my ($doc) = doc( filename => 'test-data/long-list.pl' ); is( $doc->tidied_document, <<'EOF', 'default indent is 4 spaces' ); use strict; use warnings; use lib 'test-data/lib'; use Local::LongList qw( alpha bravo charlie delta echo foxtrot golf hotel india juliet ); alpha(); bravo(); charlie(); delta(); echo(); foxtrot(); golf(); hotel(); india(); juliet(); EOF }; subtest 'indent=2' => sub { my ($doc) = doc( filename => 'test-data/long-list.pl', indent => 2, ); is( $doc->tidied_document, <<'EOF', 'indent=2 produces 2-space indent' ); use strict; use warnings; use lib 'test-data/lib'; use Local::LongList qw( alpha bravo charlie delta echo foxtrot golf hotel india juliet ); alpha(); bravo(); charlie(); delta(); echo(); foxtrot(); golf(); hotel(); india(); juliet(); EOF }; subtest 'indent=8' => sub { my ($doc) = doc( filename => 'test-data/long-list.pl', indent => 8, ); is( $doc->tidied_document, <<'EOF', 'indent=8 produces 8-space indent' ); use strict; use warnings; use lib 'test-data/lib'; use Local::LongList qw( alpha bravo charlie delta echo foxtrot golf hotel india juliet ); alpha(); bravo(); charlie(); delta(); echo(); foxtrot(); golf(); hotel(); india(); juliet(); EOF }; subtest 'indent=2 applies to wrapped test-builder imports' => sub { my ($doc) = doc( filename => 'test-data/long-test-more.pl', indent => 2, ); my $tidied = $doc->tidied_document; like( $tidied, qr/^ qw\(/m, 'wrapped test-builder qw() uses 2-space indent' ); unlike( $tidied, qr/^ qw\(/m, 'wrapped test-builder qw() does not use default 4-space indent' ); }; done_testing(); method.t100755001750001751 102515261510577 16075 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use lib 't/lib'; use TestHelper qw( doc ); use Test::More import => [qw( done_testing is )]; use Test::Needs qw( LWP::UserAgent ); my ($doc) = doc( filename => 'test-data/method.pl', selection => 'use HTTP::Status;' ); # Ensure that the ->is_success method call on an HTTP::Response object doesn't # result in an "is_success" function import for HTTP::Status. is( $doc->tidied_document, 'use HTTP::Status ();', 'is_success method not added to function imports' ); done_testing(); pragma.t100755001750001751 147315261510577 16073 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!/usr/bin/env perl use strict; use warnings; # Ensure that the pragma "use warnings;" does not get mistaken for a use of the # warnings() function exported via Test::Warnings. use lib 't/lib'; use Path::Tiny qw( path ); use TestHelper qw( source2pi ); use Test::More import => [qw( done_testing is ok )]; my $filename = 'test-data/pragma.t'; my $content = path($filename)->slurp; my $doc = PPI::Document->new( \$content ); my $includes = $doc->find( sub { $_[1]->isa('PPI::Statement::Include'); } ) || []; is( scalar @{$includes}, 4, 'found 4 includes' ); my $e = source2pi( $filename, undef, { include => $includes->[3] }, ); ok( !$e->_is_ignored, 'is not ignored' ); is( $e->formatted_ppi_statement, 'use Test::Warnings ();', 'formatted_ppi_statement' ); done_testing; socket.t100755001750001751 336515261510577 16116 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!perl use strict; use warnings; use lib 't/lib'; use Test::Differences qw( eq_or_diff ); use TestHelper qw( doc logger ); use Test::More import => [qw( done_testing is ok subtest )]; subtest tidy => sub { my ($doc) = doc( filename => 'test-data/socket.pl', ); my $expected = <<'EOF'; use strict; use warnings; use IO::Socket::INET (); use Socket qw( SO_REUSEPORT SOL_SOCKET ); foo( SO_REUSEPORT, SOL_SOCKET ); sub foo { } EOF is( $doc->tidied_document, $expected, 'Two modules with the same exports do not get conflated' ); }; subtest lint => sub { my @log; my $logger = logger( \@log, 'error' ); my ($doc) = doc( filename => 'test-data/socket.pl', lint => 1, logger => $logger, ); ok( !$doc->linter_success, 'fails linting' ); ## no critic (ValuesAndExpressions::ProhibitImplicitNewlines) eq_or_diff( \@log, [ { level => 'error', message => "\x{274c}" . ' IO::Socket::INET (import arguments need tidying) at test-data/socket.pl line 4', }, { level => 'error', message => '@@ -4 +4 @@ -use IO::Socket::INET; +use IO::Socket::INET (); ', }, { level => 'error', message => "\x{274c}" . ' Socket (import arguments need tidying) at test-data/socket.pl line 5', }, { level => 'error', message => '@@ -5 +5 @@ -use Socket qw(SO_REUSEPORT SOL_SOCKET); +use Socket qw( SO_REUSEPORT SOL_SOCKET ); ', }, ], 'linting errors logged' ); }; done_testing; sorter.t100644001750001751 1356215261510577 16161 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!perl use strict; use warnings; use lib 't/lib', 'test-data/lib'; use App::perlimports::Sorter (); use Test::Differences qw( eq_or_diff ); use TestHelper qw( logger ); use Test::More import => [qw( done_testing )]; sub sorted { my $source = shift; return App::perlimports::Sorter->new( logger => logger( [] ), source => $source, )->sorted_document; } # Heredocs always add a trailing newline; strip it for cases that must # exercise source lacking a final newline. sub no_trailing_nl { my $s = shift; chomp $s; return $s; } eq_or_diff( sorted(<<'IN'), use Foo; use Bar; use Baz; IN <<'OUT', use Bar; use Baz; use Foo; OUT 'basic sort', ); eq_or_diff( sorted(<<'IN'), use Foo; use strict; use Bar; IN <<'OUT', use strict; use Bar; use Foo; OUT 'pragma hoisted with injected blank line', ); eq_or_diff( sorted(<<'IN'), use Foo; use Bar; use Zoo; use Apple; IN <<'OUT', use Bar; use Foo; use Apple; use Zoo; OUT 'independent sections', ); eq_or_diff( sorted(<<'IN'), use Charlie; use Bravo; ## no perlimports use Alpha; IN <<'OUT', use Alpha; use Bravo; ## no perlimports use Charlie; OUT 'annotated module anchored, others fill slots', ); eq_or_diff( sorted(<<'IN'), # uses Foo use Foo; # uses Bar use Bar; IN <<'OUT', # uses Bar use Bar; # uses Foo use Foo; OUT 'leading comments travel', ); eq_or_diff( sorted(<<'IN'), use Foo; require "config.pl"; use Bar; IN <<'OUT', use Bar; require "config.pl"; use Foo; OUT 'string require anchored', ); eq_or_diff( sorted(<<'IN'), use Foo; require Bar; IN <<'OUT', require Bar; use Foo; OUT 'require Module sorts with use', ); eq_or_diff( sorted(<<'IN'), use Foo; use 5.010; use strict; use Bar; IN <<'OUT', use 5.010; use strict; use Bar; use Foo; OUT 'version and pragma hoisted, order preserved', ); eq_or_diff( sorted(<<'IN'), use Apple; use Banana; IN <<'OUT', use Apple; use Banana; OUT 'already sorted is a no-op', ); { my $once = sorted(<<'IN'); use Foo; use strict; use Bar; IN my $twice = sorted($once); eq_or_diff( $twice, $once, 'sorting is idempotent' ); } eq_or_diff( sorted(<<'IN'), ## no perlimports use Zebra; use Ant; ## use perlimports IN <<'OUT', ## no perlimports use Zebra; use Ant; ## use perlimports OUT 'block-form annotation region left intact', ); # A shared-line section cannot be safely reordered, so multiple includes on # one physical line are left unchanged. eq_or_diff( sorted(<<'IN'), use Zoo; use strict; use Apple; IN <<'OUT', use Zoo; use strict; use Apple; OUT 'shared-line section left unchanged', ); # The shared-line bail is per-section, not global: a normal separate-line # section still sorts while the shared-line section stays intact. eq_or_diff( sorted(<<'IN'), use Zoo; use Apple; use Foo; use Bar; IN <<'OUT', use Zoo; use Apple; use Bar; use Foo; OUT 'shared-line section left intact, normal section still sorted', ); # A final include without a trailing newline must not be jammed onto one line, # and the missing trailing newline must be preserved. eq_or_diff( sorted( no_trailing_nl(<<'IN') ), use Foo; use Bar; IN no_trailing_nl(<<'OUT'), use Bar; use Foo; OUT 'no trailing newline preserved, not jammed', ); { my $once = sorted( no_trailing_nl(<<'IN') ); use Foo; use Bar; IN my $twice = sorted($once); eq_or_diff( $twice, $once, 'no-trailing-newline sort is idempotent' ); } # In byte order 'S' (0x53) sorts before 'n' (0x6E), so a case-sensitive sort # would keep SOAP first; case-insensitive ordering puts namespace first. (Both # names are non-pragma: a bare lowercase word like 'strict' is a pragma, but # 'namespace::clean' is not.) eq_or_diff( sorted(<<'IN'), use SOAP::Lite; use namespace::clean; IN <<'OUT', use namespace::clean; use SOAP::Lite; OUT 'sort key is case-insensitive', ); eq_or_diff( sorted(<<'IN'), use Foo; # keep foo use Bar; # keep bar IN <<'OUT', use Bar; # keep bar use Foo; # keep foo OUT 'trailing same-line comment travels with its import', ); eq_or_diff( sorted(<<'IN'), use Zoo qw( a b ); use Apple; IN <<'OUT', use Apple; use Zoo qw( a b ); OUT 'multi-line use statement moves as a block', ); eq_or_diff( sorted(<<'IN'), use Foo; no Bar; use Apple; IN <<'OUT', use Apple; no Bar; use Foo; OUT 'non-pragma no Module is anchored, others fill slots', ); eq_or_diff( sorted(<<'IN'), use Foo; require Foo; IN <<'OUT', use Foo; require Foo; OUT 'equal keys retain original relative order (stable sort)', ); eq_or_diff( sorted(<<'IN'), # a # b use Foo; use Bar; IN <<'OUT', use Bar; # a # b use Foo; OUT 'multiple leading comment lines travel together', ); eq_or_diff( sorted(<<'IN'), use strict; use warnings; IN <<'OUT', use strict; use warnings; OUT 'pragmas-only section is a no-op', ); eq_or_diff( sorted(<<'IN'), use Zebra; use Mango; ## no perlimports use Apple; use Beta; ## no perlimports IN <<'OUT', use Apple; use Mango; ## no perlimports use Zebra; use Beta; ## no perlimports OUT 'multiple anchors keep slots while sortables fill the rest', ); # The heredoc body contains lines that look like includes; the line-splice # sorter must leave them byte-for-byte untouched. eq_or_diff( sorted(<<'IN'), use Foo; use Bar; my $x = <<'END'; use ZZZ; use AAA; END IN <<'OUT', use Bar; use Foo; my $x = <<'END'; use ZZZ; use AAA; END OUT 'heredoc content is not treated as includes', ); # Source with no include statements is returned unchanged. eq_or_diff( sorted(<<'IN'), my $x = 1; my $y = 2; IN <<'OUT', my $x = 1; my $y = 2; OUT 'source with no includes is a no-op', ); # Source PPI cannot parse is returned unchanged rather than dying. eq_or_diff( sorted("\x00\x01\x02"), "\x00\x01\x02", 'unparseable source is returned unchanged', ); done_testing(); Makefile.PL100644001750001751 735615261510577 16151 0ustar00olafolaf000000000000App-perlimports-0.000067# This file was automatically generated by Dist::Zilla::Plugin::MakeMaker v6.037 use strict; use warnings; use 5.018000; use ExtUtils::MakeMaker; my %WriteMakefileArgs = ( "ABSTRACT" => "Make implicit imports explicit", "AUTHOR" => "Olaf Alders ", "CONFIGURE_REQUIRES" => { "ExtUtils::MakeMaker" => 0 }, "DISTNAME" => "App-perlimports", "EXE_FILES" => [ "script/dump-perl-exports", "script/perlimports" ], "LICENSE" => "perl", "MIN_PERL_VERSION" => "5.018000", "NAME" => "App::perlimports", "PREREQ_PM" => { "Capture::Tiny" => 0, "Class::Inspector" => "1.36", "Cpanel::JSON::XS" => 0, "Data::Dumper" => 0, "Data::UUID" => 0, "File::Basename" => 0, "File::XDG" => "1.01", "Getopt::Long::Descriptive" => 0, "List::Util" => 0, "Log::Dispatch" => "2.70", "Memoize" => 0, "Module::Runtime" => 0, "Moo" => 0, "Moo::Role" => 0, "MooX::StrictConstructor" => 0, "PPI" => "1.276", "PPI::Document" => 0, "PPIx::Utils::Classification" => 0, "PPIx::Utils::Traversal" => 0, "Path::Iterator::Rule" => 0, "Path::Tiny" => 0, "Perl::Tidy" => 20220613, "Pod::Usage" => 0, "Ref::Util" => 0, "Scalar::Util" => 0, "Sereal::Decoder" => 0, "Sereal::Encoder" => 0, "Sub::HandlesVia" => 0, "Symbol::Get" => "0.10", "TOML::Tiny" => "0.16", "Text::Diff" => 0, "Text::SimpleTable::AutoWidth" => 0, "Try::Tiny" => 0, "Types::Common::Numeric" => 0, "Types::Standard" => 0, "feature" => 0, "strict" => 0, "utf8" => 0, "warnings" => 0 }, "TEST_REQUIRES" => { "ExtUtils::MakeMaker" => 0, "File::Spec" => 0, "File::pushd" => 0, "Log::Dispatch::Array" => 0, "PPI::Dumper" => 0, "Sub::Exporter" => 0, "Test::Differences" => 0, "Test::Fatal" => 0, "Test::More" => 0, "Test::Needs" => 0, "Test::RequiresInternet" => 0, "Test::Script" => "1.29", "Test::Warnings" => 0, "lib" => 0 }, "VERSION" => "0.000067", "test" => { "TESTS" => "t/*.t t/ExportInspector/*.t t/cpan-modules/*.t" } ); my %FallbackPrereqs = ( "Capture::Tiny" => 0, "Class::Inspector" => "1.36", "Cpanel::JSON::XS" => 0, "Data::Dumper" => 0, "Data::UUID" => 0, "ExtUtils::MakeMaker" => 0, "File::Basename" => 0, "File::Spec" => 0, "File::XDG" => "1.01", "File::pushd" => 0, "Getopt::Long::Descriptive" => 0, "List::Util" => 0, "Log::Dispatch" => "2.70", "Log::Dispatch::Array" => 0, "Memoize" => 0, "Module::Runtime" => 0, "Moo" => 0, "Moo::Role" => 0, "MooX::StrictConstructor" => 0, "PPI" => "1.276", "PPI::Document" => 0, "PPI::Dumper" => 0, "PPIx::Utils::Classification" => 0, "PPIx::Utils::Traversal" => 0, "Path::Iterator::Rule" => 0, "Path::Tiny" => 0, "Perl::Tidy" => 20220613, "Pod::Usage" => 0, "Ref::Util" => 0, "Scalar::Util" => 0, "Sereal::Decoder" => 0, "Sereal::Encoder" => 0, "Sub::Exporter" => 0, "Sub::HandlesVia" => 0, "Symbol::Get" => "0.10", "TOML::Tiny" => "0.16", "Test::Differences" => 0, "Test::Fatal" => 0, "Test::More" => 0, "Test::Needs" => 0, "Test::RequiresInternet" => 0, "Test::Script" => "1.29", "Test::Warnings" => 0, "Text::Diff" => 0, "Text::SimpleTable::AutoWidth" => 0, "Try::Tiny" => 0, "Types::Common::Numeric" => 0, "Types::Standard" => 0, "feature" => 0, "lib" => 0, "strict" => 0, "utf8" => 0, "warnings" => 0 ); unless ( eval { ExtUtils::MakeMaker->VERSION(6.63_03) } ) { delete $WriteMakefileArgs{TEST_REQUIRES}; delete $WriteMakefileArgs{BUILD_REQUIRES}; $WriteMakefileArgs{PREREQ_PM} = \%FallbackPrereqs; } delete $WriteMakefileArgs{CONFIGURE_REQUIRES} unless eval { ExtUtils::MakeMaker->VERSION(6.52) }; WriteMakefile(%WriteMakefileArgs); Sandbox.t100644001750001751 763115261510577 16221 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use lib 't/lib', 'test-data/lib'; use App::perlimports::Sandbox (); use TestHelper qw( doc ); use Test::Differences qw( eq_or_diff ); use Test::More import => [qw( cmp_ok diag done_testing ok subtest )]; my $pkg1 = App::perlimports::Sandbox::pkg_for('fakeblock'); my $pkg2 = App::perlimports::Sandbox::pkg_for('fakeblock'); ok( $pkg1, 'first pkg' ); ok( $pkg2, 'second pkg' ); cmp_ok( $pkg1, 'ne', $pkg2, 'names are not the same' ); subtest 'Carp' => sub { my $eval = App::perlimports::Sandbox::eval_pkg( 'Carp', 'use Carp qw( croak );', ); ok( !$eval, 'no problems with eval' ); }; subtest 'missing module' => sub { my $eval = App::perlimports::Sandbox::eval_pkg( 'Local::ZZZ::XXX', 'use Local::ZZZ::XXX ();', ); ok( $eval, 'eval failure' ); }; subtest 'local module' => sub { my $eval = App::perlimports::Sandbox::eval_pkg( 'Local::ImportException', 'use Local::ImportException ();', ); ok( !$eval, 'no eval failure' ); }; subtest 'local module with exception' => sub { my $eval = App::perlimports::Sandbox::eval_pkg( 'Local::ImportException', 'use Local::ImportException qw( exceptional );', ); ok( $eval, 'eval failure' ); }; subtest 'real trial-load warning is suppressed' => sub { # End-to-end check: trial-load a dependency-free module that has no # import() method while passing a non-empty import list -- the same shape # as the original report, "use LWP::UserAgent qw( new );". With no import() # to hand the list to, Perl emits its actual "Attempt to call # undefined/missing import method" warning (the symbol name is irrelevant; # only the non-empty list matters -- a bare "use" stays silent). eval_pkg # must swallow it so nothing reaches this outer handler, verifying # suppression against whatever wording this Perl version uses (see GH #181). my @leaked; local $SIG{__WARN__} = sub { push @leaked, @_ }; my $error = App::perlimports::Sandbox::eval_pkg( 'Local::NoImport', 'use Local::NoImport qw( new );', ); ok( !$error, 'module trial-loads without error' ); ok( !( grep { m/call (?:undefined|missing) import method/ } @leaked ), 'no trial-load import-method warning leaks to the outer handler' ) or diag "leaked: @leaked"; }; subtest 'trial-load warning recognized across Perl versions' => sub { # We deliberately exercise the private predicate directly here. ## no critic (Subroutines::ProtectPrivateSubs) # Perl reworded this diagnostic from "undefined" to "missing" in the 5.44 # development cycle (see GH #181). Both wordings must be suppressed so the # noise never leaks to the user's terminal, regardless of the running Perl. my $args = q{("new") via package "LWP::UserAgent"}; my $tail = ' (Perhaps you forgot to load the package?) at (eval 1) line 1.'; ok( App::perlimports::Sandbox::_is_trial_load_warning( "Attempt to call undefined import method with arguments $args$tail" ), 'undefined (Perl <= 5.42) wording is recognized' ); ok( App::perlimports::Sandbox::_is_trial_load_warning( "Attempt to call missing import method with arguments $args$tail" ), 'missing (Perl >= 5.44) wording is recognized' ); ok( !App::perlimports::Sandbox::_is_trial_load_warning( 'Some other warning we should let through'), 'unrelated warnings are not suppressed' ); }; subtest 'eval in tidied_document' => sub { my ($doc) = doc( filename => 'test-data/exceptional.pl' ); my $expected = <<'EOF'; use strict; use warnings; use Carp qw( croak ); use Local::ImportException; exceptional(); croak(); EOF eq_or_diff( $doc->tidied_document, $expected, 'does not update import with eval failure' ); }; done_testing(); builtin.t100644001750001751 62715261510577 16247 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use App::perlimports::Document (); use Test::More import => [qw( done_testing is )]; my $doc = App::perlimports::Document->new( filename => 'test-data/builtin.pl' ); my $expected = <<'EOF'; use strict; use warnings; use POSIX (); printf('%s', 'ok'); EOF is( $doc->tidied_document, $expected, 'Perl builtin does not get added to POSIX imports' ); done_testing(); english.t100644001750001751 54415261510577 16230 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use lib 't/lib'; use TestHelper qw( doc ); use Test::More import => [qw( done_testing is )]; my ($doc) = doc( filename => 'test-data/english.pl' ); my $expected = <<'EOF'; use strict; use warnings; use English qw( -no_match_vars ); EOF is( $doc->tidied_document, $expected, '-no-match-vars is preserved' ); done_testing(); heredoc.t100755001750001751 66715261510577 16221 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!/usr/bin/env perl use strict; use warnings; use lib 't/lib'; use Test::More import => [qw( done_testing is )]; use Test::Needs qw( Perl::Critic::Utils ); use TestHelper qw( source2pi ); my $source_text = 'use Perl::Critic::Utils;'; my $e = source2pi( 'test-data/heredoc.pl', $source_text ); is( $e->formatted_ppi_statement, 'use Perl::Critic::Utils qw( $QUOTE );', 'var in heredoc found' ); done_testing(); memoize.t100755001750001751 333615261510577 16271 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!perl use strict; use warnings; # This is a regression test for an error which occurs when using # "memoize('is_function_call')" in Include.pm. It appears only in cases where # the CLI is processing multiple files in a specific order. In the bug # scenario, "use MooseX::Types::UUID ();" in test-data/b.pl is transformed to # "use MooseX::Types::UUID qw( UUID );", despite the fact that "UUID" is not an # imported symbol in b.pl. This happens in the case where "a.pl" is process # first and "is_function_call('UUID')" has already been memoized. # # We use "memoize" on "is_function_call" because it was identified as a hotspot # in earlier profiling. use Test::More import => [qw( done_testing )]; # Loading the UUID XS module wedges prove at process exit on macOS: the test # passes but the worker never exits, hanging CI at the runner time limit. The # behaviour under test (memoization of is_function_call in Include.pm) is # platform-independent, so skip on darwin. This BEGIN must precede the # Test::Needs line below, which itself require()s UUID. See the macOS notes in # .github/workflows/dzil-build-and-test.yml. BEGIN { Test::More::plan( skip_all => 'Loading the UUID XS module hangs prove at exit on macOS' ) if $^O eq 'darwin'; } use lib 't/lib'; use Path::Tiny qw( path ); use Test::Differences qw( eq_or_diff ); use TestHelper qw( doc ); use Test::Needs qw( MooseX::Types::UUID UUID ); { my ($doc) = doc( filename => 'test-data/a.pl' ); $doc->tidied_document; } { my ($doc) = doc( filename => 'test-data/b.pl', preserve_unused => 1, ); eq_or_diff( $doc->tidied_document, path('test-data/b.pl')->slurp, 'doc has not changed' ); } done_testing(); padding.t100755001750001751 61515261510577 16207 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!/usr/bin/env perl use strict; use warnings; use lib 't/lib'; use TestHelper qw( doc ); use Test::More import => [qw( done_testing is )]; my ($doc) = doc( filename => 'test-data/carp.pl', padding => 0, ); my $expected = <<'EOF'; use strict; use warnings; use Carp qw(croak verbose); croak('oof'); EOF is( $doc->tidied_document, $expected, 'list is not padded' ); done_testing(); require.t100755001750001751 1103215261510577 16310 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!/usr/bin/env perl use strict; use warnings; use lib 't/lib'; use Path::Tiny qw( path ); use TestHelper qw( doc source2pi ); use Test::More import => [qw( done_testing is like ok subtest unlike )]; use Test::Needs qw( LWP::UserAgent ); my $filename = 'test-data/require.pl'; subtest 'preserve top level require via snippet by default' => sub { my $e = source2pi( $filename, 'require LWP::UserAgent;', ); ok( $e->_is_ignored, 'is ignored' ); is( $e->formatted_ppi_statement, 'require LWP::UserAgent;', 'require is preserved by default' ); }; subtest 'translate top level require via snippet when opted out' => sub { my $e = source2pi( $filename, 'require LWP::UserAgent;', { preserve_require => 0 }, ); ok( !$e->_is_ignored, 'is not ignored' ); is( $e->formatted_ppi_statement, 'use LWP::UserAgent ();', 'formatted_ppi_statement' ); }; my $content = path($filename)->slurp; my ($require_doc) = PPI::Document->new( \$content ); my $includes = $require_doc->find( sub { $_[1]->isa('PPI::Statement::Include'); } ) || []; subtest 'preserve top level require from document by default' => sub { my $e = source2pi( $filename, undef, { include => $includes->[2] }, ); ok( $e->_is_ignored, 'is ignored' ); is( $e->formatted_ppi_statement, 'require LWP::UserAgent;', 'require is preserved by default' ); }; subtest 'translate top level require from document when opted out' => sub { my $e = source2pi( $filename, undef, { include => $includes->[2], preserve_require => 0 }, ); ok( !$e->_is_ignored, 'is not ignored' ); is( $e->formatted_ppi_statement, 'use LWP::UserAgent ();', 'formatted_ppi_statement' ); }; subtest 'preserve require inside if block' => sub { my $e = source2pi( $filename, undef, { include => $includes->[3], preserve_require => 0 }, ); ok( $e->_is_ignored, 'is ignored' ); is( $e->formatted_ppi_statement, 'require WWW::Mechanize;', 'formatted_ppi_statement' ); }; subtest 'preserve require inside postfix if defined' => sub { my $e = source2pi( $filename, undef, { include => $includes->[4], preserve_require => 0 }, ); ok( $e->_is_ignored, 'is ignored' ); is( $e->formatted_ppi_statement, 'require Carp if $ENV{BAR};', 'formatted_ppi_statement' ); }; subtest 'do not import fully qualified function calls when opted out' => sub { my $e = source2pi( $filename, undef, { include => $includes->[5], preserve_require => 0 }, ); is( $e->formatted_ppi_statement, 'use List::Util ();', 'formatted_ppi_statement' ); }; subtest 'preserve require inside postfix if eq' => sub { my $e = source2pi( $filename, undef, { include => $includes->[6], preserve_require => 0 }, ); ok( $e->_is_ignored, 'is ignored' ); is( $e->formatted_ppi_statement, q{require Time::Local if $^O eq 'MacOS';}, 'formatted_ppi_statement' ); }; subtest 'require rewritten as use when opted out' => sub { my $e = source2pi( $filename, undef, { include => $includes->[7], preserve_require => 0 }, ); ok( !$e->_is_ignored, 'is not ignored' ); is( $e->formatted_ppi_statement, 'use Cwd ();', 'formatted_ppi_statement' ); }; subtest 'require Exporter not rewritten' => sub { my ($doc) = doc( filename => 'test-data/lib/Local/RequireExporter.pm', preserve_require => 0, ); my $expected = <<'EOF'; package Local::RequireExporter; use strict; use warnings; require Exporter; our @EXPORT = qw(foo); sub foo { return 'from sub foo' } 1; EOF is( $doc->tidied_document, $expected, 'statement is unchanged' ); }; subtest 'preserve top level require in document by default' => sub { my ($doc) = doc( filename => $filename, ); my $tidied = $doc->tidied_document; like( $tidied, qr{^require LWP::UserAgent;$}m, 'require LWP::UserAgent; preserved' ); like( $tidied, qr{^require Cwd;$}m, 'require Cwd; preserved' ); unlike( $tidied, qr{use \s+ (?:LWP::UserAgent|Cwd) \s+ \(\);}x, 'no requires were translated to use ();' ); }; done_testing(); warning.t100755001750001751 67615261510577 16255 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!/usr/bin/env perl use strict; use warnings; use Test::Differences qw( eq_or_diff ); use Test::More import => [qw( done_testing )]; use Test::Needs qw( Mojo::URL ); use lib 't/lib'; use TestHelper qw( doc logger ); my $log = []; my $logger = logger( $log, 'warning' ); my ($doc) = doc( filename => 'test-data/mojo-url.pl', logger => $logger, ); $doc->tidied_document; eq_or_diff( $log, [], 'no Mojo warnings' ); done_testing(); CONTRIBUTORS100644001750001751 100315261510577 16036 0ustar00olafolaf000000000000App-perlimports-0.000067 # APP-PERLIMPORTS CONTRIBUTORS # This is the (likely incomplete) list of people who have helped make this distribution what it is, either via code contributions, patches, bug reports, help with troubleshooting, etc. A huge 'thank you' to all of them. * Copilot * Dave Rolsky * dependabot[bot] * E. Choroba * James Raspass * José Manuel Rodríguez D * Kenichi Ishigaki * Nelo Onyiah * Nicolas Mendoza * Olaf Alders * Paul Johnson * Peter Oliver * pyrrhlin git000755001750001751 015261510577 14607 5ustar00olafolaf000000000000App-perlimports-0.000067setup.sh100644001750001751 14215261510577 16420 0ustar00olafolaf000000000000App-perlimports-0.000067/git#!/usr/bin/env bash chmod +x git/hooks/pre-commit cd .git/hooks ln -s ../../git/hooks/pre-commit perlcriticrc100644001750001751 614215261510577 16577 0ustar00olafolaf000000000000App-perlimports-0.000067severity = 3 verbose = 11 # default set for non-test files: theme = (core + pbp + bugs + maintenance + cosmetic + complexity + security + moose) # for tests, we will use slightly different list: #theme = (core+pbp+bugs+maintenance+cosmetic+complexity+security+moose + tests) && !nontest program-extensions = pl psgi t # better syntax to disable a policy is prefixing with hyphen like: # [-Subroutines::ProhibitCallsToUndeclaredSubs] # but then perlcritic whines if you don't have it installed. exclude = Subroutines::ProhibitCallsToUndeclaredSubs [BuiltinFunctions::ProhibitStringySplit] severity = 3 [CodeLayout::RequireTrailingCommas] severity = 3 [ControlStructures::ProhibitCStyleForLoops] severity = 3 [Documentation::RequirePackageMatchesPodName] severity = 3 [Freenode::WhileDiamondDefaultAssignment] set_themes = core [InputOutput::RequireCheckedSyscalls] functions = :builtins exclude_functions = binmode print say sleep severity = 3 [Moose::RequireCleanNamespace] modules = Moose Moose::Role MooseX::Role::Parameterized Moose::Util::TypeConstraints cleaners = namespace::autoclean [NamingConventions::Capitalization] package_exemptions = perlimports file_lexical_variables = [A-Z]\w+|[^A-Z]+ global_variables = :starts_with_upper scoped_lexical_variables = [A-Z]\w+|[^A-Z]+ severity = 3 # Given our code base, leaving this at 5 would be a huge pain [Subroutines::ProhibitManyArgs] max_arguments = 10 [RegularExpressions::ProhibitComplexRegexes] max_characters = 200 [RegularExpressions::ProhibitUnusualDelimiters] severity = 3 [Subroutines::ProhibitUnusedPrivateSubroutines] private_name_regex = _(?!build)\w+ [TestingAndDebugging::ProhibitNoWarnings] allow = redefine [ValuesAndExpressions::ProhibitEmptyQuotes] severity = 3 [ValuesAndExpressions::ProhibitInterpolationOfLiterals] severity = 3 [ValuesAndExpressions::RequireUpperCaseHeredocTerminator] severity = 3 [Variables::ProhibitPackageVars] add_packages = Test::Builder [Variables::ProhibitUnusedVarsStricter] # pushd returns a guard object that is kept only for its scope allow_if_computed_by = pushd [-ControlStructures::ProhibitCascadingIfElse] [-ErrorHandling::RequireCarping] [-InputOutput::RequireBriefOpen] [-ValuesAndExpressions::ProhibitConstantPragma] # No need for /xsm everywhere [-RegularExpressions::RequireDotMatchAnything] [-RegularExpressions::RequireExtendedFormatting] [-RegularExpressions::RequireLineBoundaryMatching] # This incorrectly thinks signatures are prototypes. [-Subroutines::ProhibitSubroutinePrototypes] # http://stackoverflow.com/questions/2275317/why-does-perlcritic-dislike-using-shift-to-populate-subroutine-variables [-Subroutines::RequireArgUnpacking] [-Subroutines::RequireFinalReturn] # "use v5.14" is more readable than "use 5.014" [-ValuesAndExpressions::ProhibitVersionStrings] [-Subroutines::ProhibitExplicitReturnUndef] # Too many false positives [-ValuesAndExpressions::ProhibitAccessOfPrivateData] # --- policies that should not be applied to tests: [Bangs::ProhibitNumberedNames] add_themes = nontest [Bangs::ProhibitDebuggingModules] add_themes = nontest #[Modules::RequireExplicitInclusion] #add_themes = nontest Document.t100755001750001751 56615261510577 16364 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!perl use strict; use warnings; use lib 't/lib'; use TestHelper qw( doc ); use Test::More import => [qw( done_testing ok )]; my ($doc) = doc( filename => 'test-data/original-imports.pl' ); ok( $doc->inspector_for('Carp'), 'Carp' ); ok( $doc->inspector_for('Data::Dumper'), 'Data::Dumper' ); ok( $doc->inspector_for('POSIX'), 'POSIX' ); done_testing(); cli-args.t100644001750001751 576015261510577 16325 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use lib 'test-data/lib', 't/lib'; use App::perlimports::CLI (); use Capture::Tiny qw( capture ); use Path::Tiny (); use TestHelper qw( logger ); use Test::Differences qw( eq_or_diff ); use Test::More import => [qw( diag done_testing is like subtest )]; use Test::Needs qw( Perl::Critic::Utils ); subtest 'almost all of the args' => sub { my $expected = <<'EOF'; use strict; use warnings; use Perl::Critic::Utils qw($QUOTE); my %foo = ( $QUOTE => q{description}, ); EOF my $log_file = Path::Tiny->tempfile('perlimportsXXXXXXXX'); local @ARGV = ( '--ignore-modules' => 'CGI,Plack', '--ignore-modules-filename' => 'test-data/ignore-modules.txt', '--ignore-modules-pattern' => '^(Foo|Foo::Bar)', '--ignore-modules-pattern-filename' => 'test-data/ignore-modules-pattern.txt', '--indent' => 2, '--libs' => 'lib,t/lib', '--never-export-modules' => 'Never::One,Never::Two', '--never-export-modules-filename' => 'test-data/never-export-modules.txt', '--log-filename' => "$log_file", '--log-level' => 'info', '--no-cache', '--no-padding', '--no-preserve-duplicates', '--no-preserve-require', '--no-preserve-unused', '--no-tidy-whitespace', '--pad-brackets', 'test-data/var-in-hash-key.pl', ); my $cli = App::perlimports::CLI->new( logger => logger( [] ) ); my ( $stdout, $stderr ) = capture { $cli->run; }; is( $stdout, $expected, 'no exception on args' ) || diag $stderr; my $c = $cli->_config; is( $c->cache, 0, 'cache' ); eq_or_diff( $c->ignore, [ 'CGI', 'Plack', 'Data::Printer', 'Git::Sub' ], 'ignore' ); eq_or_diff( $c->ignore_pattern, ['^(Foo|Foo::Bar)'], 'ignore_pattern' ); eq_or_diff( $c->libs, [ 'lib', 't/lib' ], 'libs' ); like( $c->log_filename, qr{perlimports}, 'log_filename' ); is( $c->log_level, 'info', 'log_level' ); eq_or_diff( $c->never_export, [ 'Never::One', 'Never::Two', 'Never::Three', 'Never::Four', ], 'never_export' ); is( $c->indent, 2, 'indent' ); is( $c->pad_brackets, 1, 'pad_brackets' ); is( $c->padding, 0, 'padding' ); is( $c->preserve_duplicates, 0, 'preserve_duplicates' ); is( $c->preserve_require, 0, 'preserve_require' ); is( $c->tidy_whitespace, 0, 'tidy_whitespace' ); }; # --- sort option plumbing --- { local @ARGV = ( '--no-config-file', 'lib/App/perlimports.pm' ); my $cli = App::perlimports::CLI->new; is( $cli->_config->sort, 0, 'sort defaults to false' ); } { local @ARGV = ( '--no-config-file', '--sort', 'lib/App/perlimports.pm' ); my $cli = App::perlimports::CLI->new; is( $cli->_config->sort, 1, '--sort sets config sort true' ); } done_testing(); datetime.t100644001750001751 62215261510577 16370 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!perl use strict; use warnings; use lib 't/lib'; use TestHelper qw( doc ); use Test::More import => [qw( done_testing is )]; use Test::Needs qw( DateTime ); my ($doc) = doc( filename => 'test-data/datetime.pl' ); my $expected = <<'EOF'; use strict; use warnings; use DateTime (); my $dt = DateTime->now; EOF is( $doc->tidied_document, $expected, 'DateTime does not import' ); done_testing(); do-block.t100755001750001751 73115261510577 16272 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!/usr/bin/env perl use strict; use warnings; use lib 't/lib'; use TestHelper qw( source2pi ); use Test::More import => [qw( done_testing is ok )]; my $source_text = q[use Test::More do { $ENV{COVERAGE} ? ( skip_all => 'skip under Devel::Cover' ) : () };]; my $e = source2pi( 'test-data/skip-all.t', $source_text, ); ok( !$e->_is_ignored, 'noop' ); is( $e->formatted_ppi_statement, $source_text, 'formatted_ppi_statement' ); done_testing(); explodes.t100755001750001751 127115261510577 16443 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!perl use strict; use warnings; use lib 't/lib', 'test-data/lib'; use PPI::Document (); use TestHelper qw( doc ); use Test::More import => [qw( done_testing is ok )]; my ($doc) = doc( filename => 'test-data/explodes.pl', preserve_unused => 0, ); my $expected = <<'EOF'; use strict; use warnings; use Local::Explodes qw( foo ); foo(); EOF is( $doc->tidied_document, $expected, 'modules which throw exceptions are ignored' ); my $raw_include = 'use Local::Explodes qw( foo );'; my $inc = PPI::Document->new( \$raw_include ); my $found = $inc->find('PPI::Statement::Include')->[0]; ok( $doc->_is_ignored($found), '_is_ignored' ); done_testing; find-bin.t100755001750001751 162115261510577 16305 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!/usr/bin/env perl use strict; use warnings; use lib 't/lib'; use Test::Differences qw( eq_or_diff ); use TestHelper qw( doc source2pi ); use Test::More import => [qw( done_testing is is_deeply ok )]; my $e = source2pi( 'test-data/find-bin.pl', 'use FindBin qw( $Bin );', ); is( $e->module_name(), 'FindBin', 'module_name' ); ok( !$e->_is_ignored, 'no longer ignored' ); is_deeply( $e->_imports, [qw($Bin)], 'found import' ); eq_or_diff( $e->formatted_ppi_statement . q{}, 'use FindBin qw( $Bin );', 'formatted_ppi_statement' ); my ($doc) = doc( filename => 'test-data/more-find-bin.pl', preserve_unused => 0, ); my $expected = <<'EOF'; #!/usr/bin/env perl use FindBin (); use lib "$FindBin::Bin/../../../lib"; EOF eq_or_diff( $doc->tidied_document, $expected, 'fully qualified symbol name interpolated into quotes detected' ); done_testing(); hash-key.t100755001750001751 75215261510577 16314 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!/usr/bin/env perl use strict; use warnings; use lib 't/lib'; use TestHelper qw( file2includes source2pi ); use Test::More import => [qw( done_testing is )]; use Test::Needs qw( HTTP::Status ); my @includes = file2includes('test-data/http-status.pl'); my $e = source2pi( 'test-data/http-status.pl', undef, { include => $includes[2] } ); is( $e->formatted_ppi_statement, 'use HTTP::Status qw( is_info );', 'does not think hash key is a function' ); done_testing; skip-all.t100755001750001751 132015261510577 16327 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!/usr/bin/env perl use strict; use warnings; use lib 't/lib'; use TestHelper qw( source2pi ); use Test::Differences qw( eq_or_diff ); use Test::More import => [qw( done_testing ok )]; my $e = source2pi( 'test-data/skip-all.t', q{use Test::More 0.93 skip_all => 'Test is broken', tests => 3, foo => ['bar'] ;}, ); ok( !$e->_is_ignored, 'not an ignored module' ); my $expected = <<'EOF'; use Test::More 0.93 import => [qw( is is_deeply ok )], foo => ['bar'], skip_all => 'Test is broken', tests => 3; EOF chomp $expected; eq_or_diff( $e->formatted_ppi_statement . q{}, $expected, 'formatted_ppi_statement' ); done_testing(); typeglob.t100755001750001751 57515261510577 16433 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use lib 't/lib'; use TestHelper qw( doc ); use Test::More import => [qw( done_testing is )]; use Test::Needs qw( File::chdir ); my ($doc) = doc( filename => 'test-data/typeglob.pl', selection => 'use File::chdir;', ); is( $doc->tidied_document, 'use File::chdir qw( *CWD );', 'translates $CWD to *CWD in import' ); done_testing; variable.t100644001750001751 105115261510577 16376 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!perl use strict; use warnings; use lib 't/lib'; use Test::More import => [qw( done_testing is is_deeply )]; use TestHelper qw( source2pi ); my $source_text = 'use Getopt::Long qw( $REQUIRE_ORDER $RETURN_IN_ORDER );'; my $include = source2pi( 'test-data/variable.pl', $source_text ); is( $include->formatted_ppi_statement, $source_text, 'variable in block is found' ); is_deeply( $include->_document->interpolated_symbols, { '$REQUIRE_ORDER' => 1, '$RETURN_IN_ORDER' => 1, }, 'interpolated_symbols' ); done_testing(); precious.toml100644001750001751 343215261510577 16714 0ustar00olafolaf000000000000App-perlimports-0.000067exclude = [ # Used by Dist::Zilla ".build", "build_dir/**/*", "App-perlimports-*", "blib", "inc", "test-data/**/*", # All of these are generated by Dist::Zilla "t/00-*", "t/author-*", "t/release-*", "xt/author", "xt/release", ] [commands.omegasort-gitignore] type = "both" include = "**/.gitignore" cmd = [ "omegasort", "--sort=text" ] lint-flags = "--check" tidy-flags = "--in-place" ok-exit-codes = 0 lint-failure-exit-codes = 1 # If you have an external stopwords file for use with Test::Spelling [commands.omegasort-stopwords] type = "both" include = ".stopwords" cmd = [ "omegasort", "--sort=text", "--case-insensitive" ] lint-flags = "--check" tidy-flags = "--in-place" ok-exit-codes = 0 lint-failure-exit-codes = 1 [commands.perlimports] type = "both" include = [ "**/*.{pl,pm,t,psgi}" ] cmd = [ "perl", "-Ilib", "script/perlimports" ] lint-flags = ["--lint" ] tidy-flags = ["-i" ] ok-exit-codes = 0 lint-failure-exit-codes = 1 ignore-stderr = [".* OK"] [commands.perltidy] type = "both" include = [ "**/*.{pl,pm,t,psgi}" ] cmd = [ "perltidy", "--profile=$PRECIOUS_ROOT/perltidyrc" ] lint-flags = [ "--assert-tidy", "--no-standard-output", "--outfile=/dev/null" ] tidy-flags = [ "--backup-and-modify-in-place", "--backup-file-extension=/" ] ok-exit-codes = 0 lint-failure-exit-codes = 2 [commands.perlcritic] type = "lint" include = [ "**/*.{pl,pm,psgi}" ] cmd = [ "perlcritic", "--profile=$PRECIOUS_ROOT/perlcriticrc" ] ok-exit-codes = 0 lint-failure-exit-codes = 2 [commands.perlcritic-tests] type = "lint" include = [ "**/*.{t}" ] cmd = [ "perlcritic", "--profile=$PRECIOUS_ROOT/perlcriticrc", "--severity=3", "--theme=(core+pbp+bugs+maintenance+cosmetic+complexity+security+moose+tests) && !nontest" ] ok-exit-codes = 0 lint-failure-exit-codes = 2 constants.t100644001750001751 314215261510577 16630 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!perl use strict; use warnings; use feature 'say'; use lib 'test-data/lib', 't/lib'; use App::perlimports::Document (); use TestHelper qw( logger ); use Test::More import => [qw( done_testing is is_deeply ok subtest )]; subtest 'constants parsed' => sub { my @log; my $doc = App::perlimports::Document->new( lint => 1, filename => 'test-data/use-constant.pm', logger => logger( \@log ), ); is $doc->linter_success, q{}, 'test code has lint issues'; my @possible = $doc->possibly_imported_tokens; my $found = $doc->_ppi_selection->find( sub { $_[1]->isa('PPI::Statement::Package') && $_[1]->file_scoped; } ) || []; my ($packname) = map { $_->namespace } @$found; ok $packname, "package name $packname detected"; $found = grep { $_ eq $packname } @possible; is $found, 0, 'package name is excluded from possible_imports'; $found = grep { $_ eq 'package' } @possible; is $found, 0, 'keyword "package" also excluded'; $found = grep { $_ eq 'use' } @possible; is $found, 0, 'keyword "use" also excluded'; my @cnames = qw(FIRST_IDX IDX_FORMAT IDX_SEP IDX_SEP_RE IDX_STR IDX_UTIME); my @found = sort $doc->all_constants; is_deeply \@found, \@cnames, 'parsed all 6 constants'; # find all "possible imported" tokens that match any of the constants my %cnames = map { $_ => 1 } @cnames; my @matches = grep { $cnames{"$_"} } @possible; is scalar(@matches), 0, 'constants are entirely excluded from possible_imports'; }; done_testing(); local-lib.t100644001750001751 150715261510577 16455 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!perl use strict; use warnings; use lib 't/lib'; use TestHelper qw( doc ); use Test::More import => [qw( done_testing is ok )]; # local::lib manipulates @INC as a side effect of being used. It exports # nothing we'd want to manage, so perlimports must never rewrite or remove # "use local::lib". See GH #117. It's in the default ignore list, so this # holds whether or not local::lib is installed. my ($doc) = doc( filename => 'test-data/local-lib.pl', ); my $expected = <<'EOF'; use strict; use warnings; use local::lib; 1; EOF my $includes = $doc->ppi_document->find('PPI::Statement::Include'); is( $includes->[2]->module, 'local::lib', 'module name' ); ok( $doc->_is_ignored( $includes->[2] ), 'local::lib flagged as ignored' ); is( $doc->tidied_document, $expected, 'use local::lib is left untouched' ); done_testing(); is-ignored.t100755001750001751 111415261510577 16654 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!perl use strict; use warnings; use lib 't/lib'; use TestHelper qw( doc ); use Test::More import => [qw( done_testing is ok )]; my ($doc) = doc( filename => 'test-data/lib/Local/UsesTypesStandard.pm', ); my $expected = <<'EOF'; package Local::UsesTypesStandard; use Types::Standard; 1; EOF my $includes = $doc->ppi_document->find('PPI::Statement::Include'); is( $includes->[0]->module, 'Types::Standard', 'module name' ); ok( $doc->_is_ignored( $includes->[0] ), 'is_ignored flag set' ); is( $doc->tidied_document, $expected, 'Types::Standard is ignored' ); done_testing(); quoted-var.t100755001750001751 125515261510577 16711 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!/usr/bin/env perl use strict; use warnings; use lib 't/lib'; use Path::Tiny qw( path ); use TestHelper qw( source2pi ); use Test::More import => [qw( done_testing is ok )]; my $filename = 'test-data/quoted-var.pl'; my $content = path($filename)->slurp; my $doc = PPI::Document->new( \$content ); my $includes = $doc->find( sub { $_[1]->isa('PPI::Statement::Include'); } ) || []; my $e = source2pi( $filename, undef, { include => $includes->[2] }, ); ok( !$e->_is_ignored, 'is not ignored' ); is( $e->formatted_ppi_statement, 'use IO::Uncompress::Gunzip qw( $GunzipError );', 'var is detected inside of quotes' ); done_testing(); signatures.t100644001750001751 144115261510577 17000 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!perl use strict; use warnings; use Test::Differences qw( eq_or_diff ); use Test::More import => [qw( done_testing )]; use Test::Needs { 'HTTP::Status' => 6.28, perl => 5.020 }; use lib 't/lib'; use TestHelper qw( doc ); my $expected = <<'EOF'; use strict; use warnings; use v5.20; use feature qw(signatures); no warnings qw(experimental::signatures); use signatures; use FindBin qw( $Bin ); use HTTP::Status qw( HTTP_CONTINUE HTTP_OK ); ## no critic (Subroutines::ProhibitSubroutinePrototypes) sub one ( $continue = HTTP_CONTINUE, $foo = 'bar', $two = HTTP_OK() ) { return $continue; } sub two ( $cwd = $Bin ) { } EOF my ($doc) = doc( filename => 'test-data/signatures.pl', preserve_unused => 0 ); eq_or_diff( $doc->tidied_document, $expected, 'tidied_document' ); done_testing; test-data000755001750001751 015261510577 15712 5ustar00olafolaf000000000000App-perlimports-0.000067a.pl100755001750001751 15215261510577 16610 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data#!/usr/bin/env perl use strict; use warnings; use MooseX::Types::UUID qw(UUID); foo(UUID); sub foo {} b.pl100644001750001751 17115261510577 16607 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data#!/usr/bin/env perl use strict; use warnings; use MooseX::Types::UUID (); use UUID qw( uuid ); foo(uuid); sub foo {} author000755001750001751 015261510577 15761 5ustar00olafolaf000000000000App-perlimports-0.000067/xteol.t100644001750001751 622515261510577 17072 0ustar00olafolaf000000000000App-perlimports-0.000067/xt/authoruse strict; use warnings; # this test was generated with Dist::Zilla::Plugin::Test::EOL 0.19 use Test::More 0.88; use Test::EOL; my @files = ( 'lib/App/perlimports.pm', 'lib/App/perlimports/Annotations.pm', 'lib/App/perlimports/CLI.pm', 'lib/App/perlimports/Config.pm', 'lib/App/perlimports/Document.pm', 'lib/App/perlimports/ExportInspector.pm', 'lib/App/perlimports/Include.pm', 'lib/App/perlimports/Role/Logger.pm', 'lib/App/perlimports/Sandbox.pm', 'lib/App/perlimports/Sorter.pm', 'script/dump-perl-exports', 'script/perlimports', 't/00-report-prereqs.dd', 't/00-report-prereqs.t', 't/Config.t', 't/Document.t', 't/ExportInspector/SubExporter.t', 't/ExportInspector/load.t', 't/Sandbox.t', 't/after.t', 't/annotations.t', 't/args-in-import.t', 't/builtin.t', 't/carp.t', 't/cast-in-regex.t', 't/cast.t', 't/cli-args.t', 't/cli.t', 't/config-in-import.t', 't/constants.t', 't/cpan-modules/pithub.t', 't/cpan-modules/test2-v0.t', 't/datetime.t', 't/do-block.t', 't/doc-imports.t', 't/double-quoted-q.t', 't/dump-perl-exports.t', 't/dupes.t', 't/english-program-name.t', 't/english.t', 't/env.t', 't/explodes.t', 't/export-tags.t', 't/exported-variables.t', 't/find-bin.t', 't/fully-qualified.t', 't/func-in-use.t', 't/func-in-var.t', 't/function-reference.t', 't/geo-ip.t', 't/hash-in-regex.t', 't/hash-key-expression.t', 't/hash-key.t', 't/hash-unquoted-key.t', 't/heredoc.t', 't/ignored-modules.t', 't/import-error.t', 't/indent.t', 't/indirect-object-syntax.t', 't/interpolation.t', 't/is-ignored.t', 't/lib/TestHelper.pm', 't/local-lib.t', 't/locally-defined-sub.t', 't/lookalike-words.t', 't/maybe-new-include.t', 't/memoize.t', 't/meta.t', 't/method.t', 't/missing-semicolon-in-import.t', 't/module-with-inner-packages.t', 't/moo.t', 't/moose-type-library-with-meta.t', 't/moose-types.t', 't/moose.t', 't/moosex-types-moose.t', 't/nested-quotes.t', 't/never-exports.t', 't/original-imports.t', 't/pad-brackets.t', 't/padding.t', 't/perl-imports.t', 't/perl.t', 't/perlimports.t', 't/pragma.t', 't/preserve-include-comments.t', 't/preserve-some-padding.t', 't/preserve-spaces.t', 't/qualified-bareword.t', 't/quoted-var.t', 't/re-export-via-sub-exporter.t', 't/regex-replacement.t', 't/require.t', 't/same-symbol-different-modules.t', 't/script-with-inner-packages.t', 't/signatures.t', 't/skip-all.t', 't/socket.t', 't/sort-imports.t', 't/sort-includes.t', 't/sorter.t', 't/switches-in-import.t', 't/symbol-as-method-call.t', 't/symbol-in-export.t', 't/test-builder.t', 't/tie.t', 't/typeglob.t', 't/unnest-quotes.t', 't/use-and-require.t', 't/var-in-hash-key.t', 't/var-in-regex.t', 't/variable.t', 't/via-sub-exporter-exception.pl', 't/warning.t', 't/with-version.t' ); eol_unix_ok($_, { trailing_whitespace => 1 }) foreach @files; done_testing; CONTRIBUTING.md100644001750001751 67715261510577 16407 0ustar00olafolaf000000000000App-perlimports-0.000067CONTRIBUTING * [Git Hooks](#git-hooks) * [Sending Pull Requests](#sending-pull-requests) # Git Hooks A pre-commit hook that runs `precious lint --staged` is provided. To install it: ``` bash git/setup.sh ``` # Sending Pull Requests If you're proposing an invasive change, please get in touch first by opening a GitHub issue so we can co-ordinate before significant work is invested. annotations.t100755001750001751 452015261510577 17155 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!perl use strict; use warnings; use lib 't/lib'; use App::perlimports::Annotations (); use PPI::Document (); use TestHelper qw( doc ); use Test::More import => [qw( done_testing is ok subtest )]; subtest 'mixed' => sub { my $doc = PPI::Document->new( 'test-data/annotation.pl', readonly => 1, ); die 'could not parse' unless $doc; my $anno = App::perlimports::Annotations->new( ppi_document => $doc ); my $includes = $doc->find('PPI::Statement::Include'); is( $includes->[0]->module, 'strict', 'strict' ); ok( !$anno->is_ignored( $includes->[0] ), 'pragma not ignored' ); is( $includes->[1]->module, 'warnings', 'warnings' ); ok( !$anno->is_ignored( $includes->[1] ), 'pragma not ignored' ); is( $includes->[2]->module, 'Carp', 'Carp' ); ok( $anno->is_ignored( $includes->[2] ), 'Carp is ignored' ); is( $includes->[3]->module, 'POSIX', 'POSIX' ); ok( !$anno->is_ignored( $includes->[3] ), 'POSIX is not ignored' ); is( $includes->[4]->module, 'Cwd', 'Cwd' ); ok( $anno->is_ignored( $includes->[4] ), 'Cwd is ignored' ); is( $includes->[5]->module, 'Digest', 'Digest' ); ok( $anno->is_ignored( $includes->[5] ), 'Digest is ignored' ); is( $includes->[6]->module, 'Encode', 'Encode' ); ok( !$anno->is_ignored( $includes->[6] ), 'Encode is not ignored' ); }; subtest 'all' => sub { my $doc = PPI::Document->new( 'test-data/annotate-everything.pl', readonly => 1, ); die 'could not parse' unless $doc; my $anno = App::perlimports::Annotations->new( ppi_document => $doc ); my $includes = $doc->find('PPI::Statement::Include'); for my $include ( @{$includes} ) { ok( $anno->is_ignored($include), "$include ignored" ); } }; subtest 'via Document.pm' => sub { my ($doc) = doc( filename => 'test-data/annotation.pl', preserve_unused => 0, ); my $expected = <<'EOF'; use strict; use warnings; use Carp; ## no perlimports use POSIX qw( sprintf ); ## no perlimports use Cwd; use Digest; ## use perlimports use Encode qw( decode encode ); use FindBin; # Reasons ## no perlimports print decode( 'utf8', sprintf( 'hey %s', encode( 'utf8', 'Sofia Margareta Götschenhjelm-Helin' ) ) ); EOF is( $doc->tidied_document, $expected, 'tidied_document' ); }; done_testing(); doc-imports.t100644001750001751 523615261510577 17062 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!perl use strict; use warnings; use lib 'test-data/lib', 't/lib'; use App::perlimports::Document (); use TestHelper qw( logger ); use Test::More import => [qw( done_testing is is_deeply subtest )]; subtest 'linting tracks found_imports like tidying' => sub { my @log; my $doc = App::perlimports::Document->new( lint => 1, filename => 'test-data/doc-imports.pl', logger => logger( \@log ), ); # expected original and cleaned values my $original_imports = { Carp => [ 'confess', 'croak' ] }; my $clean_imports = { Carp => ['croak'] }; is_deeply $doc->found_imports, $original_imports, 'found_imports before linting as expected'; my $result = $doc->linter_success; is $result, q{}, 'linting failure'; my $found = grep { $_->{message} =~ /import arguments need tidying/ } @log; is $found, 2, 'log indicates Carp imports need fixing'; # Lint never modifies the document, but it tracks what each include will # import once tidied, so that later includes are checked against that. is_deeply $doc->found_imports, $clean_imports, 'doc found_imports reflect the tidied imports in lint mode'; }; subtest 'found_imports edited' => sub { my @log; my $doc = App::perlimports::Document->new( lint => 0, filename => 'test-data/doc-imports.pl', logger => logger( \@log ), ); # expected original and cleaned values my $original_imports = { Carp => [ 'confess', 'croak' ] }; my $clean_imports = { Carp => ['croak'] }; is_deeply $doc->found_imports, $original_imports, 'found_imports before editing as expected'; my $clean_source = $doc->tidied_document; my $found = grep { $_->{message} =~ /resetting imports for .use Carp/ } @log; is $found, 2, 'log indicates Carp import was fixed'; is_deeply $doc->found_imports, $clean_imports, 'doc found_imports changed in edit mode'; # preserve_duplicates defaulted to 1, so we now have two # identical use statements! # diag $clean_source; # ----------- @log = (); my $ppi_doc = PPI::Document->new( \$clean_source ); my $cdoc = App::perlimports::Document->new( lint => 1, logger => logger( \@log ), filename => 'none', ppi_document => $ppi_doc, ); is_deeply $cdoc->found_imports, $clean_imports, 'verified doc imports (with duplicate use statements)'; is $cdoc->linter_success, 1, 'lint succeeds'; is_deeply $cdoc->found_imports, $clean_imports, 'linting an already tidy doc leaves found_imports unchanged'; }; done_testing(); export-tags.t100644001750001751 117015261510577 17070 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use lib 't/lib'; use TestHelper qw( doc ); use Test::Differences qw( eq_or_diff ); use Test::More import => [qw( done_testing )]; use Test::Needs { 'HTTP::Status' => 6.28 }; my ($doc) = doc( filename => 'test-data/export-tags.pl' ); my $expected = <<'EOF'; use strict; use warnings; use HTTP::Status qw( HTTP_I_AM_A_TEAPOT HTTP_NO_CODE HTTP_REQUEST_ENTITY_TOO_LARGE ); my $pot = HTTP_I_AM_A_TEAPOT; my $big = HTTP_REQUEST_ENTITY_TOO_LARGE; my $what = HTTP_NO_CODE; EOF eq_or_diff( $doc->tidied_document, $expected, 'export tags converted to symbols' ); done_testing(); func-in-use.t100644001750001751 155215261510577 16750 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!/usr/bin/env perl use strict; use warnings; use lib 't/lib'; use TestHelper qw( doc source2pi ); use Test::More import => [qw( done_testing is subtest )]; use Test::Needs; subtest 'catdir' => sub { test_needs { 'File::Spec::Functions' => '3.75' }; my $source_text = 'use File::Spec::Functions;'; my $e = source2pi( 'test-data/func-in-use.pl', $source_text ); is( $e->formatted_ppi_statement, 'use File::Spec::Functions qw( catdir );', 'func in use statement is detected' ); }; subtest 'Mojo::File' => sub { test_needs { Mojolicious => '8.25' }; my ($doc) = doc( filename => 'test-data/func-in-use-2.pl', selection => 'use Mojo::File;', ); is( $doc->tidied_document, 'use Mojo::File qw( curfile );', 'func in use is recognized' ); }; done_testing(); func-in-var.t100755001750001751 57315261510577 16731 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use lib 't/lib'; use TestHelper qw( doc ); use Test::More import => [qw( done_testing is )]; use Test::Needs qw( Mojo::Util ); my ($doc) = doc( filename => 'test-data/func-in-var.pl', selection => 'use Mojo::Util;', ); is( $doc->tidied_document, 'use Mojo::Util qw( class_to_path );', 'func in hash key found' ); done_testing; moose-types.t100755001750001751 112415261510577 17101 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!/usr/bin/env perl use strict; use warnings; use lib 't/lib', 'test-data/lib'; use TestHelper qw( source2pi ); use Test::More import => [qw( done_testing is )]; use Test::Needs qw( MooseX::Types::Path::Class ); my $e = source2pi( 'test-data/messy-imports.pl', 'use Local::MooseTypeLibrary;', ); my $expected = <<'EOF'; use Local::MooseTypeLibrary qw( ArrayRef Bool CodeRef FileHandle HashRef Maybe Object RegexpRef Str ); EOF chomp $expected; is( $e->formatted_ppi_statement, $expected, 'formatted_ppi_statement' ); done_testing(); perlimports.t100755001750001751 650015261510577 17200 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!/usr/bin/env perl use strict; use warnings; use Path::Tiny (); use Test::Differences qw( eq_or_diff ); use Test::More import => [qw( done_testing subtest )]; use Test::Needs qw( Moose ); use Test::Script 1.27 qw( script_compiles script_fails script_runs script_stderr_is script_stderr_like script_stdout_like ); use TOML::Tiny qw( from_toml ); my $script = 'script/perlimports'; my @filename = ( '--filename', 'test-data/carp.pl' ); script_compiles($script); sub tmp_perl_file { my $file = Path::Tiny->tempfile('testXXXX'); $file->spew('use strict;use warnings;'); return $file; } subtest 'provide config file' => sub { my $file = tmp_perl_file(); script_runs( [ $script, '--config-file', 'test-data/perlimports.toml', "$file" ] ); script_stderr_is( q{}, 'no errors' ); }; subtest 'config file not found' => sub { my $file = tmp_perl_file(); script_fails( [ $script, '--config-file', 'test-data/Xperlimports.toml', "$file" ], { exit => 1 } ); script_stderr_like( qr{Xperlimports.toml not found}, 'not found error' ); }; subtest 'create config file' => sub { my $dir = Path::Tiny->tempdir('testconfigXXXXXXXX'); my $file = $dir->child('perlimports.toml'); script_runs( [ $script, '--create-config-file', "$file" ] ); script_stderr_is( q{}, 'no errors' ); my $config = from_toml( $file->slurp ); eq_or_diff( $config->{libs}, [ 'lib', 't/lib' ], 'default libs' ); script_fails( [ $script, '--create-config-file', "$file" ], { exit => 1 }, ); script_stderr_like( qr{already exists}, 'error clobbering file' ); }; subtest 'filename' => sub { script_runs( [ $script, @filename ] ); script_stderr_is( q{}, 'no errors' ); }; subtest 'implied --filename' => sub { script_runs( [ $script, 'test-data/carp.pl' ] ); script_stderr_is( q{}, 'no errors' ); }; subtest 'help' => sub { script_runs( [ $script, '--help' ] ); script_stderr_is( q{}, 'no errors' ); }; subtest 'libs' => sub { script_runs( [ $script, '--libs', 'test-data/lib', '--filename', 'test-data/lib/Local/ViaExporter.pm', ] ); script_stderr_is( q{}, 'no errors' ); }; subtest 'log level' => sub { script_runs( [ $script, @filename, '--log-level', 'info', ] ); script_stderr_like( qr{Starting file: test-data/carp.pl}, 'no errors' ); }; subtest 'help' => sub { script_runs( [ $script, '--help' ] ); script_stderr_is( q{}, 'no errors' ); }; subtest 'tidy_whitespace' => sub { script_runs( [ $script, '--no-config-file', '--no-tidy-whitespace', 'test-data/preserve-spaces.pl' ] ); script_stderr_is( q{}, 'no errors' ); script_stdout_like( qr{use Carp \(\);}, 'whitespace preserved' ); }; subtest 'verbose help' => sub { script_runs( [ $script, '--verbose-help' ] ); script_stderr_is( q{}, 'no errors' ); }; subtest 'version' => sub { script_runs( [ $script, '--version' ] ); script_stderr_is( q{}, 'no errors' ); }; subtest 'Not Found' => sub { script_fails( [ $script, '--filename', 'x', ], { exit => 1 } ); script_stderr_like( qr{x does not appear to be a file}, 'error when module not found' ); }; done_testing(); foo.t100644001750001751 10115261510577 16772 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Test::More; ok(1); done_testing; perlimports.toml100644001750001751 220015261510577 17433 0ustar00olafolaf000000000000App-perlimports-0.000067# Valid log levels are: # debug, info, notice, warning, error, critical, alert, emergency # critical, alert and emergency are not currently used. # # Please use boolean values in this config file. Negated options (--no-*) are # not permitted here. Explicitly set options to true or false. # # Some of these values deviate from the regular perlimports defaults. In # particular, you're encouraged to leave preserve_duplicates and # preserve_unused disabled. cache = false # setting this to true is currently discouraged ignore_modules = [] ignore_modules_filename = "" ignore_modules_pattern = "" # regex like "^(Foo|Foo::Bar)" ignore_modules_pattern_filename = "" # indent = 4 # default: perltidy -i libs = ["lib", "t/lib"] log_level = "warn" never_export_modules = [] never_export_modules_filename = "" pad_brackets = false padding = true preserve_duplicates = false preserve_unused = false tidy_whitespace = true import-error.t100755001750001751 102315261510577 17254 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!/usr/bin/env perl use strict; use warnings; use lib 't/lib'; use TestHelper qw( doc ); use Test::More import => [qw( done_testing ok )]; my $source_text = 'use Local::Module::Does::Not::Exist::At::All;'; my ( $doc, $log ) = doc( filename => 'test-data/geo-ip.pl', selection => $source_text, ); $doc->tidied_document; my $found = grep { $_->{level} eq 'warning' && $_->{message} =~ qr{Can't locate Local/Module} } @{$log}; ok( $found, 'exception on module not found' ); done_testing(); pad-brackets.t100644001750001751 357015261510577 17161 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!/usr/bin/env perl use strict; use warnings; use lib 't/lib'; use TestHelper qw( doc source2pi ); use Test::More import => [qw( done_testing is subtest )]; subtest 'default (tight brackets)' => sub { my $e = source2pi( 'test-data/foo.t', 'use Test::More;', ); is( $e->formatted_ppi_statement, 'use Test::More import => [qw( done_testing ok )];', 'default uses tight brackets' ); }; subtest 'no padding' => sub { my ($doc) = doc( filename => 'test-data/foo.t', pad_brackets => 0, ); is( $doc->tidied_document, <<'EOF', 'pad_brackets=0 produces tight brackets' ); use strict; use warnings; use Test::More import => [qw( done_testing ok )]; ok(1); done_testing; EOF }; subtest 'padded brackets explicitly' => sub { my ($doc) = doc( filename => 'test-data/foo.t', pad_brackets => 1, ); is( $doc->tidied_document, <<'EOF', 'pad_brackets=1 produces padded brackets' ); use strict; use warnings; use Test::More import => [ qw( done_testing ok ) ]; ok(1); done_testing; EOF }; subtest 'path 1 tight brackets (test builder with args)' => sub { my $e = source2pi( 'test-data/foo.t', 'use Test::More import => [qw( ok )];', { pad_brackets => 0 }, ); is( $e->formatted_ppi_statement, 'use Test::More import => [qw( done_testing ok )];', 'path 1 with pad_brackets=0 produces tight brackets' ); }; subtest 'path 1 padded brackets (test builder with args)' => sub { my $e = source2pi( 'test-data/foo.t', 'use Test::More import => [qw( ok )];', { pad_brackets => 1 }, ); is( $e->formatted_ppi_statement, 'use Test::More import => [ qw( done_testing ok ) ];', 'path 1 with pad_brackets=1 produces padded brackets' ); }; done_testing(); perl-imports.t100755001750001751 437015261510577 17260 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!/usr/bin/env perl use strict; use warnings; use lib 't/lib', 'test-data/lib'; use TestHelper qw( doc source2pi ); use Test::More import => [qw( done_testing is is_deeply ok subtest )]; subtest 'Getopt::Long' => sub { my $e = source2pi( 'test-data/foo.pl', 'use Getopt::Long;', ); is( $e->module_name(), 'Getopt::Long', 'module_name' ); ok( $e->_has_explicit_exports, 'Found some _explicit_exports' ); ok( !$e->_isa_test_builder_module, 'isa_test_builder_module' ); is_deeply( $e->_imports, ['GetOptions'], '_imports' ); is( $e->formatted_ppi_statement, 'use Getopt::Long qw( GetOptions );', 'formatted_ppi_statement' ); }; subtest 'Test::More' => sub { my $e = source2pi( 'test-data/foo.t', 'use Test::More;', ); is( $e->module_name(), 'Test::More', 'module_name' ); ok( $e->_has_explicit_exports, 'Found some _explicit_exports' ); ok( $e->_isa_test_builder_module, 'isa_test_builder_module' ); is_deeply( $e->_imports, [qw( done_testing ok)], '_imports' ); is( $e->formatted_ppi_statement, 'use Test::More import => [qw( done_testing ok )];', 'formatted_ppi_statement' ); }; subtest 'pragma' => sub { my ($doc) = doc( filename => 'test-data/foo.t', selection => 'use strict;', ); is( $doc->tidied_document, 'use strict;', 'formatted_ppi_statement' ); }; subtest 'ViaExporter' => sub { my $e = source2pi( 'test-data/via-exporter.pl', 'use Local::ViaExporter qw( foo $foo @foo %foo );', ); is( $e->module_name(), 'Local::ViaExporter', 'module_name' ); is_deeply( $e->_explicit_exports, { '$foo' => '$foo', '%foo' => '%foo', '@foo' => '@foo', 'foo' => 'foo', }, 'Found some _explicit_exports' ); ok( !$e->_isa_test_builder_module, 'isa_test_builder_module' ); is_deeply( $e->_imports, [qw( foo $foo @foo %foo )], '_imports' ); is( $e->formatted_ppi_statement, 'use Local::ViaExporter qw( foo $foo @foo %foo );', 'formatted_ppi_statement' ); }; done_testing(); sort-imports.t100644001750001751 103315261510577 17273 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!perl use strict; use warnings; use lib 't/lib', 'test-data/lib'; use Test::Differences qw( eq_or_diff ); use TestHelper qw( doc ); use Test::More import => [qw( done_testing )]; my ($doc) = doc( filename => 'test-data/sort.pl' ); my $expected = <<'EOF'; use strict; use warnings; use Local::Sort qw( $AAA $AAA_2FA bbb @BBB %CCC ); bbb(); bbb_2fa(); if ( defined $AAA || defined $AAA_2FA || scalar @BBB || keys %CCC ) { print 'defined'; } EOF eq_or_diff( $doc->tidied_document, $expected, 'sorted' ); done_testing(); test-builder.t100644001750001751 42615261510577 17201 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use lib 't/lib'; use TestHelper qw( inspector ); use Test::Needs qw( Test::HTML::Lint ); use Test::More import => [qw( done_testing ok )]; my ($ei) = inspector('Test::HTML::Lint'); ok( $ei->isa_test_builder, 'isa_test_builder' ); done_testing(); var-in-regex.t100644001750001751 66615261510577 17110 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use lib 't/lib'; use Test::More import => [qw( done_testing is )]; use TestHelper qw( source2pi ); use Test::Needs qw( Perl::Critic::Utils ); my $source_text = 'use Perl::Critic::Utils qw( $BACKTICK $PERIOD );'; my $include = source2pi( 'test-data/var-in-regex.pl', $source_text ); is( $include->formatted_ppi_statement, $source_text, 'exported var in regex is detected' ); done_testing(); with-version.t100644001750001751 166015261510577 17255 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use lib 't/lib'; use Test::Differences qw( eq_or_diff ); use TestHelper qw( doc ); use Test::More import => [qw( diag done_testing )]; use Test::Needs { 'Cpanel::JSON::XS' => 4.19, 'Getopt::Long' => 2.40, 'LWP::UserAgent' => 5.00, }; my ( $doc, $log ) = doc( filename => 'test-data/with-version.pl' ); my $expected = <<'EOF'; use strict; use warnings; use Cpanel::JSON::XS 4.19 qw( decode_json ); use Getopt::Long 2.40 qw( GetOptions ); use LWP::UserAgent 5.00 (); use Test::Script 1.27 qw( script_compiles script_runs script_stderr_is script_stderr_like ); my $foo = decode_json( { foo => 'bar' } ); my @foo = GetOptions(); script_compiles(); script_runs(); script_stderr_is(); script_stderr_like(); EOF eq_or_diff( $doc->tidied_document, $expected, 'versions preserved' ) || do { require Data::Dumper; diag Data::Dumper::Dumper($log); }; done_testing(); env.pl100644001750001751 10315261510577 17151 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Env qw( @PATH ); my @copy = @PATH; foo.pl100755001750001751 13315261510577 17152 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data#!/usr/bin/env perl use strict; use warnings; use Getopt::Long; my @foo = GetOptions(); meta.t100644001750001751 11515261510577 17142 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Test2::V0 qw( !meta ); ok(1); done_testing; noop.t100644001750001751 17115261510577 17171 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Test::More; use Test::RequiresInternet ( 'www.example.com' => 80 ); ok(1); done_testing; tie.pl100644001750001751 13615261510577 17150 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Tie::SubstrHash (); tie my %hash, 'Tie::SubstrHash', 1, 1, 1; cast-in-regex.t100644001750001751 114315261510577 17261 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use lib 't/lib'; use Test::Differences qw( eq_or_diff ); use TestHelper qw( doc ); use Test::More import => [qw( done_testing is_deeply )]; use Test::Needs qw( Lingua::EN::Inflect ); my ($doc) = doc( filename => 'test-data/cast-in-regex.pl', preserve_unused => 0, ); is_deeply( $doc->interpolated_symbols, {}, 'vars' ); my $expected = <<'END'; use strict; use warnings; my $thing = 'B'; if ( $thing =~ m{ \A b }x ) { ... } END eq_or_diff( $doc->tidied_document, $expected, 'Did not mistake \A for A() provided by Lingua::EN::Inflect' ); done_testing(); hash-in-regex.t100644001750001751 73615261510577 17241 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use lib 't/lib'; use TestHelper qw( doc ); use Test::More import => [qw( done_testing is $TODO )]; my ($doc) = doc( filename => 'test-data/hash-in-regex.pl' ); my $expected = <<'EOF'; use strict; use warnings; use Config qw( $Config ); sub foo { return $INC{'Foo.pm'} =~ /^\Q$Config{sitelibexp}/; } EOF TODO: { local $TODO = 'Cannot find hash var in regex yet'; is( $doc->tidied_document, $expected, 'var found' ); } done_testing(); interpolation.t100644001750001751 51615261510577 17465 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use lib 't/lib'; use Test::Differences qw( eq_or_diff ); use TestHelper qw( doc ); use Test::More import => [qw( done_testing )]; my ($doc) = doc( filename => 'test-data/interpolation.pl' ); eq_or_diff( $doc->interpolated_symbols, { '$code' => 1, encode => 1 }, 'vars' ); done_testing(); nested-quotes.t100644001750001751 114415261510577 17414 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use lib 't/lib'; use Test::Differences qw( eq_or_diff ); use TestHelper qw( doc ); use Test::More import => [qw( done_testing is_deeply )]; my ($doc) = doc( filename => 'test-data/nested-quotes.pl' ); is_deeply( $doc->interpolated_symbols, { path => 1, '$thing' => 1, }, 'vars' ); my $expected = <<'EOF'; use strict; use warnings; use Path::Tiny qw( path ); my $thing = qq{content="${ \( path('one/two.txt')->stringify )}"}; print "$thing\n"; EOF eq_or_diff( $doc->tidied_document, $expected, 'function call in nested quotes detected' ); done_testing(); never-exports.t100755001750001751 337615261510577 17451 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!/usr/bin/env perl use strict; use warnings; use lib 't/lib'; use TestHelper qw( source2pi ); use Test::More import => [qw( is is_deeply ok subtest )]; use Test::Warnings; use Test::Needs { 'Cpanel::JSON::XS' => 4.19, 'Getopt::Long' => 2.40, 'LWP::UserAgent' => 5.00, 'Test::Script' => 1.27, }; subtest 'with version' => sub { my $pi = source2pi( 'test-data/with-version.pl', 'use LWP::UserAgent 5.00;', ); ok( !$pi->_is_ignored, '_is_ignored' ); is( $pi->formatted_ppi_statement, 'use LWP::UserAgent 5.00 ();', 'formatted_ppi_statement' ); ok( !$pi->_has_export_inspector, 'export inspection bypassed' ); is_deeply( $pi->_imports, [], '_imports' ); is_deeply( $pi->_explicit_exports, {}, 'no _explicit_exports' ); }; subtest 'without version' => sub { my $pi = source2pi( 'test-data/with-version.pl', 'use LWP::UserAgent;', ); ok( !$pi->_is_ignored, '_is_ignored' ); is( $pi->formatted_ppi_statement, 'use LWP::UserAgent ();', 'formatted_ppi_statement' ); ok( !$pi->_has_export_inspector, 'export inspection bypassed' ); is_deeply( $pi->_imports, [], '_imports' ); }; subtest 'without incorrect import' => sub { my $pi = source2pi( 'test-data/with-version.pl', 'use LWP::UserAgent qw( new );', ); ok( !$pi->_is_ignored, '_is_ignored' ); is( $pi->formatted_ppi_statement, 'use LWP::UserAgent ();', 'formatted_ppi_statement' ); ok( !$pi->_has_export_inspector, 'export inspection bypassed' ); is_deeply( $pi->_imports, [], '_imports' ); is_deeply( $pi->_explicit_exports, {}, 'no _explicit_exports' ); }; done_testing(); sort-includes.t100644001750001751 1361215261510577 17432 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!perl use strict; use warnings; use lib 't/lib', 'test-data/lib'; use Cpanel::JSON::XS qw( decode_json ); use Test::Differences qw( eq_or_diff ); use TestHelper qw( doc ); use Test::More import => [qw( done_testing is like ok )]; my @ignore = ( 'Foo', 'Bar', 'Baz' ); # sort => 0 leaves ordering untouched. { my ($document) = doc( filename => 'test-data/sort-includes.pl', ignore_modules => \@ignore, ); my $expected = <<'EOF'; use strict; use Foo; use Bar; use Baz; 1; EOF eq_or_diff( $document->tidied_document, $expected, 'sort off: unchanged' ); } # sort => 1 hoists the pragma, injects a blank line, sorts the modules. { my ($document) = doc( filename => 'test-data/sort-includes.pl', ignore_modules => \@ignore, sort => 1, ); my $expected = <<'EOF'; use strict; use Bar; use Baz; use Foo; 1; EOF eq_or_diff( $document->tidied_document, $expected, 'sort on: sorted' ); } # Lint mode: unsorted includes fail (linter_success is false). { my ($document) = doc( filename => 'test-data/sort-includes.pl', ignore_modules => \@ignore, sort => 1, lint => 1, ); ok( !$document->linter_success, 'lint fails on unsorted includes' ); } # Lint mode: already-sorted includes pass. { my ($document) = doc( filename => 'test-data/sort-includes.pl', ignore_modules => \@ignore, sort => 0, lint => 1, ); ok( $document->linter_success, 'lint passes when sort is disabled' ); } # Lint mode: already-sorted includes pass with sort enabled. { my ($document) = doc( filename => 'test-data/sort-includes-sorted.pl', ignore_modules => \@ignore, sort => 1, lint => 1, ); ok( $document->linter_success, 'lint passes on already-sorted includes with sort enabled' ); } # Multiple blank-separated sections are each sorted independently, and the # blank line between sections is preserved. { my ($document) = doc( filename => 'test-data/sort-includes-multi.pl', ignore_modules => [qw( Foo Bar Zoo Apple )], sort => 1, ); my $expected = <<'EOF'; use strict; use Bar; use Foo; use Apple; use Zoo; 1; EOF eq_or_diff( $document->tidied_document, $expected, 'multiple sections each sorted independently' ); } # Leading and trailing comments travel with their imports through the tidy # path: the leading "# uses Foo" and the trailing "# foo trailing" both stay # attached to Foo when it sorts below Bar. { my ($document) = doc( filename => 'test-data/sort-includes-comments.pl', ignore_modules => [qw( Foo Bar )], sort => 1, ); my $expected = <<'EOF'; use Bar; # uses Foo use Foo; # foo trailing 1; EOF eq_or_diff( $document->tidied_document, $expected, 'leading and trailing comments travel with their import' ); } # Sorting is idempotent through the Document tidy path: running --sort on # already-sorted output yields byte-identical output. { my ($document) = doc( filename => 'test-data/sort-includes-sorted.pl', ignore_modules => [qw( Foo Bar Baz )], sort => 1, ); my $expected = <<'EOF'; use strict; use Bar; use Baz; use Foo; 1; EOF eq_or_diff( $document->tidied_document, $expected, 'already-sorted input is unchanged through tidy (idempotent)' ); } # Lint mode with --json reports the unsorted includes as a JSON diagnostic # instead of a unified diff. { my ( $document, $log ) = doc( filename => 'test-data/sort-includes.pl', ignore_modules => \@ignore, sort => 1, lint => 1, json => 1, ); ok( !$document->linter_success, 'json lint fails on unsorted includes' ); my ($error) = grep { $_->{level} eq 'error' } @{$log}; my $payload = decode_json( $error->{message} ); is( $payload->{reason}, 'includes are not sorted', 'json diagnostic carries the unsorted reason' ); is( $payload->{filename}, 'test-data/sort-includes.pl', 'json diagnostic carries the filename' ); # The location spans the lines that actually changed. The `use strict` # pragma on line 1 is hoisted but stays put, so the span starts at the # first reordered include (line 2) and ends at the last (line 4). There # is no single module for a reordering. eq_or_diff( $payload->{location}, { start => { line => 2, column => 1 }, end => { line => 4, column => 8 }, }, 'json diagnostic carries the location spanning the changed includes' ); ok( !exists $payload->{module}, 'json diagnostic omits module for a document-wide sort' ); ok( length $payload->{diff}, 'json diagnostic carries a non-empty diff' ); like( $payload->{diff}, qr{^\@\@}m, 'diff is in unified format' ); } # A reordering of the top-of-file block must not report a location that # reaches down to a `require` buried in a sub far below, which never # participates in the sort. { my ( $document, $log ) = doc( filename => 'test-data/sort-includes-noncontiguous.pl', sort => 1, lint => 1, json => 1, ); ok( !$document->linter_success, 'json lint fails on unsorted includes' ); my ($error) = grep { $_->{level} eq 'error' } @{$log}; my $payload = decode_json( $error->{message} ); eq_or_diff( $payload->{location}, { start => { line => 2, column => 1 }, end => { line => 3, column => 8 }, }, 'location covers only the reordered top block, not the distant require' ); } done_testing(); unnest-quotes.t100644001750001751 55615261510577 17434 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!perl use strict; use warnings; use lib 't/lib'; use List::Util qw( none ); use TestHelper qw( doc ); use Test::More import => [qw( done_testing ok )]; my ( $doc, $logs ) = doc( filename => 'test-data/unnest-quotes.pl', ); $doc->tidied_document; ok( do { none { $_->{level} eq 'error' } @$logs; }, 'no errors in logs' ); done_testing; carp.pl100644001750001751 11015261510577 17304 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Carp qw( croak verbose ); croak('oof'); cast.pl100644001750001751 13615261510577 17321 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Mojo::Util; my @pairs = map {@$_} @{split_header $str // ''}; sort.pl100644001750001751 30715261510577 17356 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Local::Sort qw( $AAA_2FA bbb bba_2fa $AAA @BBB %CCC ); bbb(); bbb_2fa(); if ( defined $AAA || defined $AAA_2FA || scalar @BBB || keys %CCC ) { print 'defined'; } script000755001750001751 015261510577 15330 5ustar00olafolaf000000000000App-perlimports-0.000067perlimports100755001750001751 6273715261510577 20035 0ustar00olafolaf000000000000App-perlimports-0.000067/script#!perl use strict; use warnings; use App::perlimports::CLI (); use Try::Tiny qw( catch try ); my $exit_code = 0; try { $exit_code = App::perlimports::CLI->new->run; } catch { print STDERR $_; $exit_code = 1; }; exit($exit_code); # PODNAME: perlimports # ABSTRACT: A command line utility for cleaning up imports in your Perl code __END__ =pod =encoding UTF-8 =head1 NAME perlimports - A command line utility for cleaning up imports in your Perl code =head1 VERSION version 0.000067 =head1 SYNOPSIS Create a config file called C at the top level of your application or repository: perlimports --create-config-file perlimports.toml You can also have a config file with a leading C<.>. perlimports --create-config-file .perlimports.toml For system-wide defaults, you can create a file in C<$XDG_HOME>. Something like: perlimports --create-config-file ~/.config/perlimports/perlimports.toml After you have set up the config file to your liking, you can do away with most command line switches, other than C<-i>, C<--lint> or C<--read-stdin>. Now, let's update a file in place. (Make sure you can revert the file if you need to, as C will not make a backup.) perlimports -i foo.pl Lint a file: perlimports --lint foo.pl In-place edits on directories: perlimports -i lib t xt Lint directories: perlimports --lint lib t xt In-place edits on files and directories perlimports -i foo.pl lib t xt Run C on a file and only print the results to STDOUT. perlimports foo.pl If some of your imported modules are in local directories, you can give some hints as to where to find them: perlimports -i --libs t/lib,/some/dir/lib foo.pl Redirect output to a new file: perlimports foo.pl > foo.new.pl =head1 DESCRIPTION This distribution provides the C command line interface (CLI), which automates the cleanup and maintenance of Perl C and C statements. Loosely inspired by L, this tool aims to be part of your linting and tidying workflow, in much the same way you might use L or L. For a detailed discussion of the problems this tool attempts to solve, see this "Conference in the Cloud" talk from June 2021: L. Slides for the above talk are also available: curl -O https://raw.githubusercontent.com/oalders/presentations/main/slides/6-perlimports/remark.html && open remark.html =head1 MOTIVATION Many Perl modules helpfully export functions and variables by default. These provide handy shortcuts when you're writing a quick or small script, but they can quickly become a maintenance burden as code grows organically. When code increases in complexity, it leads to greater costs in terms of development time. Conversely, reducing code complexity can speed up development. This tool aims to reduce complexity to further this goal. While importing symbols by default or using export tags provides a convenient shorthand for getting work done, this shorthand requires the developer to retain knowledge of these defaults and tags in order to understand the code. C aims to allow you to develop your code as you see fit, while still giving you a viable option of tidying your imports automatically. In much the same way as you might use L to format your code, you can now automate the process of making your imports easier to understand. Let's look at some examples. =over =item Where is this function defined? You may come across some code like this: use strict; use warnings; use HTTP::Request::Common; use LWP::UserAgent; my $ua = LWP::UserAgent->new; my $req = $ua->request( GET 'https://metacpan.org/' ); print $req->content; Where does C come from? If you're not familiar with L, you may not realize that the statement C has implicitly imported the functions C, C, C, C, C and C into to this block of code. What would happen if we used C to import all needed functions explicitly? It might look something like this: use strict; use warnings; use HTTP::Request::Common qw( GET ); use LWP::UserAgent (); my $ua = LWP::UserAgent->new; my $req = $ua->request( GET 'https://metacpan.org/' ); print $req->content; The code above makes it immediately obvious where C originates, which in turn makes it easier for us to look up its documentation. It has the added bonus of also not importing C, C or any of the other functions which L exports by default. So, those functions cannot unwittingly be used later in the code. This makes for more understandable code for present day you, future you and any others tasked with reading your code at some future point. Keep in mind that this simple act can save much time for developers who are not intimately familiar with Perl and the default exports of many CPAN modules. =item Are we even using all of these imports? Imagine the following import statement use HTTP::Status qw( is_cacheable_by_default is_client_error is_error is_info is_redirect is_server_error is_success status_message ); followed by 3,000 lines of code. How do you know if all of these functions are actually being used? Were they ever used? You can grep all of these function names manually or you can remove them by trial and error to see what breaks. This is a doable solution, but it does not scale well to scripts and modules with many imports or to large code bases with many imports. Having an unmaintained list of imports is preferable to implicit imports, but it would be helpful to automate maintaining this list. L can, in many situations, clean up your import statements and automate this maintenance burden away. This makes it easier for you to write clean code, which is easier to understand. =item Are we even using all of these modules? In cases where code is implicitly importing from modules or where explicit imports are not being curated, it can be hard to discover which modules are no longer being used in a script, module or even a code base. Removing unused modules from code can lead to gains in performance and decrease in consumption of resources. Removing entire modules from your code base can decrease the number of dependencies which you need to manage and decrease friction in your your deployment process. C can remove unused modules for you, making dependency management much easier. =item Enforcing a consistent style Having a messy list of module imports makes your code harder to read. Imagine this: use Cpanel::JSON::XS; use Database::Migrator::Types qw( HashRef ArrayRef Object Str Bool Maybe CodeRef FileHandle RegexpRef ); use List::AllUtils qw( uniq any ); use LWP::UserAgent q{}; use Try::Tiny qw/ catch try /; use WWW::Mechanize q<>; L turns the above list into: use Cpanel::JSON::XS (); use Database::Migrator::Types qw( ArrayRef Bool CodeRef FileHandle HashRef Maybe Object RegexpRef Str ); use List::AllUtils qw( any uniq ); use LWP::UserAgent (); use Try::Tiny qw( catch try); use WWW::Mechanize (); Where possible, L will enforce a consistent style of parentheses and will also sort your imports and break up long lines. As mentioned above, if some imports are no longer in use, C will helpfully remove these for you. =item Import tags Import tags may obscure where symbols are coming from. While import tags provide a useful shorthand, they can contribute to code complexity by obscuring the origin of imported symbols. Consider: use HTTP::Status qw(:constants :is status_message); The above line imports the C function as well *some other things* via C<:constants> and C<:is>. What exactly are these things? We'll need to read the documentation to know for sure. C can audit your code and expand the line above to list the symbols which you are actually importing. So, the line above might now look something like: use HTTP::Status qw( HTTP_ACCEPTED HTTP_BAD_REQUEST HTTP_CONTINUE HTTP_I_AM_A_TEAPOT HTTP_MOVED_PERMANENTLY HTTP_NO_CODE HTTP_NOT_FOUND HTTP_OK HTTP_PAYLOAD_TOO_LARGE HTTP_PERMANENT_REDIRECT HTTP_RANGE_NOT_SATISFIABLE HTTP_REQUEST_ENTITY_TOO_LARGE HTTP_REQUEST_RANGE_NOT_SATISFIABLE HTTP_REQUEST_URI_TOO_LARGE HTTP_TOO_EARLY HTTP_UNORDERED_COLLECTION HTTP_URI_TOO_LONG is_cacheable_by_default is_client_error is_error is_info is_redirect is_server_error is_success status_message ); This is more verbose, but grepping your code will now reveal to you where something like C gets defined. You have increased the lines of code, but you have also reduced complexity. =back =head1 COMMAND LINE PARAMETERS =head2 --create-config-file Expects a path to a C<.toml> file which does not yet exist. --create-config-file perlimports.toml --create-config-file .perlimports.toml For system-wide defaults, you can create a file in C<$XDG_HOME>. Something like: perlimports --create-config-file ~/.config/perlimports/perlimports.toml All of the above are default file locations which L will search, unless C<--config-file> has been provided as an argument. =head2 --config-file Path to a perlimports config file. If this parameter is not supplied, we will look for a file called C or C<.perlimports.toml> in the current directory and then look for a perlimports.toml in XDG_CONFIG_HOME (usually something like C<$HOME/perlimports/perlimports.toml>). This behaviour can be disabled via C<--no-config-file> as described below. =head2 --no-config-file Prevents L from automatically using a config file which is in one of the standard locations. Use this option if you want to define all of your behaviours on the command line. =head2 --filename|-f The absolute or relative path to a file (or directory) to process. --filename path/to/file -f path/to/file -f path/to/dir Note that if you do not provide a C<--filename> we will fall back to checking C<@ARGV> for any remaining args. So, perlimports --filename path/to/file is equivalent to perlimports path/to/file You may also pass multiple file and dir names. perlimports path/to/file path/to/other/file lib t xt =head2 --ignore-modules A comma-separated list of module names which should be ignored by this script. Any modules in this list should remain unchanged after processing. --ignore-modules Foo,Foo::Bar =head2 --ignore-modules-filename The absolute or relative path to a file which contains a lost of module names to ignore. (See above for behaviour). The pattern is one module name per line. Foo Foo::Bar =head2 --ignore-modules-pattern A regular expression to match module names which should be ignored by this script. Any modules matched by this regular expression remain unchanged after processing. --ignore-modules-pattern '^(Foo|Foo::Bar)' =head2 --ignore-modules-pattern-filename The absolute or relative path to a file which contains a list of regular expression that matches modules that should be ignored. (See above for behaviour). The pattern is one regular expression per line. ^Foo ^Foo::Bar =head2 --never-export-modules A comma-separated list of module names which should never export symbols. If these modules are found, we will ensure that they have an empty import list. So, C becomes C. --never-export-modules Foo,Foo::Bar =head2 --never-export-modules-filename The absolute or relative path to a file which contains a lost of module names which should never export symbols. (See above for behaviour). The pattern is one module name per line. Foo Foo::Bar =head2 --inplace-edit|-i Edit the file in place rather than printing the result to STDOUT. Make sure you have a backup copy first. --inplace--edit -i Edit the file in place rather than printing the result to STDOUT. Make sure you have a backup copy first. =head2 --json (Experimental). If enabled, linting errors will be emitted as JSON objects with one object per error. This is intended to make it easier for editors to parse line numbers and column numbers as well as the error message. This flag can only be used in tandem with C<--lint>. =head2 --lint If this argument is passed, C will act as a linter, rather than a tidier. Failure (and success) messages will be reported on STDERR. Failures will also return a non-zero exit code. This is still a bit experimental, so the output format and exit codes could change in a subsequent release. This cannot be combined with tidying. So, passing C<--lint --inplace-edit> will generate an error. =head2 --indent Sets the indent width in spaces for C import lists that are split across multiple lines. Defaults to the value of perltidy's C setting (read from C<.perltidyrc> if present), or 4 if unset. # --indent 2 use Foo qw( bar baz ); =head2 --[no-]pad-brackets When enabled, adds whitespace inside the square brackets of test builder import lists. Defaults to disabled. # --pad-brackets use Test::More import => [ qw( ok ) ]; # --no-pad-brackets use Test::More import => [qw( ok )]; =head2 --[no-]padding C<--padding> is enabled by default, so you only need to pass this arg if you want to be explicit. This setting adds whitespace inside the parentheses. # --padding use Foo qw( bar baz ); The C<--no-padding> arg allows you to disable the additional padding inside parentheses. # --no-padding use Foo qw(bar baz); =head2 --[no-]tidy-whitespace C<--tidy-whitespace> is enabled by default. This means that use statements will be updated even when the only change is in whitespace. Disabling this can help reduce the churn involved when running C, especially if the codebase does not have automated tidying. If you have changed from C<--padding> to C<--no-padding> or vice versa, you'll probably want to ensure that C<--tidy-whitespace> has also been enabled so that you can see the whitespace changes. =head2 --libs A comma separated list of module directories which are not in your C<@INC> --libs lib,t/lib =head2 --[no-]preserve-duplicates When enabled, only one use statement per module will be preserved. Defaults to preserving duplicate statements. For example, when enabled the following text use Foo qw( bar ); use Foo qw (baz ); will be converted to: use Foo qw( bar baz ); If left disabled, the above will probably be converted to: use Foo qw( bar baz ); use Foo qw( bar baz ); This allows you to determine manually how you'd like to handle the imports in question. Use this setting with care. =head2 --[no-]preserve-require When enabled (the default), C statements are left untouched. When disabled, a top-level C is translated to C. C is not equivalent to C: C loads the module at runtime, at the point where the statement appears, whereas C loads it at compile time. A C is frequently used deliberately (for example to defer loading, to load a module conditionally, or to break a circular dependency), so C preserves it by default. Disable this option if you'd prefer the old behaviour of rewriting requires as C. Note that requires which are already preserved regardless of this setting -- such as those inside a conditional or block, or C -- are unaffected. =head2 --[no-]preserve-unused When enabled, unused modules will be removed. Defaults to preserving unused modules. Enabling this may remove modules which are only present for the purposes of preloading or which aren't being detected for other reasons, so use this setting with care. =head2 --range-begin Experimental. First line of a range to tidy or lint. The line ranges begin at 1 (not 0). This will select the appropriate range of lines from C. Requires C<--read-stdin>. Mostly useful for editors. Unless you're writing an editor plugin or extension, you can probably ignore this. =head2 --range-end Experimental. Last line of a range to tidy or lint. The line ranges begin at 1 (not 0). This will select the appropriate range of lines from C. Requires C<--read-stdin>. Mostly useful for editors. Unless you're writing an editor plugin or extension, you can probably ignore this. =head2 --read-stdin Read statements to process from STDIN rather than processing the entire file. This is intended for use by editors, like C. See the L section below for more information on how to set up an integration with your editor. If this option is enabled, then C<--inplace-edit|-i> is not available. --read-stdin =head2 --[no-]sort (Experimental). Sort contiguous include statements into a deterministic order. Defaults to false. As this feature is still experimental, the exact sorting behaviour may change in a subsequent release. =head2 --log-level|-l Generally only useful for debugging. C notifies about progress, like which file or snippet is currently being processed. C will generally log the errors which were swallowed as text was being processed. All levels are subject to change. --log-level notice --log-level info -l notice -l info See L for a list of available log levels. Log output defaults to STDERR. See C<--log-filename> if you'd rather log to a file. =head2 --log-filename Name of a file to redirect logs to, rather than STDERR. =head2 --help Output a concise help menu, with a summary of available parameters. --help =head2 --verbose-help Include the SYNOPSIS section from this page after printing the C<--help> menu listed above. =head1 ANNOTATIONS/IGNORING MODULES Aside from the documented command line switches for ignoring modules, you can add annotations in your code. use Encode; ## no perlimports The above will tell L not to attempt a tidy of this line. ## no perlimports use Encode; use Cpanel::JSON::XS; ## use perlimports use POSIX (); The above will tell L not to tidy the two modules contained inside of the annotations. Please note that since L needs to know as much as possible about what's going on in a file, the annotations don't prevent modules from being loaded. It's only a directive to leave the lines in the file unchanged after processing. =head1 INTEGRATIONS You are encouraged to make this tool part of your automated tidying workflow. Some guidance on how to configure this follows. =head2 VIM If you're a C user, you can pipe your import statements to perlimports directly. :vnoremap im :!perlimports --read-stdin --filename '%:p' The above statement will allow you to visually select one or more lines of code and have them updated in place by C. Once you have selected the code enter C to have your imports (re)formatted. =head2 VIM and ALE If you use ALE with vim, you can add something like this to your C configuration. Note that this function will save your buffer before running C. function! Perlimports(buffer) abort write return { \ 'command': 'perlimports --read-stdin -f %s' \} endfunction let ale_fixers.perl = ['perlimports', 'perltidy'] execute ale#fix#registry#Add('perlimports', 'Perlimports', ['perl'], 'Tidy Perl imports') =head2 Emacs and Flycheck L 35 and newer will suggest changes from C automatically if it finds that it is installed. =head2 precious If you're a L user, your configuration might look something like this: exclude = [ # Used by Dist::Zilla ".build", "App-perlimports-*", "blib", "inc", "test-data", # All of these are generated by Dist::Zilla "t/00-*", "t/author-*", "t/release-*", "xt/author", "xt/release", ] [commands.perlimports] type = "both" include = [ "**/*.{pl,pm,t,psgi}" ] cmd = [ "perlimports" ] lint-flags = [ "--lint"] tidy-flags = [ "-i"] ok-exit-codes = 0 lint-failure-exit-codes = 1 expect-stderr = true [commands.perltidy] type = "both" include = [ "**/*.{pl,pm,t,psgi}" ] cmd = [ "perltidy", "--profile=$PRECIOUS_ROOT/perltidyrc" ] lint-flags = [ "--assert-tidy", "--no-standard-output", "--outfile=/dev/null" ] tidy-flags = [ "--backup-and-modify-in-place", "--backup-file-extension=/" ] ok-exit-codes = 0 lint-failure-exit-codes = 2 expect-stderr = true Note that L runs plugins in order, so we've placed a L config after L. This is handy because L could introduce changes which will later be reverted by L. By running them sequentially we can avoid false positives which might be generated by L changing an include which L might revert. For an up to date example, see the config file which this repository uses: L =head2 Code::TidyAll If you're a L user, you can configure C as a GenericTransformer. Your configuration might look something like this: [GenericTransformer perlimports] select = **/*.{pl,pm,t,psgi} ignore = .build/**/* ignore = App-perlimports-*/**/* ignore = blib/**/* ignore = fatlib/**/* ignore = inc/**/* ignore = t/00-* ignore = t/author-* ignore = t/release-* ignore = t/zzz-* ignore = test-data/**/* ignore = xt/**/* ignore = xt/author/{pod-coverage,pod-spell,tidyall}.t argv = --libs lib,t/lib --no-preserve-duplicates --no-preserve-unused --log-filename /tmp/perlimports.txt --log-level debug cmd = perlimports file_flag = -f ok_exit_codes = 0 weight = 1 Note that in this case we've set the lowest possible weight. This is because we want C to run before any other plugin which may transform the file. For example, you'll want L to run after C to avoid having to re-tidy files after your use statements have been rewritten. If you want to use C to run just C you'll need to do something like: tidyall --plugin "GenericTransformer perlimports" -a For an up to date example, see the config file which this repository uses: L =head1 RECIPES Included are some examples to use if you want to employ your own file finding logic or prefer not to use config files. If this does not apply to you, you can safely skip this section. Running perlimports on test files find t -type f | \ grep .t$ | \ xargs perlimports \ --libs lib,t/lib \ --ignore-modules Test::More \ --no-preserve-unused \ --no-preserve-duplicates \ --log-level debug \ -i The above command: =over =item * finds all test files in C<./t> =item * pipes them to C =item * adds C and C to C<@INC> =item * ignores the L module =item * removes unused modules =item * removes duplicated use statements =item * displays debugging info =item * edits files in place (C<-i>) =back Users of L can make this a touch simpler: ack -f --perltest \ xargs perlimports \ --libs lib,t/lib \ --ignore-modules Test::More \ --no-preserve-unused \ --no-preserve-duplicates \ --log-level debug \ -i Running perlimports on modules: find lib -type f | \ grep .pm$ | \ xargs perlimports \ --libs lib \ --no-preserve-unused \ --no-preserve-duplicates \ -i The above command: =over =item * finds all .pm files in C<./lib> =item * pipes them to C =item * adds C to C<@INC> =item * removes unused modules =item * removes duplicated use statements =item * edits files in place (C<-i>) =back We can also make this slightly shorter by using L: ack -f --perl lib \ xargs perlimports \ --libs lib \ --no-preserve-unused \ --no-preserve-duplicates \ -i =head1 CAVEATS There are lots of shenanigans that Perl modules can get up to. This code will not find exports for all of those cases, but it should only attempt to rewrite imports which it knows how to handle. Please file a bug report in all other cases. =head1 SEE ALSO L, L and L =head1 AUTHOR Olaf Alders =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2020 by Olaf Alders. 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 args-in-import.t100644001750001751 75315261510577 17451 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!perl use strict; use warnings; use lib 't/lib'; use TestHelper qw( doc ); use Test::More import => [qw( done_testing is_deeply )]; use Test::Needs qw( Test2::V0 ); my ($doc) = doc( filename => 'test-data/args-in-import.t', selection => q{use Test2::V0 '-no_pragmas' => 1, '!meta', 'diag', 'done_testing', 'is';} ); is_deeply( $doc->found_imports->{'Test2::V0'}, [ '-no_pragmas', '!meta', 'diag', 'done_testing', 'is' ], 'found_imports' ); done_testing(); dupes.pl100644001750001751 34615261510577 17512 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use File::Temp qw(tempfile); use List::Util qw( any ); use File::Temp qw(tempdir); # some comments sub foo { my $dir = tempdir(); my $file = tempfile(); return any { $_ > 1 } ( 0 .. 2 ); } pragma.t100644001750001751 12615261510577 17465 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Test::More; use Test::Warnings; ok(1); done_testing; double-quoted-q.t100644001750001751 416615261510577 17632 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!perl use strict; use warnings; use lib 't/lib'; use List::Util qw( none ); use TestHelper qw( doc ); use Test::More import => [qw( done_testing like ok )]; # Test the minimal example from the issue my ( $doc1, $logs1 ) = doc( filename => 'test-data/double-quoted-q.pl', ); my $tidied1 = $doc1->tidied_document; ok( do { none { $_->{level} eq 'error' } @$logs1; }, 'no errors in logs for double-quoted "q"' ); ok( do { none { $_->{message} && $_->{message} =~ /undefined value/ } @$logs1; }, 'no undefined value errors for double-quoted "q"' ); ok( defined $tidied1, 'tidied_document returns a result for double-quoted "q"' ); # Test the real-world pack("qq") example my ( $doc2, $logs2 ) = doc( filename => 'test-data/pack-qq.pl', ); my $tidied2 = $doc2->tidied_document; ok( do { none { $_->{level} eq 'error' } @$logs2; }, 'no errors in logs for pack("qq")' ); ok( do { none { $_->{message} && $_->{message} =~ /undefined value/ } @$logs2; }, 'no undefined value errors for pack("qq")' ); ok( defined $tidied2, 'tidied_document returns a result for pack("qq")' ); # Make sure the tidied document still contains the pack statement like( $tidied2, qr/pack\("qq"/, 'pack statement is preserved' ); # Test various quote-like strings my ( $doc3, $logs3 ) = doc( filename => 'test-data/various-quote-strings.pl', ); my $tidied3 = $doc3->tidied_document; ok( do { none { $_->{level} eq 'error' } @$logs3; }, 'no errors in logs for various quote-like strings' ); ok( do { none { $_->{message} && $_->{message} =~ /undefined value/ } @$logs3; }, 'no undefined value errors for various quote-like strings' ); ok( defined $tidied3, 'tidied_document returns a result for various quote-like strings' ); # Verify that real quote operators are preserved in output like( $tidied3, qr/q\{single quoted string\}/, 'q{} operator preserved' ); like( $tidied3, qr/qq\[double quoted string\]/, 'qq[] operator preserved' ); like( $tidied3, qr/qw\(list of words\)/, 'qw() operator preserved' ); done_testing; fully-qualified.t100755001750001751 254315261510577 17717 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use lib 't/lib', 'test-data/lib'; use Test::Differences qw( eq_or_diff ); use TestHelper qw( doc ); use Test::More import => [qw( diag done_testing ok )]; use Test::Needs qw( HTTP::Tiny ); my ( $doc, $log ) = doc( filename => 'test-data/fully-qualified.pl', preserve_unused => 0, tidy_whitespace => 0, ); ok( $doc->_is_used_fully_qualified('List::Util'), 'find List::Util' ); ok( !$doc->_is_used_fully_qualified('Encode'), 'cannot find Encode' ); ok( $doc->_is_used_fully_qualified('JSON::PP'), 'find JSON::PP' ); ok( $doc->_is_used_fully_qualified('HTTP::Tiny'), 'find HTTP::Tiny' ); my $expected = <<'EOF'; use strict; use warnings; use lib 'test-data/lib'; use List::Util (); use Carp qw( croak ); use HTTP::Tiny (); use JSON::PP qw( encode_json ); use Local::ViaExporter (); use Test::Builder (); use POSIX (); my @foo = List::Util::uniq( 0 .. 10 ); my $bar = encode_json( {} ); my $hr = JSON::PP->new; local *HTTP::Tiny::new = sub { 1 }; sub foo { croak() } sub some_func { local $Test::Builder::Level = $Test::Builder::Level + 1; } sub ok { return @POSIX::EXPORT_OK; } sub also_ok { return %Local::ViaExporter::foo; } EOF eq_or_diff( $doc->tidied_document, $expected, 'used modules not removed' ) || do { require Data::Dumper; diag Data::Dumper::Dumper($log); }; done_testing; ignored-modules.t100755001750001751 202115261510577 17707 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!perl use strict; use warnings; use lib 't/lib'; use TestHelper qw( doc source2pi ); use Test::More import => [qw( done_testing is ok )]; use Test::Needs qw( Geo::IP ); { my $e = source2pi( 'test-data/geo-ip.pl', 'use Geo::IP;', ); is( $e->formatted_ppi_statement, 'use Geo::IP qw( GEOIP_MEMORY_CACHE GEOIP_STANDARD );', 'module not ignored' ); } { my ($doc) = doc( filename => 'test-data/geo-ip.pl', ignore_modules => ['Geo::IP'], ); my $expected = <<'EOF'; use strict; use warnings; use Geo::IP; my $enable_cache = 0; my $standard = GEOIP_STANDARD; my $cache = $enable_cache ? GEOIP_MEMORY_CACHE : 0; EOF is( $doc->tidied_document, $expected, 'module ignored' ); my $includes = $doc->ppi_document->find('PPI::Statement::Include'); is( $includes->[2]->module, 'Geo::IP', 'Geo::IP is an include' ); ok( $doc->_is_ignored( $includes->[2] ), 'Geo::IP flagged as ignored' ); } done_testing(); lib000755001750001751 015261510577 15035 5ustar00olafolaf000000000000App-perlimports-0.000067/tTestHelper.pm100644001750001751 447515261510577 17624 0ustar00olafolaf000000000000App-perlimports-0.000067/t/libpackage TestHelper; use strict; use warnings; use App::perlimports::Document (); use App::perlimports::Include (); use Log::Dispatch::Array (); use Path::Tiny qw( path ); use PPI::Document (); use PPI::Dumper (); use Sub::Exporter -setup => { exports => [ qw( doc file2includes inc inspector logger ppi_dump source2pi ) ] }; sub doc { my %args = @_; my @log; return ( App::perlimports::Document->new( logger => logger( \@log ), %args, ), \@log ); } sub inc { my %args = @_; my @log; return ( App::perlimports::Include->new( logger => logger( \@log ), %args, ), \@log ); } sub file2includes { my $filename = shift; my $content = path($filename)->slurp; my $doc = PPI::Document->new( \$content ); my $includes = $doc->find( sub { $_[1]->isa('PPI::Statement::Include'); } ); my @includes = map { $_->clone } @{$includes}; return @includes; } sub logger { my $target = shift || die 'log target required'; my $log_level = shift || 'debug'; my $log = Log::Dispatch->new; $log->add( Log::Dispatch::Array->new( name => 'text_table', min_level => $log_level, array => $target, ) ); return $log; } sub ppi_dump { my $doc = shift; my $p = PPI::Dumper->new($doc); $p->print; } sub source2pi { my $filename = shift; my $source_text = shift; my $pi_args = shift; my @logs; my $logger = logger( \@logs ); my $doc = App::perlimports::Document->new( filename => $filename, logger => $logger, $source_text ? ( selection => $source_text ) : (), ); return App::perlimports::Include->new( document => $doc, include => $doc->includes->[0], logger => $logger, %{$pi_args}, ); } sub inspector { my $module = shift; my $logs = []; return ( App::perlimports::ExportInspector->new( module_name => $module, logger => logger($logs), ), $logs ); } 1; lookalike-words.t100644001750001751 101115261510577 17713 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use lib 't/lib'; use Test::Differences qw( eq_or_diff ); use TestHelper qw( doc ); use Test::More import => [qw( done_testing is_deeply )]; my ($doc) = doc( filename => 'test-data/lookalike-words.pl', preserve_unused => 0, ); is_deeply( $doc->interpolated_symbols, {}, 'vars' ); my $expected = <<'END'; my $foo = "this will not croak"; my $bar = <<"EOF" croak() EOF END eq_or_diff( $doc->tidied_document, $expected, 'croak not mistaken for function' ); done_testing(); preserve-spaces.t100755001750001751 204015261510577 17722 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!/usr/bin/env perl use strict; use warnings; use lib 't/lib'; use Test::Differences qw( eq_or_diff ); use TestHelper qw( doc ); use Test::More import => [qw( done_testing subtest )]; use Test::Needs qw( HTTP::Status ); subtest 'tidy_whitespace' => sub { my $expected = <<'EOF'; use strict; use warnings; use Carp (); use HTTP::Status qw( HTTP_FOUND ); print HTTP_FOUND; EOF my ($doc) = doc( filename => 'test-data/preserve-spaces.pl', tidy_whitespace => 1, ); eq_or_diff( $doc->tidied_document, $expected, 'arbitrary spacing is preserved' ); }; subtest 'disable tidy_whitespace' => sub { my $expected = <<'EOF'; use strict; use warnings; use Carp (); use HTTP::Status qw ( HTTP_FOUND ); print HTTP_FOUND; EOF my ($doc) = doc( filename => 'test-data/preserve-spaces.pl', tidy_whitespace => 0, ); eq_or_diff( $doc->tidied_document, $expected, 'arbitrary spacing is preserved' ); }; done_testing(); use-and-require.t100755001750001751 73515261510577 17612 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use lib 't/lib'; use App::perlimports::Document (); use TestHelper qw( logger ); use Test::More import => [qw( done_testing is )]; my @log; my $doc = App::perlimports::Document->new( filename => 'test-data/use-and-require.pl', logger => logger( \@log ), selection => 'use Fcntl;', ); is( $doc->tidied_document, 'use Fcntl qw( O_RDONLY );', 'require not used to find existing imports' ); done_testing; var-in-hash-key.t100644001750001751 65415261510577 17504 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use Test::More import => [qw( done_testing is )]; use Test::Needs qw( Perl::Critic::Utils ); use lib 't/lib'; use TestHelper qw( source2pi ); my $source_text = 'use Perl::Critic::Utils;'; my $e = source2pi( 'test-data/var-in-hash-key.pl', $source_text ); is( $e->formatted_ppi_statement, 'use Perl::Critic::Utils qw( $QUOTE );', 'var in hash key is found' ); done_testing(); geo-ip.pl100644001750001751 22715261510577 17550 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Geo::IP; my $enable_cache = 0; my $standard = GEOIP_STANDARD; my $cache = $enable_cache ? GEOIP_MEMORY_CACHE : 0; getopt.pl100644001750001751 12715261510577 17671 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Getopt::Long 2.40 qw(); my @foo = GetOptions(); exit; method.pl100755001750001751 30215261510577 17645 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data#!/usr/bin/env perl use strict; use warnings; use HTTP::Status; use LWP::UserAgent; my $ua = LWP::UserAgent->new; my $res = $ua->get('https://metacpan.org'); print 'ok' if $res->is_success; pithub.pl100644001750001751 7715261510577 17646 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Pithub; my $p = Pithub->new(); socket.pl100644001750001751 20715261510577 17656 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use IO::Socket::INET; use Socket qw(SO_REUSEPORT SOL_SOCKET); foo( SO_REUSEPORT, SOL_SOCKET ); sub foo { } stdout.pl100644001750001751 14315261510577 17707 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Local::STDOUT; BEGIN { print "perlimports should trap this"; } test-needs-cpanfile100644001750001751 210715261510577 17741 0ustar00olafolaf000000000000App-perlimports-0.000067use strict; use warnings; on 'test' => sub { requires 'Cpanel::JSON::XS' => '4.19'; requires 'DateTime' => 0; requires 'Env' => 0; requires 'File::chdir' => 0; requires 'File::Spec::Functions' => 0; requires 'Geo::IP' => 0; requires 'Getopt::Long' => '2.40'; requires 'HTML::TableExtract' => 0; requires 'Import::Into' => 0; requires 'IP::Random' => '1.200230' if "$]" >= 5.020; requires 'Lingua::EN::Inflect'; requires 'List::AllUtils' => 0; requires 'LWP::UserAgent' => '6.49'; requires 'Math::Round' => '0.08'; requires 'MetaCPAN::Moose' => 0; requires 'Mojo' => 0 if "$]" >= 5.016000; requires 'Moose' => 0; requires 'MooseX::Types' => 0.51; requires 'MooseX::Types::Moose' => 0.51; requires 'MooseX::Types::Path::Class' => 0; requires 'MooseX::Types::UUID' => 0; requires 'Object::Tap' => 0; requires 'Perl::Critic::Utils' => 0; requires 'Pithub' => '0'; requires 'Test2::V0' => '0'; requires 'Test::HTML::Lint' => '0'; requires 'Test::Most' => '0'; requires 'UUID' => '0'; }; mojibake.t100644001750001751 15115261510577 20044 0ustar00olafolaf000000000000App-perlimports-0.000067/xt/author#!perl use strict; use warnings qw(all); use Test::More; use Test::Mojibake; all_files_encoding_ok(); hooks000755001750001751 015261510577 15732 5ustar00olafolaf000000000000App-perlimports-0.000067/gitpre-commit100755001750001751 10215261510577 20045 0ustar00olafolaf000000000000App-perlimports-0.000067/git/hooks#!/usr/bin/env bash set -eux -o pipefail precious lint --staged config-in-import.t100644001750001751 71315261510577 17756 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use App::perlimports::Document (); use Test::More import => [qw( done_testing is )]; my $doc = App::perlimports::Document->new( filename => 'test-data/config-in-import.pl' ); my $expect = <<'EOF'; use strict; use warnings; use Getopt::Long qw( :config no_auto_abbrev no_ignore_case bundling pass_through ); EOF is( $doc->tidied_document, $expect, 'config options in import preserved' ); done_testing(); original-imports.t100644001750001751 75715261510577 20104 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use Test::More import => [qw( done_testing is_deeply )]; use App::perlimports::Document (); my $doc = App::perlimports::Document->new( filename => 'test-data/original-imports.pl' ); # use Carp; => undef # use Data::Dumper qw( Dumper ); => ['Dumper'] # use POSIX (); => [] is_deeply( $doc->found_imports, { Carp => undef, 'Data::Dumper' => ['Dumper'], POSIX => [], }, 'found imports' ); done_testing(); symbol-in-export.t100644001750001751 67715261510577 20036 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!perl use strict; use warnings; use lib 'test-data/lib', 't/lib'; use TestHelper qw( doc ); use Test::More import => [qw( done_testing is )]; use Test::Needs qw( HTTP::Status ); my ($doc) = doc( filename => 'test-data/lib/Local/SymbolInExport.pm', selection => 'use HTTP::Request::Common;', ); is( $doc->tidied_document, 'use HTTP::Request::Common qw( DELETE GET POST );', 'imports in exports found' ); done_testing(); builtin.pl100644001750001751 7615261510577 20020 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use POSIX (); printf('%s', 'ok'); english.pl100644001750001751 7515261510577 20002 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use English qw( -no_match_vars ); heredoc.pl100644001750001751 22015261510577 17772 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Perl::Critic::Utils qw( $QUOTE ); my $foo = <<"EOT"; one $QUOTE two EOT my $bar = <<'EOT'; one $DQUOTE two EOT pack-qq.pl100644001750001751 23515261510577 17724 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use IO::Socket::INET; my $sock = IO::Socket::INET->new; my $timeout = pack("qq", 10, 0); $sock->sockopt(SO_RCVTIMEO, $timeout); require.pl100755001750001751 47515261510577 20054 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data#!/usr/bin/env perl use strict; use warnings; require LWP::UserAgent; if ( $ENV{FOO} ) { require WWW::Mechanize; } require Carp if $ENV{BAR}; require List::Util; require Time::Local if $^O eq 'MacOS'; require Cwd; my @foo = List::Util::any { $_ > 3 } ( 0..4 ); my $bar = any (); sub any { return 1; } skip-all.t100644001750001751 26315261510577 17734 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Test::More import => [ 'is', 'is_deeply', 'ok' ], skip_all => 'Test is broken', tests => 28; ok(1); is( 1, 1 ); is_deeply( ['foo'], ['bar'] ); pod-spell.t100644001750001751 117015261510577 20204 0ustar00olafolaf000000000000App-perlimports-0.000067/xt/authoruse strict; use warnings; use Test::More; # generated by Dist::Zilla::Plugin::Test::PodSpelling 2.007006 use Test::Spelling 0.17; use Pod::Wordlist; add_stopwords(); all_pod_files_spelling_ok( qw( bin lib ) ); __DATA__ 1197072 198982749 49699333 Alders Alders' Annotations App CLI Choroba Config Copilot Dave Document ExportInspector Include Ishigaki James Johnson José Kenichi Logger Manuel Mendoza Nelo Nicolas Olaf Oliver Onyiah PPI Paul Peter Raspass Rodríguez Role Rolsky Sandbox Sorter autarch choroba dependabot dump git ishigaki jose93rd jraspass lib mendoza nelo olaf paul perlimports pyrrhlin sandboxed script 00-report-prereqs.t100644001750001751 1360115261510577 20044 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!perl use strict; use warnings; # This test was generated by Dist::Zilla::Plugin::Test::ReportPrereqs 0.029 use Test::More tests => 1; use ExtUtils::MakeMaker; use File::Spec; # from $version::LAX my $lax_version_re = qr/(?: undef | (?: (?:[0-9]+) (?: \. | (?:\.[0-9]+) (?:_[0-9]+)? )? | (?:\.[0-9]+) (?:_[0-9]+)? ) | (?: v (?:[0-9]+) (?: (?:\.[0-9]+)+ (?:_[0-9]+)? )? | (?:[0-9]+)? (?:\.[0-9]+){2,} (?:_[0-9]+)? ) )/x; # hide optional CPAN::Meta modules from prereq scanner # and check if they are available my $cpan_meta = "CPAN::Meta"; my $cpan_meta_pre = "CPAN::Meta::Prereqs"; my $HAS_CPAN_META = eval "require $cpan_meta; $cpan_meta->VERSION('2.120900')" && eval "require $cpan_meta_pre"; ## no critic # Verify requirements? my $DO_VERIFY_PREREQS = 1; sub _max { my $max = shift; $max = ( $_ > $max ) ? $_ : $max for @_; return $max; } sub _merge_prereqs { my ($collector, $prereqs) = @_; # CPAN::Meta::Prereqs object if (ref $collector eq $cpan_meta_pre) { return $collector->with_merged_prereqs( CPAN::Meta::Prereqs->new( $prereqs ) ); } # Raw hashrefs for my $phase ( keys %$prereqs ) { for my $type ( keys %{ $prereqs->{$phase} } ) { for my $module ( keys %{ $prereqs->{$phase}{$type} } ) { $collector->{$phase}{$type}{$module} = $prereqs->{$phase}{$type}{$module}; } } } return $collector; } my @include = qw( ); my @exclude = qw( ); # Add static prereqs to the included modules list my $static_prereqs = do './t/00-report-prereqs.dd'; # Merge all prereqs (either with ::Prereqs or a hashref) my $full_prereqs = _merge_prereqs( ( $HAS_CPAN_META ? $cpan_meta_pre->new : {} ), $static_prereqs ); # Add dynamic prereqs to the included modules list (if we can) my ($source) = grep { -f } 'MYMETA.json', 'MYMETA.yml'; my $cpan_meta_error; if ( $source && $HAS_CPAN_META && (my $meta = eval { CPAN::Meta->load_file($source) } ) ) { $full_prereqs = _merge_prereqs($full_prereqs, $meta->prereqs); } else { $cpan_meta_error = $@; # capture error from CPAN::Meta->load_file($source) $source = 'static metadata'; } my @full_reports; my @dep_errors; my $req_hash = $HAS_CPAN_META ? $full_prereqs->as_string_hash : $full_prereqs; # Add static includes into a fake section for my $mod (@include) { $req_hash->{other}{modules}{$mod} = 0; } for my $phase ( qw(configure build test runtime develop other) ) { next unless $req_hash->{$phase}; next if ($phase eq 'develop' and not $ENV{AUTHOR_TESTING}); for my $type ( qw(requires recommends suggests conflicts modules) ) { next unless $req_hash->{$phase}{$type}; my $title = ucfirst($phase).' '.ucfirst($type); my @reports = [qw/Module Want Have/]; for my $mod ( sort keys %{ $req_hash->{$phase}{$type} } ) { next if grep { $_ eq $mod } @exclude; my $want = $req_hash->{$phase}{$type}{$mod}; $want = "undef" unless defined $want; $want = "any" if !$want && $want == 0; if ($mod eq 'perl') { push @reports, ['perl', $want, $]]; next; } my $req_string = $want eq 'any' ? 'any version required' : "version '$want' required"; my $file = $mod; $file =~ s{::}{/}g; $file .= ".pm"; my ($prefix) = grep { -e File::Spec->catfile($_, $file) } @INC; if ($prefix) { my $have = MM->parse_version( File::Spec->catfile($prefix, $file) ); $have = "undef" unless defined $have; push @reports, [$mod, $want, $have]; if ( $DO_VERIFY_PREREQS && $HAS_CPAN_META && $type eq 'requires' ) { if ( $have !~ /\A$lax_version_re\z/ ) { push @dep_errors, "$mod version '$have' cannot be parsed ($req_string)"; } elsif ( ! $full_prereqs->requirements_for( $phase, $type )->accepts_module( $mod => $have ) ) { push @dep_errors, "$mod version '$have' is not in required range '$want'"; } } } else { push @reports, [$mod, $want, "missing"]; if ( $DO_VERIFY_PREREQS && $type eq 'requires' ) { push @dep_errors, "$mod is not installed ($req_string)"; } } } if ( @reports ) { push @full_reports, "=== $title ===\n\n"; my $ml = _max( map { length $_->[0] } @reports ); my $wl = _max( map { length $_->[1] } @reports ); my $hl = _max( map { length $_->[2] } @reports ); if ($type eq 'modules') { splice @reports, 1, 0, ["-" x $ml, "", "-" x $hl]; push @full_reports, map { sprintf(" %*s %*s\n", -$ml, $_->[0], $hl, $_->[2]) } @reports; } else { splice @reports, 1, 0, ["-" x $ml, "-" x $wl, "-" x $hl]; push @full_reports, map { sprintf(" %*s %*s %*s\n", -$ml, $_->[0], $wl, $_->[1], $hl, $_->[2]) } @reports; } push @full_reports, "\n"; } } } if ( @full_reports ) { diag "\nVersions for all modules listed in $source (including optional ones):\n\n", @full_reports; } if ( $cpan_meta_error || @dep_errors ) { diag "\n*** WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING ***\n"; } if ( $cpan_meta_error ) { my ($orig_source) = grep { -f } 'MYMETA.json', 'MYMETA.yml'; diag "\nCPAN::Meta->load_file('$orig_source') failed with: $cpan_meta_error\n"; } if ( @dep_errors ) { diag join("\n", "\nThe following REQUIRED prerequisites were not satisfied:\n", @dep_errors, "\n" ); } pass('Reported prereqs'); # vim: ts=4 sts=4 sw=4 et: dump-perl-exports.t100755001750001751 377415261510577 20241 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!/usr/bin/env perl use strict; use warnings; use Test::More import => [qw( done_testing subtest )]; use Test::Needs qw( Moose ); use Test::Script 1.27 qw( script_compiles script_runs script_stderr_is script_stderr_like ); script_compiles('script/dump-perl-exports'); subtest 'Moose' => sub { script_runs( [ 'script/dump-perl-exports', '--module', 'Moose' ] ); script_stderr_is( q{}, 'no errors' ); }; subtest 'Moo' => sub { script_runs( [ 'script/dump-perl-exports', '--module', 'Moo' ] ); script_stderr_is( q{}, 'no errors' ); }; subtest 'implied --module' => sub { script_runs( [ 'script/dump-perl-exports', 'Moo' ] ); script_stderr_is( q{}, 'no errors' ); }; subtest 'help' => sub { script_runs( [ 'script/dump-perl-exports', '--help' ] ); script_stderr_is( q{}, 'no errors' ); }; subtest 'libs' => sub { script_runs( [ 'script/dump-perl-exports', '--libs', 'test-data/lib', 'Local::ViaExporter' ] ); script_stderr_is( q{}, 'no errors' ); }; subtest 'log level' => sub { script_runs( [ 'script/dump-perl-exports', '--log-level', 'info', 'Moo' ] ); script_stderr_is( q{}, 'no errors' ); }; subtest 'verbose help' => sub { script_runs( [ 'script/dump-perl-exports', '--verbose-help' ] ); script_stderr_is( q{}, 'no errors' ); }; subtest 'version' => sub { script_runs( [ 'script/dump-perl-exports', '--version' ] ); script_stderr_is( q{}, 'no errors' ); }; subtest 'Local::ViaExporter' => sub { script_runs( [ 'script/dump-perl-exports', '--libs', 'test-data/lib', '--module', 'Local::ViaExporter' ] ); script_stderr_is( q{}, 'no errors' ); }; subtest 'Not Found' => sub { script_runs( [ 'script/dump-perl-exports', '--module', 'Local::Does::Not::Exist::Foo' ] ); script_stderr_like( qr{Can't locate}, 'error when module not found' ); }; done_testing(); hash-unquoted-key.t100644001750001751 77015261510577 20153 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!/usr/bin/env perl use strict; use warnings; use lib 't/lib'; use TestHelper qw( file2includes source2pi ); use Test::More import => [qw( done_testing is )]; use Test::Needs qw( HTTP::Status ); my @includes = file2includes('test-data/hash-unquoted-key.pl'); my $e = source2pi( 'test-data/hash-unquoted-key.pl', undef, { include => $includes[2] } ); is( $e->formatted_ppi_statement, 'use HTTP::Status ();', 'recognizes is_info as a word representing a string' ); done_testing; maybe-new-include.t100644001750001751 1643015261510577 20145 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!perl use strict; use warnings; use lib 'test-data/lib', 't/lib'; use App::perlimports::Document (); use TestHelper qw( logger ); use Test::More import => [qw( done_testing ok subtest )]; sub chomped { my ($str) = @_; chomp($str); return $str; } my @log; ## no critic (Subroutines::ProtectPrivateSubs) sub make_doc { my %args = @_; @log = (); my $text = $args{include} || die 'must give an use statement'; my $ppi_doc = PPI::Document->new( \$text ); # (lint default is 0, tidy default is 1) my $doc = App::perlimports::Document->new( logger => logger( \@log ), ppi_document => $ppi_doc, filename => 'none', ( lint => $args{lint} ) x !!defined $args{lint}, ( tidy_whitespace => $args{tidy} ) x !!defined $args{tidy}, ); my $stm = $doc->includes->[0]; # PPI:Statement:Include # An empty includes list means the fixture's use statement could not be # evaluated in the sandbox (e.g. it relies on a symbol not exported by the # installed module version). Fail with a clear message rather than a cryptic # "Can't call method ... on an undefined value" from _include_analyzer. die "no includes found for: $text" unless $stm; my $inc = $doc->_include_analyzer($stm); # App:perlimports:Include return ( $doc, $inc ); } ## use critic subtest 'tidied include with tidying' => sub { my $orig = 'use List::Util qw( first );'; my ( undef, $inc ) = make_doc( include => $orig ); my $ppis = $inc->_include; # PPI:Statement:Include # with tidy_whitespace, the only way to get the original back is: # * statement was identical already, or, # * original had some extra spaces before the symbol list. # statements that are rejected (the original statement is kept!) my $reject = 'use List::Util qw( first );'; foreach my $try ( $orig, $reject ) { my $res = $inc->_maybe_get_new_include($try); ok( $res == $ppis, 'kept original, rejected: ' . $try ); } # and a list of statements that should replace the original: my @tries = split /\n/, <<'EODOC'; use List::Util qw(first); use List::Util (); use List::Util qw( first max ); EODOC push @tries, chomped(<<'EOTEXT'); use List::Util qw( first ); EOTEXT foreach my $try (@tries) { my $res = $inc->_maybe_get_new_include($try); ok( $res != $ppis, 'replaced original with: ' . $try ); } }; subtest 'tidied include without tidying' => sub { my $orig = 'use List::Util qw( first );'; my ( undef, $inc ) = make_doc( include => $orig, tidy => 0 ); my $ppis = $inc->_include; # PPI:Statement:Include # without tidy_whitespace, always get back the original # if the only change was whitespace. # statements that are rejected (the original statement is kept!) my @rejects = split /\n/, <<'EODOC'; use List::Util qw( first ); use List::Util qw(first); EODOC push @rejects, chomped(<<'EOTEXT'); use List::Util qw( first ); EOTEXT foreach my $try ( $orig, @rejects ) { my $res = $inc->_maybe_get_new_include($try); ok( $res == $ppis, 'kept original, rejected spacing change' ); } # statements that should replace the original: my @tries = split /\n/, <<'EODOC2'; use List::Util (); use List::Util qw( first max ); EODOC2 foreach my $try (@tries) { my $res = $inc->_maybe_get_new_include($try); ok( $res != $ppis, 'replaced original: different content' ); } }; subtest 'tidied include with version and tidying' => sub { my $orig = 'use File::Temp 0.23 qw( tempfile tempdir );'; my ( $doc, $inc ) = make_doc( include => $orig ); my $ppis = $inc->_include; # PPI:Statement:Include # statement rejected in favor of the original my $reject = 'use File::Temp 0.23 qw( tempfile tempdir );'; foreach my $try ( $orig, $reject ) { my $res = $inc->_maybe_get_new_include($try); ok( $res == $ppis, 'kept original, rejected: ' . $try ); } # statements that should replace the original: my @tries = ('use File::Temp 0.23 qw(tempfile tempdir);'); push @tries, chomped(<<'EOTEXT'); use File::Temp 0.23 qw( tempfile tempdir ); EOTEXT foreach my $try (@tries) { my $res = $inc->_maybe_get_new_include($try); ok( $res != $try, 'replaced original with ' . $try ); } # ----------- extra space before version number -------- # always gets replaced! $orig = 'use File::Temp 0.23 qw( tempfile tempdir );'; ( $doc, $inc ) = make_doc( include => $orig ); $ppis = $inc->_include; # PPI:Statement:Include # statements that should replace the original: @tries = split /\n/, <<'EODOC'; use File::Temp 0.23 qw( tempfile tempdir ); use File::Temp 0.23 qw(tempfile tempdir); use File::Temp 0.23 (); EODOC push @tries, chomped(<<'EOTEXT2'); use File::Temp 0.23 qw( tempfile tempdir ); EOTEXT2 foreach my $try (@tries) { my $res = $inc->_maybe_get_new_include($try); ok( $res != $ppis, 'replaced original with: ' . $try ); } }; subtest 'include w version no tidying' => sub { my $orig = 'use File::Temp 0.23 qw( tempfile tempdir );'; my ( undef, $inc ) = make_doc( include => $orig, tidy => 0 ); my $ppis = $inc->_include; # PPI:Statement:Include # without tidy_whitespace, always get back the original # if the only change was whitespace. # statements that are rejected in favor of the original my $rejects = <<'EODOC'; use File::Temp 0.23 qw( tempfile tempdir ); use File::Temp 0.23 qw(tempfile tempdir); EODOC foreach my $try ( $orig, split /\n/, $rejects ) { my $res = $inc->_maybe_get_new_include($try); ok( $res == $ppis, 'kept original, rejected spacing change' ); } # statements that should replace the original: my @tries = split /\n/, <<'EODOC2'; use File::Temp 0.23 qw(tempfile); use File::Temp 0.23 (); EODOC2 push @tries, chomped(<<'EOTEXT'); use File::Temp 0.23 qw( tempfile tempdir mkstemp ); EOTEXT foreach my $try (@tries) { my $res = $inc->_maybe_get_new_include($try); ok( $res != $ppis, 'replaced original; different content' ); } }; subtest 'multiline include with tidying' => sub { my $orig = chomped(<<'EORIG'); use List::Util qw( first max min ); EORIG my ( undef, $inc ) = make_doc( include => $orig ); my $ppis = $inc->_include; # PPI:Statement:Include # with tidy_whitespace, the only way to get the original back is: # * statement was identical already, or, # * original had some extra spaces before the symbol list. # statement that is rejected (the original statement is kept!) my $reject = chomped(<<'EOTEXT'); use List::Util qw( first max min ); EOTEXT foreach my $try ( $orig, $reject ) { my $res = $inc->_maybe_get_new_include($try); ok( $res == $ppis, 'kept original, rejected spacing change' ); } # statements that should replace the original: my @tries = split /\n/, <<'EODOC'; use List::Util qw(first max min); use List::Util qw( first max min ); EODOC foreach my $try (@tries) { my $res = $inc->_maybe_get_new_include($try); ok( $res != $ppis, 'replaced original with: ' . $try ); } }; done_testing(); regex-replacement.t100644001750001751 76115261510577 20207 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use lib 't/lib'; use TestHelper qw( doc ); use Test::More import => [qw( done_testing is )]; use Test::Needs { 'IP::Random' => '1.200230' }; my ($doc) = doc( filename => 'test-data/regex-replacement.pl', preserve_unused => 0, ); my $expected = <<'EOF'; use IP::Random (); s/($RE{net}{IPv4})/${\( $store{$1} ||= IP::Random::random_ipv4() )}/g; EOF is( $doc->tidied_document, $expected, 'function found in regex replacement' ); done_testing(); datetime.pl100644001750001751 10215261510577 20154 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use DateTime; my $dt = DateTime->now; env-bare.pl100644001750001751 6415261510577 20046 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Env; my $h = $HOME; explodes.pl100644001750001751 10215261510577 20203 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Local::Explodes qw( foo ); foo(); find-bin.pl100644001750001751 11115261510577 20046 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use FindBin '$Bin'; use lib "$Bin/../../lib"; mojo-url.pl100644001750001751 1715261510577 20111 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause Mojo::URL; test-more.t100644001750001751 7415261510577 20117 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Test::More; done_testing(); typeglob.pl100644001750001751 10115261510577 20204 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use File::chdir; $CWD = 'test-data'; variable.pl100644001750001751 27415261510577 20157 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Getopt::Long qw( $REQUIRE_ORDER $RETURN_IN_ORDER ); print ${RETURN_IN_ORDER}; my $code = <<"EOT"; ${REQUIRE_ORDER} EOT my $more = <<'EOT'; ${PERMUTE} EOT pod-syntax.t100644001750001751 25115261510577 20372 0ustar00olafolaf000000000000App-perlimports-0.000067/xt/author#!perl # This file was automatically generated by Dist::Zilla::Plugin::PodSyntaxTests use strict; use warnings; use Test::More; use Test::Pod 1.41; all_pod_files_ok(); 00-report-prereqs.dd100644001750001751 1375115261510577 20176 0ustar00olafolaf000000000000App-perlimports-0.000067/tdo { my $x = { 'configure' => { 'requires' => { 'ExtUtils::MakeMaker' => '0', 'perl' => '5.013002' } }, 'develop' => { 'recommends' => { 'Dist::Zilla::PluginBundle::Git::VersionManager' => '0.007' }, 'requires' => { 'Code::TidyAll' => '0.71', 'Code::TidyAll::Plugin::SortLines::Naturally' => '0.000003', 'Code::TidyAll::Plugin::Test::Vars' => '0.04', 'Code::TidyAll::Plugin::UniqueLines' => '0.000003', 'Parallel::ForkManager' => '1.19', 'Perl::Critic' => '1.132', 'Perl::Critic::Bangs' => '1.10', 'Perl::Critic::Freenode' => '0', 'Perl::Critic::Moose' => '0', 'Perl::Critic::Policy::ValuesAndExpressions::ProhibitAccessOfPrivateData' => 'v1.0.0', 'Perl::Critic::Policy::Variables::ProhibitUnusedVarsStricter' => '0.116', 'Perl::Tidy' => '20180220', 'Pod::Coverage::TrustPod' => '0', 'Pod::Wordlist' => '0', 'Test::CPAN::Changes' => '0.19', 'Test::EOL' => '0', 'Test::Mojibake' => '0', 'Test::More' => '0.96', 'Test::Pod' => '1.41', 'Test::Pod::Coverage' => '1.08', 'Test::Portability::Files' => '0', 'Test::Spelling' => '0.17', 'Test::Vars' => '0.014', 'Test::Version' => '1' } }, 'runtime' => { 'requires' => { 'Capture::Tiny' => '0', 'Class::Inspector' => '1.36', 'Cpanel::JSON::XS' => '0', 'Data::Dumper' => '0', 'Data::UUID' => '0', 'File::Basename' => '0', 'File::XDG' => '1.01', 'Getopt::Long::Descriptive' => '0', 'List::Util' => '0', 'Log::Dispatch' => '2.70', 'Memoize' => '0', 'Module::Runtime' => '0', 'Moo' => '0', 'Moo::Role' => '0', 'MooX::StrictConstructor' => '0', 'PPI' => '1.276', 'PPI::Document' => '0', 'PPIx::Utils::Classification' => '0', 'PPIx::Utils::Traversal' => '0', 'Path::Iterator::Rule' => '0', 'Path::Tiny' => '0', 'Perl::Tidy' => '20220613', 'Pod::Usage' => '0', 'Ref::Util' => '0', 'Scalar::Util' => '0', 'Sereal::Decoder' => '0', 'Sereal::Encoder' => '0', 'Sub::HandlesVia' => '0', 'Symbol::Get' => '0.10', 'TOML::Tiny' => '0.16', 'Text::Diff' => '0', 'Text::SimpleTable::AutoWidth' => '0', 'Try::Tiny' => '0', 'Types::Common::Numeric' => '0', 'Types::Standard' => '0', 'feature' => '0', 'perl' => 'v5.18.0', 'strict' => '0', 'utf8' => '0', 'warnings' => '0' } }, 'test' => { 'recommends' => { 'CPAN::Meta' => '2.120900' }, 'requires' => { 'ExtUtils::MakeMaker' => '0', 'File::Spec' => '0', 'File::pushd' => '0', 'Log::Dispatch::Array' => '0', 'PPI::Dumper' => '0', 'Sub::Exporter' => '0', 'Test::Differences' => '0', 'Test::Fatal' => '0', 'Test::More' => '0', 'Test::Needs' => '0', 'Test::RequiresInternet' => '0', 'Test::Script' => '1.29', 'Test::Warnings' => '0', 'lib' => '0', 'perl' => 'v5.18.0' } } }; $x; }App000755001750001751 015261510577 15312 5ustar00olafolaf000000000000App-perlimports-0.000067/libperlimports.pm100644001750001751 141515261510577 20371 0ustar00olafolaf000000000000App-perlimports-0.000067/lib/Apppackage App::perlimports; use strict; use warnings; our $VERSION = '0.000067'; 1; # ABSTRACT: Make implicit imports explicit __END__ =pod =encoding UTF-8 =head1 NAME App::perlimports - Make implicit imports explicit =head1 VERSION version 0.000067 =head1 DESCRIPTION This distribution provides the L command line interface (CLI), which aims to automate the cleanup and maintenance of Perl import statements. See L for detailed information on how to use this tool. =head1 AUTHOR Olaf Alders =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2020 by Olaf Alders. 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 exported-variables.t100755001750001751 135215261510577 20420 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!/usr/bin/env perl use strict; use warnings; use lib 'test-data/lib', 't/lib'; use TestHelper qw( doc inc ); use Test::More import => [qw( done_testing is is_deeply ok )]; my ($doc) = doc( filename => 'test-data/exported-variables.pl', selection => 'use Local::ViaExporter qw();', ); my ($pi) = inc( document => $doc, include => $doc->includes->[0], ); is_deeply( $pi->_explicit_exports, { 'foo' => 'foo', '$foo' => '$foo', '@foo' => '@foo', '%foo' => '%foo', }, 'some _explicit_exports' ); ok( !$pi->_is_ignored, '_is_ignored' ); is( $pi->formatted_ppi_statement, 'use Local::ViaExporter qw( $foo @foo %foo );', 'formatted_ppi_statement' ); done_testing(); function-reference.t100644001750001751 143415261510577 20377 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use lib 't/lib', 'test-data/lib'; use Test::Differences qw( eq_or_diff ); use TestHelper qw( doc ); use Test::More import => [qw( diag done_testing ok )]; use Test::Needs qw( Cpanel::JSON::XS ); my ( $doc, $log ) = doc( filename => 'test-data/function-reference.pl', preserve_unused => 0, ); ok( $doc->_is_used_fully_qualified('Cpanel::JSON::XS'), 'find Cpanel::JSON::XS via function reference' ); my $expected = <<'EOF'; use strict; use warnings; use Cpanel::JSON::XS (); my $true_ref = \&Cpanel::JSON::XS::true; my $false_ref = \&Cpanel::JSON::XS::false; EOF eq_or_diff( $doc->tidied_document, $expected, 'function reference keeps module' ) || do { require Data::Dumper; diag Data::Dumper::Dumper($log); }; done_testing; moosex-types-moose.t100755001750001751 71715261510600 20363 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!/usr/bin/env perl use strict; use warnings; use lib 't/lib'; use TestHelper qw( doc ); use Test::More import => [qw( done_testing is )]; use Test::Needs qw( MooseX::Types MooseX::Types::Moose ); my ($doc) = doc( filename => 'test-data/moosex-types-moose.pl', selection => 'use MooseX::Types::Moose qw( ArrayRef );', ); is( $doc->tidied_document, 'use MooseX::Types::Moose qw( ArrayRef Str );', 'imported types found' ); done_testing; qualified-bareword.t100644001750001751 106415261510600 20346 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use lib 't/lib'; use Test::Differences qw( eq_or_diff ); use TestHelper qw( doc ); use Test::More import => [qw( done_testing is_deeply )]; my ($doc) = doc( filename => 'test-data/qualified-bareword.pl', preserve_unused => 0, ); is_deeply( $doc->interpolated_symbols, {}, 'vars' ); my $expected = <<'END'; use strict; use warnings; use Path::Tiny (); my $path = Path::Tiny::->new('foo.txt'); END eq_or_diff( $doc->tidied_document, $expected, 'qualified bareword detected as module name' ); done_testing(); switches-in-import.t100644001750001751 72715261510600 20332 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use App::perlimports::CLI (); use Capture::Tiny qw( capture ); use Test::More import => [qw( done_testing is )]; my $expected = <<'EOF'; use strict; use warnings; use CustomImport qw( -ignore blib -ignore \\wB\\w ); EOF local @ARGV = ( '-f', 'test-data/switches-in-import.pl', ); my $cli = App::perlimports::CLI->new; my ($stdout) = capture { $cli->run; }; is( $stdout, $expected, 'module switches preserved' ); done_testing(); env-comma.pl100644001750001751 10715261510600 20232 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Env 'HOME', '@PATH'; my @copy = @PATH; env-mixed.pl100644001750001751 11115261510600 20237 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Env qw( $HOME @PATH ); my @copy = @PATH; local-lib.pl100644001750001751 5715261510600 20172 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use local::lib; 1; long-list.pl100644001750001751 30215261510600 20255 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use lib 'test-data/lib'; use Local::LongList qw( alpha bravo charlie ); alpha(); bravo(); charlie(); delta(); echo(); foxtrot(); golf(); hotel(); india(); juliet(); portability.t100644001750001751 13015261510600 20605 0ustar00olafolaf000000000000App-perlimports-0.000067/xt/authoruse strict; use warnings; use Test::More; use Test::Portability::Files; run_tests(); cpan-modules000755001750001751 015261510600 16641 5ustar00olafolaf000000000000App-perlimports-0.000067/tpithub.t100755001750001751 61115261510600 20442 0ustar00olafolaf000000000000App-perlimports-0.000067/t/cpan-modules#!/usr/bin/env perl use strict; use warnings; use lib 'test-data/lib', 't/lib'; use TestHelper qw( source2pi ); use Test::More import => [qw( done_testing is )]; use Test::Needs qw( Pithub ); my $pi = source2pi( 'test-data/pithub.pl', 'use Pithub;', ); is( $pi->formatted_ppi_statement, 'use Pithub ();', 'removes implicit export for Moo OO class' ); done_testing(); hash-key-expression.t100644001750001751 77515261510600 20476 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!/usr/bin/env perl use strict; use warnings; use lib 't/lib'; use TestHelper qw( file2includes source2pi ); use Test::More import => [qw( done_testing is )]; use Test::Needs qw( HTTP::Status ); my @includes = file2includes('test-data/hash-key-expression.pl'); my $e = source2pi( 'test-data/hash-key-expression.pl', undef, { include => $includes[2] } ); is( $e->formatted_ppi_statement, 'use HTTP::Status qw( is_info );', 'recognizes is_info as an imported symbol' ); done_testing; locally-defined-sub.t100644001750001751 125315261510600 20422 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use lib 't/lib', 'test-data/lib'; use Test::Differences qw( eq_or_diff ); use TestHelper qw( doc ); use Test::More import => [qw( done_testing )]; use Test::Needs qw( Math::Round ); my ($doc) = doc( filename => 'test-data/lib/Local/Round.pm', preserve_unused => 0, ); my $expected = <<'END'; package Local::Round; use parent 'Exporter'; use strict; use warnings; use Math::Round qw( nearest ); our @EXPORT_OK = qw(round); sub round { my ( $number, $places ) = @_; return nearest( 10**-$places, $number ); } 1; END eq_or_diff( $doc->tidied_document, $expected, 'locally defined sub is not ignored' ); done_testing(); annotation.pl100644001750001751 46315261510600 20527 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Carp; ## no perlimports use POSIX; ## no perlimports use Cwd; use Digest; ## use perlimports use Encode; use FindBin; # Reasons ## no perlimports print decode( 'utf8', sprintf( 'hey %s', encode( 'utf8', 'Sofia Margareta Götschenhjelm-Helin' ) ) ); env-scalar.pl100644001750001751 7715261510600 20371 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Env qw( HOME ); my $h = $HOME; env-unused.pl100644001750001751 7415261510600 20424 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Env qw( @PATH ); my $x = 1; quoted-var.pl100644001750001751 31015261510600 20433 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use IO::Uncompress::Gunzip qw( $GunzipError ); sub load { my $fname = 'foo.gz'; IO::Uncompress::Gunzip->new($fname) or die "gzip failed: $GunzipError\n"; } signatures.pl100644001750001751 55115261510600 20537 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use v5.20; use feature qw(signatures); no warnings qw(experimental::signatures); use signatures; use FindBin; use HTTP::Status qw( HTTP_CONTINUE ); ## no critic (Subroutines::ProhibitSubroutinePrototypes) sub one ( $continue = HTTP_CONTINUE, $foo = 'bar', $two = HTTP_OK() ) { return $continue; } sub two ( $cwd = $Bin ) { } pod-coverage.t100644001750001751 245515261510600 20652 0ustar00olafolaf000000000000App-perlimports-0.000067/xt/author#!perl # This file was automatically generated by Dist::Zilla::Plugin::Test::Pod::Coverage::Configurable 0.07. use Test::Pod::Coverage 1.08; use Test::More 0.88; BEGIN { if ( $] <= 5.008008 ) { plan skip_all => 'These tests require Pod::Coverage::TrustPod, which only works with Perl 5.8.9+'; } } use Pod::Coverage::TrustPod; my %skip = map { $_ => 1 } qw( ); my @modules; for my $module ( all_modules() ) { next if $skip{$module}; push @modules, $module; } plan skip_all => 'All the modules we found were excluded from POD coverage test.' unless @modules; plan tests => scalar @modules; my %trustme = ( 'App::perlimports::Role::Logger' => [ qr/.*/ ] ); my @also_private = ( qr/^(?:BUILD|BUILDARGS|all_includes|possibly_imported_tokens|sub_exporter_export_list|has_at_export|has_at_export_ok|has_import_flags)$/ ); for my $module ( sort @modules ) { pod_coverage_ok( $module, { coverage_class => 'Pod::Coverage::TrustPod', also_private => \@also_private, trustme => $trustme{$module} || [], }, "pod coverage for $module" ); } done_testing(); test-version.t100644001750001751 63715261510600 20721 0ustar00olafolaf000000000000App-perlimports-0.000067/xt/authoruse strict; use warnings; use Test::More; # generated by Dist::Zilla::Plugin::Test::Version 1.09 use Test::Version; my @imports = qw( version_all_ok ); my $params = { is_strict => 0, has_version => 1, multiple => 0, }; push @imports, $params if version->parse( $Test::Version::VERSION ) >= version->parse('1.002'); Test::Version->import(@imports); version_all_ok; done_testing; dump-perl-exports100644001750001751 1252015261510600 21025 0ustar00olafolaf000000000000App-perlimports-0.000067/script#!perl use strict; use warnings; use feature qw( say ); use App::perlimports::ExportInspector (); use Getopt::Long::Descriptive qw( describe_options ); use List::Util qw( max ); use Log::Dispatch (); use Module::Runtime qw( use_module ); use Pod::Usage qw( pod2usage ); use Text::SimpleTable::AutoWidth (); my ( $opts, $usage ) = _options(); if ( $opts->version ) { say $App::perlimports::ExportInspector::VERSION; exit(0); } if ( $opts->help ) { print $usage; exit(0); } if ( $opts->verbose_help ) { print STDOUT $usage; pod2usage({ -exitval => 0 }); } if ( $opts->libs ) { unshift @INC, ( split m{,}, $opts->libs ); } my $logger = Log::Dispatch->new( outputs => [ [ 'Screen', min_level => $opts->log_level, newline => 1, stderr => 1 ] ] ); my $module = $opts->module || shift @ARGV; if ( !$module ) { say q{Mandatory parameter 'module' missing}; print $usage; exit(1); } my $ei = App::perlimports::ExportInspector->new( logger => $logger, module_name => $module, ); if ( $ei->is_oo_class ) { print 'Appears to be an Object Oriented class.' . "\n"; } if ( @{ $ei->class_isa } ) { my $t = Text::SimpleTable::AutoWidth->new(); $t->captions( ['ISA'] ); for my $class ( @{ $ei->class_isa } ) { $t->row($class); } print $t->draw; } if ( @{ $ei->pkg_isa } ) { my $t = Text::SimpleTable::AutoWidth->new(); $t->captions( ['Package ISA'] ); for my $class ( @{ $ei->pkg_isa } ) { $t->row($class); } print $t->draw; } if ( @{ $ei->at_export_tags } ) { my %tags = %{ $ei->at_export_tags }; my @keys = keys %tags; my @headings = ( 'Export Tag', 'Exported Symbols' ); my $col1_width = max map { length($_) } @keys, $headings[0]; my $col2_width = max map { length($_) } map ( { @{$_} } values %tags ), $headings[1]; my $t = Text::SimpleTable->new( [ $col1_width, 'Export Tag' ], [ $col2_width, 'Exported Symbols' ] ); my $i = 0; for my $key ( sort @keys ) { $t->row( $key, join "\n", sort @{ $tags{$key} } ); ++$i; $t->hr if $i < scalar @keys; } print $t->draw; } if ( @{ $ei->at_export_fail } ) { my $t = Text::SimpleTable::AutoWidth->new(); $t->captions( ['@EXPORT_FAIL'] ); for my $val ( sort @{ $ei->at_export_fail } ) { $t->row($val); } print $t->draw; } if ( $ei->has_implicit_exports ) { my $t = Text::SimpleTable::AutoWidth->new(); if ( $ei->implicit_export_names_match_values ) { $t->captions( ['Default Exported Symbols'] ); for my $symbol ( sort $ei->implicit_export_names ) { $t->row($symbol); } } else { $t->captions( [ 'Default Export Symbol', 'Import Name' ] ); for my $key ( sort $ei->implicit_export_names ) { $t->row( $key, $ei->implicit_exports->{$key} ); } } print $t->draw; printf( "%i symbols\n", scalar $ei->implicit_export_names ); } my $exports = $ei->explicit_exports; if ( !keys %{$exports} ) { print 'No exported symbols found' . "\n"; exit(0); } { my $t = Text::SimpleTable::AutoWidth->new(); if ( $ei->explicit_export_names_match_values ) { $t->captions( ['All Exportable Symbols'] ); for my $symbol ( sort $ei->explicit_export_names ) { $t->row($symbol); } } else { $t->captions( [ 'Explicit Export Symbol', 'Import Name' ] ); for my $key ( sort $ei->explicit_export_names ) { $t->row( $key, $exports->{$key} ); } } print $t->draw; printf( "%i symbols\n", scalar $ei->explicit_export_names ); require Data::Dumper; ## no perlimports $logger->debug( Data::Dumper::Dumper($ei) ); } sub _options { return describe_options( 'dump-perl-exports %o', [ 'module|m=s', 'The module to inspect for exports', ], [], [ 'libs=s', 'Comma-separated list of library paths to include (eg --libs lib,t/lib,dev/lib)', ], [], [ 'version', 'Print installed version', { shortcircuit => 1 } ], [ 'log-level|l=s', 'Print messages to STDERR', { default => 'warning' } ], [ 'help', 'Print usage message and exit', { shortcircuit => 1 } ], [ 'verbose-help', 'Print usage message and documentation ', { shortcircuit => 1 } ], ); } # PODNAME: dump-perl-exports # ABSTRACT: A command line utility for describing what a class exports __END__ =pod =encoding UTF-8 =head1 NAME dump-perl-exports - A command line utility for describing what a class exports =head1 VERSION version 0.000067 =head1 SYNOPSIS Here are a few interesting modules to help you understand the output of C. dump-perl-exports POSIX dump-perl-exports Getopt::Long dump-perl-exports Getopt::Long::Descriptive dump-perl-exports Test::More dump-perl-exports Test::Most dump-perl-exports Moose dump-perl-exports Moo =head1 AUTHOR Olaf Alders =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2020 by Olaf Alders. 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 ExportInspector000755001750001751 015261510600 17422 5ustar00olafolaf000000000000App-perlimports-0.000067/tload.t100644001750001751 1074215261510600 20712 0ustar00olafolaf000000000000App-perlimports-0.000067/t/ExportInspector#!perl use strict; use warnings; use lib 'test-data/lib', 't/lib'; use App::perlimports::ExportInspector (); use TestHelper qw( logger ); use Test::More import => [qw( done_testing is_deeply ok subtest )]; use Test::Needs qw( Import::Into Moose Test::Most ); use Test::Warnings (); sub ei { my @log; my $module = shift; return ( App::perlimports::ExportInspector->new( logger => logger( \@log ), module_name => $module, ), \@log ); } # Check ISA here subtest 'Local::MyOwnMoose' => sub { my ($ei) = ei('Local::MyOwnMoose'); is_deeply( $ei->explicit_exports, { after => 'after', around => 'around', augment => 'augment', before => 'before', blessed => 'blessed', confess => 'confess', extends => 'extends', has => 'has', inner => 'inner', isa => 'isa', meta => 'meta', override => 'override', super => 'super', with => 'with', }, 'explicit exports' ); ok( !$ei->is_oo_class, 'is OO class' ); is_deeply( $ei->pkg_isa, ['Moose::Object'], 'class_isa' ); ok( $ei->is_moose_class, 'class with imported Moose' ); }; # Test::Most imports a lot of functions. any() in particular will clash with an # import of List::Util qw( any ). So, Test::Warnings will fail if we try to # import duplicate symbol names in ExportInspector. subtest 'Test::Most' => sub { my ($ei) = ei('Test::Most'); ok( $ei->has_implicit_exports, 'found export' ); ok( $ei->has_explicit_exports, 'found explicit_exports' ); }; subtest 'List::Util' => sub { my ($ei) = ei('List::Util'); # It does override $a and $b, but I'm not sure if that's helpful for our # purposes. is_deeply( $ei->implicit_exports, {}, 'no implicit exports' ); ok( $ei->has_explicit_exports, 'found explicit_exports' ); }; # UsesMoose.pm literally just includes a "use Moose;" subtest 'Local::UsesMoose' => sub { my ($ei) = ei('Local::UsesMoose'); ok( $ei->is_oo_class, 'is oo class' ); ok( !$ei->is_moose_class, 'Not a Moose class' ); ok( $ei->uses_moose, 'uses Moose' ); is_deeply( $ei->class_isa, ['Moose::Object'], 'ISA Moose::Object' ); }; # UsesMoo.pm literally just includes a "use Moo;" subtest 'Local::UsesMoo' => sub { my ($ei) = ei('Local::UsesMoo'); ok( $ei->is_oo_class, 'is oo class' ); ok( !$ei->is_moose_class, 'Not a Moose class' ); is_deeply( $ei->class_isa, ['Moo::Object'], 'ISA Moo::Object' ); }; subtest 'IO::Socket' => sub { my ($ei) = ei('IO::Handle'); ok( !$ei->is_moose_class, 'Not a Moose class' ); is_deeply( $ei->class_isa, ['Exporter'], 'ISA Exporter' ); is_deeply( $ei->at_export, [], 'at_export' ); ok( scalar @{ $ei->at_export_ok }, 'at_export_ok' ); is_deeply( $ei->at_export_fail, [], 'at_export_fail' ); is_deeply( $ei->at_export_tags, [], 'at_export_tags' ); ok( !$ei->has_implicit_exports, 'no implicit_exports' ); ok( scalar keys %{ $ei->explicit_exports }, 'explicit_exports' ); }; subtest 'Local::ViaSubExporter' => sub { my ($ei) = ei('Local::ViaSubExporter'); ok( !$ei->is_moose_class, 'Not a Moose class' ); is_deeply( $ei->class_isa, [], 'no ISA' ); is_deeply( $ei->at_export, [], 'at_export' ); ok( !scalar @{ $ei->at_export_ok }, 'no export_ok' ); is_deeply( $ei->at_export_fail, [], 'no export_fail' ); is_deeply( $ei->at_export_tags, [], 'no export_tags' ); ok( !$ei->has_implicit_exports, 'no implicit_exports' ); is_deeply( $ei->explicit_exports, { bar => 'bar', foo => 'foo', }, 'has some explicit exports' ); }; subtest 'IO::Socket::INET' => sub { my ($ei) = ei('IO::Socket::INET'); ok( !$ei->is_moose_class, 'Not a Moose class' ); is_deeply( $ei->class_isa, ['IO::Socket'], 'ISA IO::Socket' ); is_deeply( $ei->at_export, [], 'at_export' ); is_deeply( $ei->at_export_ok, [], 'at_export_ok' ); is_deeply( $ei->at_export_fail, [], 'at_export_fail' ); is_deeply( $ei->at_export_tags, [], 'at_export_tags' ); ok( $ei->has_implicit_exports, 'no implicit_exports' ); }; subtest 'Local::Explodes' => sub { my ($ei) = ei('Local::Explodes'); ok( $ei->has_fatal_error, 'has_fatal_error' ); }; done_testing(); english-program-name.t100644001750001751 111215261510600 20606 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use lib 't/lib'; use TestHelper qw( doc ); use Test::More import => [qw( done_testing is )]; # GH #97: English exports typeglobs like *PROGRAM_NAME, but a single-slot # import such as $PROGRAM_NAME must be preserved, not expanded. my ($doc) = doc( filename => 'test-data/english-program-name.pl' ); my $expected = <<'EOF'; use strict; use warnings; use English qw( $PROGRAM_NAME ); print "$PROGRAM_NAME\n"; EOF is( $doc->tidied_document, $expected, '$PROGRAM_NAME slot import is preserved, not expanded to *PROGRAM_NAME' ); done_testing(); doc-imports.pl100644001750001751 12415261510600 20607 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data#!perl use strict; use warnings; use Carp qw( confess croak ); use Carp; croak(); env-version.pl100644001750001751 11615261510600 20623 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Env 1.00 qw( $HOME @PATH ); my @copy = @PATH; exceptional.pl100644001750001751 13215261510600 20661 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Carp; use Local::ImportException; exceptional(); croak(); export-tags.pl100644001750001751 23715261510600 20631 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use HTTP::Status qw(:constants); my $pot = HTTP_I_AM_A_TEAPOT; my $big = HTTP_REQUEST_ENTITY_TOO_LARGE; my $what = HTTP_NO_CODE; func-in-use.pl100644001750001751 12615261510600 20502 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use File::Spec::Functions; use lib catdir( qw< t lib > ); func-in-var.pl100644001750001751 21215261510600 20472 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Mojo::Util; my $class = 'Foo'; if ( $class && ( my $path = $INC{ my $file = class_to_path $class} ) ) { } getopt-long.pl100644001750001751 17515261510600 20614 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Getopt::Long qw(:config bundling no_ignore_case); sub thing { GetOptions ("length=i"); } http-status.pl100644001750001751 15215261510600 20650 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use HTTP::Status; my %foo = ( is_error => 1 ); my $is_info = is_info( 100 ); same-import.pl100644001750001751 24415261510600 20607 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; # Both export a tmpdir() use Test::TempDir::Tiny qw( tempdir ); use Path::Tiny qw( path ); my $path = path('foo'); my $dir = tempdir(); release000755001750001751 015261510600 16062 5ustar00olafolaf000000000000App-perlimports-0.000067/xtcpan-changes.t100644001750001751 34415261510600 20717 0ustar00olafolaf000000000000App-perlimports-0.000067/xt/releaseuse strict; use warnings; # this test was generated with Dist::Zilla::Plugin::Test::CPAN::Changes 0.013 use Test::More 0.96 tests => 1; use Test::CPAN::Changes; subtest 'changes_ok' => sub { changes_file_ok('Changes'); }; test2-v0.t100644001750001751 75715261510600 20543 0ustar00olafolaf000000000000App-perlimports-0.000067/t/cpan-modulesuse strict; use warnings; use lib 't/lib'; use App::perlimports::ExportInspector (); use TestHelper qw( logger ); use Test::More import => [qw( done_testing ok )]; use Test::Needs qw( Test2::V0 ); my $ei = App::perlimports::ExportInspector->new( logger => logger( [] ), module_name => 'Test2::V0' ); # This used to throw an exception, because we weren't checking if meta() # returns an object. ok( !$ei->is_oo_class, 'is not OO class' ); done_testing(); preserve-some-padding.t100755001750001751 74615261510600 20771 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!/usr/bin/env perl use strict; use warnings; use lib 't/lib'; use Test::Differences qw( eq_or_diff ); use TestHelper qw( doc ); use Test::More import => [qw( done_testing )]; my ($doc) = doc( filename => 'test-data/preserve-some-padding.pl', tidy_whitespace => 1, ); my $expected = <<'EOF'; use strict; use warnings; use Carp qw( croak verbose ); croak('oof'); EOF eq_or_diff( $doc->tidied_document, $expected, 'list is not padded' ); done_testing(); symbol-as-method-call.t100755001750001751 106015261510600 20674 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use lib 't/lib'; use App::perlimports::Document (); use TestHelper qw( logger ); use Test::More import => [qw( done_testing is )]; use Test::Needs qw( HTML::TableExtract Object::Tap ); my @errors; my $logger = logger( \@errors ); my $doc = App::perlimports::Document->new( filename => 'test-data/symbol-as-method-call.pl', logger => $logger, selection => 'use Object::Tap;', ); is( $doc->tidied_document, 'use Object::Tap qw( $_tap );', 'symbol in method call found' ); done_testing; lint-success.pl100644001750001751 15715261510600 20771 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Perl::Critic::Utils qw( $QUOTE ); my %foo = ( $QUOTE => q{description}, ); perl-version.pl100644001750001751 5015261510600 20752 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use 5.008001; use-constant.pm100644001750001751 243715261510600 21024 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datapackage rfc3339::nonsense; use strict; use warnings; use version; our $VERSION = qv('v1.10.0'); use Carp qw( croak ); use Time::Local qw(timegm); use Scalar::Util; use constant FIRST_IDX => 0; use constant IDX_FORMAT => FIRST_IDX + 1; use constant { IDX_SEP => FIRST_IDX + 2, "IDX_SEP_RE", FIRST_IDX + 3, 'IDX_STR' => 4 * IDX_FORMAT - 0, }; use constant q{IDX_UTIME}, abs(5); sub _parse { my $self; $self = shift if Scalar::Util::blessed $_[0]; my $string = shift; return unless my @tm = $string =~ /(\d{2,4})-(\d{2})-(\d{2})(.)(\d{2}):(\d{2}):(\d{2})/; my $sep = splice( @tm, 3, 1 ); if ($self) { return unless $sep eq $self->[IDX_SEP]; } $tm[1]--; my $gmt = $string =~ m/(?:Z|\+00|\+00:00|\-00:00)$/; return my $utime = $gmt ? timegm( reverse @tm ) : timelocal( reverse @tm ); } sub new { my ( $class, $string ) = @_; confess('somethings not right here') if FIRST_IDX(); my $sep = 'T'; my $sep_re = quotemeta($sep); my $self = bless( [], $class ); @$self[ IDX_SEP, IDX_SEP_RE ] = ( $sep, $sep_re ); $self->[IDX_STR] = $string; croak('bad timestamp') unless my $utime = $string && $self->_parse($string); $self->[IDX_UTIME] = $utime; return $self; } 1; var-in-regex.pl100644001750001751 57115261510600 20661 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; # Borrowed from Perl::Critic::Policy::ValuesAndExpressions::ProhibitMagicNumbers use Perl::Critic::Utils qw( $BACKTICK $PERIOD ); my $UNSIGNED_NUMBER = qr{ \d+ (?: [$PERIOD] \d+ )? # 1, 1.5, etc. | [$PERIOD] \d+ # .3, .7, etc. }xms; my $rule = '12345'; if ( $rule =~ m/$BACKTICK/xms ) { print 'ok'; } via-exporter.pl100644001750001751 24115261510600 20774 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Local::ViaExporter; my $one = foo(); my $two = $foo; my @three = @foo; my %four = %foo; p $one; p $two; p @three; p %four; with-version.pl100644001750001751 57315261510600 21015 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Cpanel::JSON::XS 4.19 qw( encode_json ); use Getopt::Long 2.40 qw(); use LWP::UserAgent 5.00; use Test::Script 1.27 qw( script_compiles script_runs script_stderr_is script_stderr_like ); my $foo = decode_json( { foo => 'bar' } ); my @foo = GetOptions(); script_compiles(); script_runs(); script_stderr_is(); script_stderr_like(); perlimports000755001750001751 015261510600 17655 5ustar00olafolaf000000000000App-perlimports-0.000067/lib/AppCLI.pm100644001750001751 4311215261510600 21003 0ustar00olafolaf000000000000App-perlimports-0.000067/lib/App/perlimportspackage App::perlimports::CLI; use Moo; use utf8; our $VERSION = '0.000067'; use App::perlimports (); use App::perlimports::Config (); use App::perlimports::Document (); use Capture::Tiny qw( capture_stdout ); use Getopt::Long::Descriptive qw( describe_options ); use List::Util qw( uniq ); use Log::Dispatch (); use Path::Iterator::Rule (); use Path::Tiny qw( path ); use Try::Tiny qw( catch try ); use Types::Standard qw( ArrayRef Bool HashRef InstanceOf Object Str ); has _args => ( is => 'ro', isa => HashRef, lazy => 1, builder => '_build_args', ); has _config => ( is => 'ro', isa => InstanceOf [App::perlimports::Config::], lazy => 1, builder => '_build_config', ); has _config_file => ( is => 'ro', isa => Str, lazy => 1, init_arg => 'config', builder => '_build_config_file', ); # off by default has _inplace_edit => ( is => 'ro', isa => Bool, lazy => 1, default => sub { my $self = shift; return defined $self->_opts->inplace_edit ? $self->_opts->inplace_edit : 0; }, ); has _json => ( is => 'ro', isa => Bool, lazy => 1, default => sub { my $self = shift; return defined $self->_opts->json ? $self->_opts->json : 0; }, ); has _lint => ( is => 'ro', isa => Bool, lazy => 1, default => sub { my $self = shift; return defined $self->_opts->lint ? $self->_opts->lint : 0; }, ); has _opts => ( is => 'ro', isa => InstanceOf ['Getopt::Long::Descriptive::Opts'], lazy => 1, default => sub { $_[0]->_args->{opts} }, ); # off by default has _quiet => ( is => 'ro', isa => Bool, lazy => 1, default => sub { my $self = shift; return defined $self->_opts->quiet ? $self->_opts->quiet : 0; }, ); # off by default has _read_stdin => ( is => 'ro', isa => Bool, lazy => 1, default => sub { my $self = shift; return defined $self->_opts->read_stdin ? $self->_opts->read_stdin : defined $self->_config->{read_stdin} ? $self->_config->{read_stdin} : 0; }, ); has _usage => ( is => 'ro', isa => Object, lazy => 1, default => sub { $_[0]->_args->{usage} }, ); with 'App::perlimports::Role::Logger'; sub _build_args { my ( $opt, $usage ) = describe_options( 'perlimports %o', [ 'filename|f=s', 'A file you would like to run perlimports on. Alternatively, just provide a list of one or more file names without a named parameter as the last arguments to this script: perlimports file1 file2 file3' ], [], [ 'config-file=s', 'Path to a perlimports config file. If this parameter is not supplied, we will look for a file called perlimports.toml or .perlimports.toml in the current directory and then look for a perlimports.toml in XDG_CONFIG_HOME (usually something like $HOME/.config/perlimports/perlimports.toml). This behaviour can be disabled via --no-config-file' ], [], [ 'create-config-file=s', 'Create a sample config file using the supplied name and then exit.', { shortcircuit => 1 } ], [], [ 'ignore-modules=s', 'Comma-separated list of modules to ignore.' ], [], [ 'ignore-modules-pattern=s', 'Regular expression that matches modules to ignore.' ], [], [ 'cache!', '(Experimental and currently discouraged.) Cache some objects in order to speed up subsequent runs. Defaults to no cache.', ], [], [ 'ignore-modules-filename=s', 'Path to file listing modules to ignore. One per line.' ], [], [ 'ignore-modules-pattern-filename=s', 'Path to file listing regular expressions that matches modules to ignore. One per line.' ], [], [ 'json', '(Experimental) Emit linting results as JSON rather than plain text' ], [], [ 'never-export-modules=s', 'Comma-separated list of modules which do not export symbols.' ], [], [ 'never-export-modules-filename=s', q{Path to file listing modules which don't export symbols. One per line.} ], [], [ 'inplace-edit|i', 'Edit the file in place.' ], [], [ 'libs=s', 'Comma-separated list of library paths to include (eg --libs lib,t/lib,dev/lib)', ], [], [ 'lint', 'Act as a linter only. Do not edit any files.', ], [], [ 'quiet|q', 'Suppress the " OK" summary and console log output.', ], [], [ 'no-config-file', 'Do not look for a perlimports config file.' ], [], [ 'indent=i', 'Indent for multiline qw() lists. Default: perltidy -i value', ], [], [ 'pad-brackets!', 'Pad square brackets in import lists: [ qw( foo ) ] vs [qw( foo )]. Defaults to false', ], [], [ 'padding!', 'Pad imports: qw( foo bar ) vs qw(foo bar). Defaults to true', ], [], [ 'read-stdin', 'Read statements to process from STDIN rather than the supplied file.', ], [], [ 'sort!', '(Experimental) Sort contiguous include statements. Defaults to false.', ], [], [ 'preserve-duplicates!', 'Preserve duplicate use statements for the same module. This is the default behaviour. You are encouraged to disable it.', ], [], [ 'preserve-require!', 'Preserve require statements rather than translating them to "use Module ();". This is the default behaviour.', ], [], [ 'preserve-unused!', 'Preserve use statements for modules which appear to be unused. This is the default behaviour. You are encouraged to disable it.', ], [], [ 'range-begin=i', 'Experimental. First line of range to tidy or lint. Mostly useful for editors.', ], [], [ 'range-end=i', 'Experimental. Last line of range to tidy or lint. Mostly useful for editors.', ], [], [ 'tidy-whitespace!', 'Reformat use statements even when changes are only whitespace. This is the default behaviour.', ], [], [], [ 'version', 'Print installed version', { shortcircuit => 1 } ], [ 'log-level|l=s', 'Print messages to STDERR', ], [ 'log-filename=s', 'Log messages to file rather than STDERR', ], [ 'help', 'Print usage message and exit', { shortcircuit => 1 } ], [ 'verbose-help', 'Print usage message and documentation ', { shortcircuit => 1 } ], ); return { opts => $opt, usage => $usage, }; } sub _build_config { my $self = shift; my %config; if ( !$self->_opts->no_config_file && $self->_config_file ) { %config = %{ $self->_read_config_file }; # The Bool type provided by Types::Standard doesn't seem to like # JSON::PP::Boolean for my $key ( keys %config ) { my $maybe_bool = $config{$key}; my $ref = ref $maybe_bool; next unless $ref; if ( $ref eq 'JSON::PP::Boolean' || $ref eq 'Types::Serializer::Boolean' ) { $config{$key} = $$maybe_bool ? 1 : 0; } } } my @config_options = qw( cache ignore_modules_filename ignore_modules_pattern indent log_filename log_level never_export_modules_filename pad_brackets padding preserve_duplicates preserve_require preserve_unused sort tidy_whitespace ); my @config_option_lists = ( 'ignore_modules', 'libs', 'never_export_modules' ); my %args = map { $_ => $self->_opts->$_ } grep { defined $self->_opts->$_ } @config_options; for my $list (@config_option_lists) { my $val = $self->_opts->$list; if ( defined $val ) { $args{$list} = [ split m{,}, $val ]; } } return App::perlimports::Config->new( %config, %args ); } sub _build_config_file { my $self = shift; if ( $self->_opts->config_file ) { if ( !-e $self->_opts->config_file ) { die $self->_opts->config_file . ' not found'; } return $self->_opts->config_file; } my @filenames = ( 'perlimports.toml', '.perlimports.toml', ); for my $name (@filenames) { return $name if -e $name; } require File::XDG; my $xdg_config = File::XDG->new( name => 'perlimports', api => 1 ); my $file = $xdg_config->config_home->child( $filenames[0] ); return -e $file ? "$file" : q{}; } sub _read_config_file { my $self = shift; require TOML::Tiny; my $config = TOML::Tiny::from_toml( path( $self->_config_file )->slurp ); return $config || {}; } ## no critic (Subroutines::ProhibitExcessComplexity) sub run { my $self = shift; my $opts = $self->_opts; ( print $VERSION, "\n" ) && return 0 if $opts->version; ( print $self->_usage->text ) && return 0 if $opts->help; if ( $opts->verbose_help ) { require Pod::Usage; ## no perlimports my $fh = \*STDOUT; Pod::Usage::pod2usage( ( { -exitval => 'NOEXIT', -message => $self->_usage->text, -output => $fh, } ) ); return 0; } if ( $opts->create_config_file ) { my $exit_code = 0; try { App::perlimports::Config->create_config( $opts->create_config_file ); } catch { print STDERR $_, "\n"; $exit_code = 1; }; return $exit_code; } my $input; my $selection; my $tmp_file; if ( $self->_read_stdin ) { ## no critic (Variables::RequireInitializationForLocalVars) local $/; $input = <>; if ( $opts->range_begin && $opts->range_end ) { $tmp_file = Path::Tiny->tempfile('perlimportsXXXXXXXX'); $tmp_file->spew($input); my @lines = split( qr{\n}, $input ); my $end = $opts->range_end; if ( $end > scalar @lines + 1 ) { $end = scalar @lines + 1; } $selection = join "\n", @lines[ $opts->range_begin - 1 .. $end - 1 ]; } else { $selection = $input; } } unshift @INC, @{ $self->_config->libs }; my $logger = $self->_has_logger ? $self->logger : Log::Dispatch->new( outputs => [ $self->_config->log_filename # --quiet only quiets the console (STDERR). A log file (configured # via --log-filename or the config file) keeps its log level. ? [ 'File', binmode => ':encoding(UTF-8)', filename => $self->_config->log_filename, min_level => $self->_config->log_level, mode => '>>', newline => 1, ] : [ 'Screen', # --quiet suppresses noisy info/notice console output (e.g. # the 🚀/📦 progress lines) but must still let genuine # warnings and errors through -- including --lint failure # diagnostics and --json output, which are logged at the # error level. See GH #163. min_level => $self->_quiet ? 'warning' : $self->_config->log_level, newline => 1, stderr => 1, utf8 => 1, ] ] ); if ( $self->_json && !$self->_lint ) { $logger->error('--json can only be used with --lint'); return 1; } if ( $self->_lint && $self->_inplace_edit ) { $logger->error('Cannot lint if inplace edit has been enabled'); return 1; } if ( ( $opts->range_begin && !$opts->range_end ) || ( $opts->range_end && !$opts->range_begin ) ) { $logger->error('You must supply both range_begin and range_end'); return 1; } if ( $opts->range_begin && !$self->_read_stdin ) { $logger->error( 'You must specify --read-stdin if you provide a range'); return 1; } my @files = $tmp_file ? ("$tmp_file") : _filter_paths( $opts->filename ? $opts->filename : (), @ARGV ); unless (@files) { $logger->error(q{Mandatory parameter 'filename' missing}); $logger->error( $self->_usage->text ); return 1; } my %doc_args = ( cache => $self->_config->cache, @{ $self->_config->ignore } ? ( ignore_modules => $self->_config->ignore ) : (), @{ $self->_config->ignore_pattern } ? ( ignore_modules_pattern => $self->_config->ignore_pattern ) : (), @{ $self->_config->never_export } ? ( never_export_modules => $self->_config->never_export ) : (), indent => $self->_config->indent, json => $self->_json, lint => $self->_lint, logger => $logger, pad_brackets => $self->_config->pad_brackets, padding => $self->_config->padding, preserve_duplicates => $self->_config->preserve_duplicates, preserve_require => $self->_config->preserve_require, preserve_unused => $self->_config->preserve_unused, sort => $self->_config->sort, tidy_whitespace => $self->_config->tidy_whitespace, $selection ? ( selection => $selection ) : (), ); my $exit_code = 0; FILENAME: foreach my $filename (@files) { if ( !path($filename)->is_file ) { $logger->error("$filename does not appear to be a file"); $logger->error( $self->_usage->text ); return 1; } $logger->notice( '🚀 Starting file: ' . $filename ); my $pi_doc = App::perlimports::Document->new( %doc_args, filename => $filename, ); # Capture STDOUT here so that 3rd party code printing to STDOUT doesn't get # piped back into vim. my ( $stdout, $tidied, $linter_success ); if ( $self->_lint ) { ( $stdout, $linter_success ) = capture_stdout( sub { return $pi_doc->linter_success; } ); if ( $linter_success && !$self->_json && !$self->_quiet ) { # The lint *result* goes to STDOUT so that STDERR is reserved # for diagnostics and log messages. This keeps a clean run # silent on STDERR, which matters for tools (e.g. precious) # that treat any STDERR output as a failure. See GH #163. print STDOUT $filename . " OK\n"; } elsif ( !$linter_success ) { $exit_code = 1; } next FILENAME; } ( $stdout, $tidied ) = capture_stdout( sub { return $pi_doc->tidied_document; } ); if ( $self->_read_stdin ) { print STDOUT $tidied; } elsif ( $self->_inplace_edit ) { # append() with truncate, because spew() can change file permissions path($filename)->append( { truncate => 1 }, $tidied ); } else { print STDOUT $tidied; } } return $exit_code; } ## use critic sub _filter_paths { my @paths = @_; my @files; my $rule = Path::Iterator::Rule->new->or( Path::Iterator::Rule->new->perl_module, Path::Iterator::Rule->new->perl_script, Path::Iterator::Rule->new->perl_test, ); foreach my $path (@paths) { if ( -d $path ) { my $iter = $rule->iter($path); while ( defined( my $file = $iter->() ) ) { push @files, $file; } } else { push @files, $path; } } return uniq @files; } 1; =pod =encoding UTF-8 =head1 NAME App::perlimports::CLI - CLI arg parsing for C =head1 VERSION version 0.000067 =head1 DESCRIPTION This module isn't really meant to provide a public interface. =head2 run() The method which will do the argument parsing and print out the results. =head1 AUTHOR Olaf Alders =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2020 by Olaf Alders. 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: CLI arg parsing for C indirect-object-syntax.t100644001750001751 371215261510600 21173 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use lib 't/lib', 'test-data/lib'; use Test::Differences qw( eq_or_diff ); use TestHelper qw( doc ); use Test::More import => [qw( done_testing is subtest )]; my ($doc) = doc( filename => 'test-data/indirect-object-syntax.pl', preserve_unused => 0, tidy_whitespace => 0, ); # [ module name, is it detected as used?, description ] my @cases = ( [ 'File', 1, 'indirect object syntax: new File $path, $data' ], [ 'Database', 1, 'indirect object syntax: connect Database $dsn' ], [ 'JSON::PP', 1, 'arrow method call still detected: JSON::PP->new' ], [ 'Unused', 0, 'use statement is not indirect object usage' ], [ 'Forbidden', 0, 'no statement is not indirect object usage' ], [ 'Deferred', 0, 'require statement is not indirect object usage' ], [ 'Ignored', 0, 'package statement is not indirect object usage' ], [ 'Widget', 0, 'sub declaration is not indirect object usage' ], [ 'Nonexistent', 0, 'module which never appears is not used' ], ); subtest 'indirect object syntax detection' => sub { for my $case (@cases) { my ( $module, $expected, $desc ) = @{$case}; is( ( $doc->_is_used_fully_qualified($module) ? 1 : 0 ), $expected, $desc ); } }; # A module used only via indirect object syntax must be preserved in the # rewritten document rather than removed as unused. subtest 'used module is preserved end to end' => sub { my ($preserved) = doc( filename => 'test-data/indirect-object-syntax-preserved.pl', preserve_unused => 0, tidy_whitespace => 0, ); my $expected = <<'EOF'; use strict; use warnings; use lib 'test-data/lib'; use Local::NoImport (); my $obj = new Local::NoImport; EOF eq_or_diff( $preserved->tidied_document, $expected, 'use Local::NoImport preserved when used via indirect object syntax' ); }; done_testing; args-in-import.t100644001750001751 24115261510600 21047 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Test2::V0 '-no_pragmas' => 1, '!meta', 'diag', 'done_testing', 'is'; my $foo = 'foo'; is($foo, 'foo'); diag $foo; done_testing; cast-in-regex.pl100644001750001751 15215261510600 21016 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Lingua::EN::Inflect; my $thing = 'B'; if ( $thing =~ m{ \A b }x ) { ... } filter-paths000755001750001751 015261510600 20277 5ustar00olafolaf000000000000App-perlimports-0.000067/test-datafoo100755001750001751 715261510600 21065 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/filter-paths#!perl func-in-use-2.pl100644001750001751 14315261510600 20640 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Mojo::File qw(curfile); use lib curfile->sibling('lib')->to_string; hash-in-regex.pl100644001750001751 15315261510600 21010 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Config; sub foo { return $INC{'Foo.pm'} =~ /^\Q$Config{sitelibexp}/; } inner-package.pl100644001750001751 32215261510600 21053 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use HTTP::Status qw( is_success is_redirect ); package Foo; sub test_code { return ::is_success( shift ); } package main; print Foo::test_code(200); print ::is_redirect(301); interpolation.pl100644001750001751 14415261510600 21240 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Encode; my $code = 'foo'; warn "-- @{[encode 'UTF-8', $code]}\n\n"; messy-imports.pl100644001750001751 54715261510600 21213 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; # Use this file to generate some before/after examples in Pod and also test # Moose type imports. use Local::MooseTypeLibrary qw( HashRef ArrayRef Object Str Bool Maybe CodeRef FileHandle RegexpRef ); is_HashRef(); ArrayRef(); Object(); my $ref = \&is_Str(); Bool(); Maybe(); CodeRef(); FileHandle(); RegexpRef(); is_RegexpRef(); more-find-bin.pl100755001750001751 11115261510600 20774 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data#!/usr/bin/env perl use FindBin; use lib "$FindBin::Bin/../../../lib"; nested-quotes.pl100644001750001751 20115261510600 21143 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Path::Tiny; my $thing = qq{content="${ \( path('one/two.txt')->stringify )}"}; print "$thing\n"; perlimports.toml100644001750001751 224415261510600 21314 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data# Valid log levels are: # debug, info, notice, warning, error, critical, alert, emergency # critical, alert and emergency are not currently used. # # Please use boolean values in this config file. Negated options (--no-*) are # not permitted here. Explicitly set options to true or false. # # Some of these values deviate from the regular perlimports defaults. In # particular, you're encouraged to leave preserve_duplicates and # preserve_unused disabled. cache = false # setting this to true is currently discouraged ignore_modules = [] ignore_modules_filename = "" ignore_modules_pattern = "" # regex like "^(Foo|Foo::Bar)" ignore_modules_pattern_filename = "test-data/ignore-modules-pattern.txt" # indent = 4 # default: perltidy -i libs = ["lib", "t/lib"] log_level = "warn" never_export_modules = [] never_export_modules_filename = "" pad_brackets = false padding = true preserve_duplicates = false preserve_unused = false tidy_whitespace = true sort-includes.pl100644001750001751 5315261510600 21123 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use Foo; use Bar; use Baz; 1; test-html-lint.t100644001750001751 15015261510600 21063 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Test::HTML::Lint; use Test::More; html_ok(''); done_testing(); unnest-quotes.pl100644001750001751 11715261510600 21203 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Carp qw( croak ); my $green = "█"; croak(); Local000755001750001751 015261510600 17475 5ustar00olafolaf000000000000App-perlimports-0.000067/test-data/libMaxA.pm100644001750001751 25015261510600 20776 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/lib/Localpackage Local::MaxA; use strict; use warnings; use Exporter qw( import ); our @EXPORT_OK = qw( max a_only ); sub max { return 'A' } sub a_only { return 'a' } 1; MaxB.pm100644001750001751 25015261510600 20777 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/lib/Localpackage Local::MaxB; use strict; use warnings; use Exporter qw( import ); our @EXPORT_OK = qw( max b_only ); sub max { return 'B' } sub b_only { return 'b' } 1; Sort.pm100644001750001751 44115261510600 21101 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/lib/Localpackage Local::Sort; use strict; use warnings; use Exporter qw( import ); our $AAA = 1; our $AAA_2FA = 1; our @BBB = (); our %CCC = (); sub bbb { } sub bba_2fa { } our @EXPORT_OK = ( '$AAA', '$AAA_2FA', 'bbb', 'bba_2fa', '@BBB', '%CCC', ); 1; long-test-more.pl100644001750001751 56215261510600 21231 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Test::More import => [qw( can_ok cmp_ok diag done_testing is isa_ok isnt like note ok pass subtest unlike )]; can_ok( 'Foo', 'bar' ); cmp_ok( 1, '==', 1 ); diag('hi'); is( 1, 1 ); isa_ok( \1, 'SCALAR' ); isnt( 1, 2 ); like( 'a', qr/a/ ); note('hi'); ok(1); pass('ok'); subtest 'x' => sub { ok(1) }; unlike( 'a', qr/b/ ); done_testing(); double-quoted-q.pl100644001750001751 6015261510600 21335 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use List::Util; "q"; foo.t100644001750001751 015261510600 21315 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/filter-pathsfully-qualified.pl100644001750001751 106215261510600 21465 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use lib 'test-data/lib'; use Encode; ## no critic (Some::Policy) use List::Util; use Carp qw( croak ); use HTTP::Tiny; use JSON::PP; use Local::ViaExporter (); use Test::Builder (); use POSIX (); my @foo = List::Util::uniq( 0 .. 10 ); my $bar = encode_json( {} ); my $hr = JSON::PP->new; local *HTTP::Tiny::new = sub { 1 }; sub foo { croak() } sub some_func { local $Test::Builder::Level = $Test::Builder::Level + 1; } sub ok { return @POSIX::EXPORT_OK; } sub also_ok { return %Local::ViaExporter::foo; } ignore-modules.txt100644001750001751 2715261510600 21466 0ustar00olafolaf000000000000App-perlimports-0.000067/test-dataData::Printer Git::Sub After.pm100644001750001751 24215261510600 21212 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/lib/Localpackage Local::After; use Moose; use List::AllUtils qw( any uniq ); my @foo = uniq { 1..10 }; after run => sub { my @foo = uniq ( 1..9 ) }; sub run { 1; } 1; Round.pm100644001750001751 34615261510600 21245 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/lib/Localpackage Local::Round; use parent 'Exporter'; use strict; use warnings; use Math::Round qw( nearest ); our @EXPORT_OK = qw(round); sub round { my ( $number, $places ) = @_; return nearest( 10**-$places, $number ); } 1; lookalike-words.pl100644001750001751 11115261510600 21451 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause Carp; my $foo = "this will not croak"; my $bar = <<"EOF" croak() EOF preserve-spaces.pl100644001750001751 14215261510600 21456 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Carp (); use HTTP::Status qw ( HTTP_FOUND ); print HTTP_FOUND; use-and-require.pl100644001750001751 15515261510600 21361 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; require IO::File; use Fcntl; { my $fh; sysopen( $fh, 'foo', O_RDONLY ) } var-in-hash-key.pl100644001750001751 14215261510600 21252 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Perl::Critic::Utils; my %foo = ( $QUOTE => q{description}, ); Config.pm100644001750001751 1512715261510600 21606 0ustar00olafolaf000000000000App-perlimports-0.000067/lib/App/perlimportspackage App::perlimports::Config; use Moo; use MooX::StrictConstructor; our $VERSION = '0.000067'; use List::Util qw( uniq ); use Path::Tiny qw( path ); use Types::Common::Numeric qw( PositiveOrZeroInt ); use Types::Standard qw( ArrayRef Bool HashRef InstanceOf Str ); has cache => ( is => 'ro', isa => Bool, lazy => 1, default => 0, ); has _ignore_modules => ( is => 'ro', isa => ArrayRef, init_arg => 'ignore_modules', lazy => 1, default => sub { [] }, ); has _ignore_modules_filename => ( is => 'ro', isa => Str, init_arg => 'ignore_modules_filename', predicate => '_has_ignore_modules_filename', ); has _ignore_modules_pattern => ( is => 'ro', isa => ArrayRef [Str], init_arg => 'ignore_modules_pattern', lazy => 1, predicate => '_has_ignore_modules_pattern', coerce => sub { return ref $_[0] ? $_[0] : [ $_[0] ] }, ); has _ignore_modules_pattern_filename => ( is => 'ro', isa => Str, init_arg => 'ignore_modules_pattern_filename', predicate => '_has_ignore_modules_pattern_filename', ); has ignore => ( is => 'ro', isa => ArrayRef, lazy => 1, builder => '_build_ignore', ); has ignore_pattern => ( is => 'ro', isa => ArrayRef, lazy => 1, builder => '_build_ignore_pattern', ); has libs => ( is => 'ro', isa => ArrayRef, lazy => 1, default => sub { [] }, ); has log_filename => ( is => 'ro', isa => Str, lazy => 1, default => sub { q{} }, ); has log_level => ( is => 'ro', isa => Str, lazy => 1, default => sub { 'error' }, ); has _never_export_modules => ( is => 'ro', isa => ArrayRef, init_arg => 'never_export_modules', lazy => 1, default => sub { [] }, ); has _never_export_modules_filename => ( is => 'ro', isa => Str, init_arg => 'never_export_modules_filename', predicate => '_has_never_export_modules_filename', ); has never_export => ( is => 'ro', isa => ArrayRef, lazy => 1, builder => '_build_never_export', ); has _perltidy_options => ( is => 'ro', isa => HashRef, lazy => 1, default => sub { require Perl::Tidy; ## no perlimports my %opts; Perl::Tidy::perltidy( dump_options => \%opts, dump_options_type => 'full', argv => q{}, ); return \%opts; }, ); has indent => ( is => 'ro', isa => PositiveOrZeroInt, lazy => 1, default => sub { return $_[0]->_perltidy_options->{'indent-columns'} // 4; }, ); has pad_brackets => ( is => 'ro', isa => Bool, lazy => 1, default => 0, ); has padding => ( is => 'ro', isa => Bool, lazy => 1, default => 1, ); has preserve_duplicates => ( is => 'ro', isa => Bool, lazy => 1, default => 1, ); has preserve_require => ( is => 'ro', isa => Bool, lazy => 1, default => 1, ); has preserve_unused => ( is => 'ro', isa => Bool, lazy => 1, default => 1, ); has sort => ( is => 'ro', isa => Bool, lazy => 1, default => 0, ); has tidy_whitespace => ( is => 'ro', isa => Bool, lazy => 1, default => 1, ); with 'App::perlimports::Role::Logger'; sub _build_ignore { my $self = shift; return $self->_aggregate( $self->_ignore_modules, '_ignore_modules_filename' ); } sub _build_ignore_pattern { my $self = shift; return $self->_aggregate( $self->_ignore_modules_pattern, '_ignore_modules_pattern_filename' ); } sub _build_never_export { my $self = shift; return $self->_aggregate( $self->_never_export_modules, '_never_export_modules_filename' ); } sub _aggregate { my $self = shift; my $list = shift || []; my $accessor = shift; my $predicate = '_has' . $accessor; return $list if !$self->$predicate; my $filename = $self->$accessor; return $list if !$filename; # could be an empty string die "File $filename not found" unless -e $filename; return [ uniq( @{$list}, path($filename)->lines( { chomp => 1 } ) ) ]; } sub create_config { shift; # $class my $filename = shift; if ( -e $filename ) { die "$filename already exists"; } my @toml = ; path($filename)->spew(@toml); } 1; # ABSTRACT: Generic configuration options for C =pod =encoding UTF-8 =head1 NAME App::perlimports::Config - Generic configuration options for C =head1 VERSION version 0.000067 =head1 DESCRIPTION This module isn't really meant to provide a public interface. =head2 create_config( $filename ) This class method creates a L config file at the provided filename. Dies if the file already exists. =head1 AUTHOR Olaf Alders =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2020 by Olaf Alders. 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 __DATA__ # Valid log levels are: # debug, info, notice, warning, error, critical, alert, emergency # critical, alert and emergency are not currently used. # # Please use boolean values in this config file. Negated options (--no-*) are # not permitted here. Explicitly set options to true or false. # # Some of these values deviate from the regular perlimports defaults. In # particular, you're encouraged to leave preserve_duplicates and # preserve_unused disabled. cache = false # setting this to true is currently discouraged ignore_modules = [] ignore_modules_filename = "" ignore_modules_pattern = "" # regex like "^(Foo|Foo::Bar)" ignore_modules_pattern_filename = "" # indent = 4 # default: perltidy -i libs = ["lib", "t/lib"] log_filename = "" log_level = "warn" never_export_modules = [] never_export_modules_filename = "" pad_brackets = false padding = true preserve_duplicates = false preserve_require = true preserve_unused = false sort = false tidy_whitespace = true Sorter.pm100644001750001751 1407015261510600 21653 0ustar00olafolaf000000000000App-perlimports-0.000067/lib/App/perlimportspackage App::perlimports::Sorter; use Moo; use utf8; use App::perlimports::Annotations (); use PPI::Document (); use Types::Standard qw( Str ); our $VERSION = '0.000067'; with 'App::perlimports::Role::Logger'; has _source => ( is => 'ro', isa => Str, init_arg => 'source', required => 1, ); sub sorted_document { my $self = shift; my $source = $self->_source; my $doc = PPI::Document->new( \$source ); return $source unless $doc; $doc->index_locations; my $found = $doc->find( sub { $_[1]->isa('PPI::Statement::Include') } ) || []; return $source unless @{$found}; my $annotations = App::perlimports::Annotations->new( ppi_document => $doc, logger => $self->logger, ); # Each element retains its trailing "\n"; line N is $lines[N - 1]. my @lines = split /(?<=\n)/, $source; my @units = map { _unit( $_, $annotations, \@lines ) } @{$found}; my @sections = _sections( \@units, \@lines ); # Rewrite bottom-up so earlier line numbers stay valid across splices. my $changed = 0; for my $section ( reverse @sections ) { my ( $new_text, $section_changed ) = _reorder_section( $section, \@lines ); next unless $section_changed; $changed = 1; my $first = $section->[0]{lead}; my $end = $section->[-1]{end}; splice @lines, $first - 1, $end - $first + 1, $new_text; } return $changed ? join( q{}, @lines ) : $source; } # Build a unit hashref describing one include and the source lines it owns. sub _unit { my ( $node, $annotations, $lines ) = @_; my $start = $node->line_number; my $newlines = () = $node->content =~ /\n/g; my $end = $start + $newlines; # Absorb full-line comments directly above the statement (no blank line # can appear here: a blank line would have ended the section). my $lead = $start; while ( $lead - 1 >= 1 && $lines->[ $lead - 2 ] =~ /\A\s*#/ ) { $lead--; } return { lead => $lead, start => $start, end => $end, class => _classify( $node, $annotations ), key => lc( $node->module ), }; } sub _classify { my ( $node, $annotations ) = @_; return 'hoist' if $node->pragma; return 'hoist' if $node->version; return 'anchor' if $annotations->is_ignored($node); return 'anchor' if $node->type eq 'no'; return 'anchor' unless length $node->module; return 'sortable'; } # Group units into contiguous sections. sub _sections { my ( $units, $lines ) = @_; my @sections; my @current; for my $u ( @{$units} ) { if (@current) { my $prev = $current[-1]; my $same = 1; for my $ln ( $prev->{end} + 1 .. $u->{start} - 1 ) { unless ( $lines->[ $ln - 1 ] =~ /\A\s*#/ ) { $same = 0; last; } } if ( !$same ) { push @sections, [@current]; @current = (); } } push @current, $u; } # @current always holds at least the final unit: sorted_document returns # early when there are no includes, so this loop always runs at least once. push @sections, [@current]; return @sections; } # Return ( $new_section_text, $changed_bool ) for one section. sub _reorder_section { my ( $section, $lines ) = @_; # If any two units share or overlap a physical line, reordering would # duplicate or merge the user's source. We cannot safely sort statements # that share a line, so leave the whole section byte-identical. for my $i ( 0 .. $#{$section} - 1 ) { return ( q{}, 0 ) if $section->[$i]{end} >= $section->[ $i + 1 ]{lead}; } my @hoist = grep { $_->{class} eq 'hoist' } @{$section}; my @modules = grep { $_->{class} ne 'hoist' } @{$section}; my @sortable = sort { $a->{key} cmp $b->{key} } grep { $_->{class} eq 'sortable' } @modules; my @ordered_modules; my $si = 0; for my $u (@modules) { push @ordered_modules, $u->{class} eq 'anchor' ? $u : $sortable[ $si++ ]; } my $text_of = sub { my $u = shift; return join q{}, @{$lines}[ $u->{lead} - 1 .. $u->{end} - 1 ]; }; # Normalize each unit's text to end in exactly one newline so reordered # units never jam onto one line when the final unit lacked a trailing "\n". my $rendered = sub { my $text = $text_of->(shift); $text =~ s/\n?\z/\n/; return $text; }; my $new_text = q{}; $new_text .= $rendered->($_) for @hoist; $new_text .= "\n" if @hoist && @ordered_modules; # set pragmas off $new_text .= $rendered->($_) for @ordered_modules; my $old_text = join q{}, map { $text_of->($_) } @{$section}; # Preserve the section's original trailing-newline state: if the source # had no final "\n", do not add bytes the user did not have. $new_text =~ s/\n\z// unless $old_text =~ /\n\z/; return ( $new_text, $new_text ne $old_text ); } 1; # ABSTRACT: Sort a document's include statements __END__ =pod =encoding UTF-8 =head1 NAME App::perlimports::Sorter - Sort a document's include statements =head1 VERSION version 0.000067 =head1 SYNOPSIS my $sorter = App::perlimports::Sorter->new( logger => $logger, source => $source_string, ); my $sorted = $sorter->sorted_document; =head2 sorted_document Returns the source with each contiguous section of C/C statements sorted per the C<--sort> rules. Pragmas and version requires are hoisted, C<## no perlimports> and other anchors keep their slots, and attached comments travel with their include. Returns the original source unchanged when there is nothing to sort. =head1 AUTHOR Olaf Alders =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2020 by Olaf Alders. 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 preserve-include-comments.t100644001750001751 534715261510600 21707 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!perl # Comments embedded in an include statement (e.g. a "## no critic" # annotation) must not be discarded when perlimports rewrites the # statement. See https://github.com/perl-ide/App-perlimports/issues/50. use strict; use warnings; use lib 'test-data/lib', 't/lib'; use App::perlimports::Document (); use TestHelper qw( logger ); use Test::More import => [qw( done_testing is like subtest )]; sub tidied { my ($text) = @_; my @log; my $doc = App::perlimports::Document->new( logger => logger( \@log ), ppi_document => PPI::Document->new( \$text ), filename => 'none', preserve_unused => 0, ); return $doc->tidied_document; } subtest 'comment between module name and import list is preserved' => sub { my $got = tidied(<<'EOT'); use List::Util ## no critic (SomePolicy) qw( first max ); first { $_ } (1); max( 1, 2 ); EOT is( $got, <<'EOT', 'comment re-attached as a trailing side comment' ); use List::Util qw( first max ); ## no critic (SomePolicy) first { $_ } (1); max( 1, 2 ); EOT }; subtest 'comment already trailing the statement is preserved' => sub { my $got = tidied(<<'EOT'); use List::Util qw( first max ); ## no critic (SomePolicy) first { $_ } (1); max( 1, 2 ); EOT is( $got, <<'EOT', 'trailing comment kept in place' ); use List::Util qw( first max ); ## no critic (SomePolicy) first { $_ } (1); max( 1, 2 ); EOT }; subtest 'comment preserved when rewritten to an empty import list' => sub { my $got = tidied(<<'EOT'); use POSIX ## no critic (SomePolicy) (); POSIX::floor(1.5); EOT is( $got, <<'EOT', 'comment kept on a "use Module ();" rewrite' ); use POSIX (); ## no critic (SomePolicy) POSIX::floor(1.5); EOT }; subtest 'comment nested inside the import list parens is preserved' => sub { my $got = tidied(<<'EOT'); use POSIX ( ## no critic (SomePolicy) 'floor', 'ceil' ); floor(1.5); ceil(2.5); EOT is( $got, <<'EOT', 'comment nested in "( ... )" re-attached as trailing' ); use POSIX qw( ceil floor ); ## no critic (SomePolicy) floor(1.5); ceil(2.5); EOT }; subtest 'comment preserved and indent kept on a wrapped import list' => sub { my $got = tidied(<<'EOT'); use POSIX ## no critic (SomePolicy) qw( floor ceil strftime setlocale LC_ALL INT_MAX INT_MIN DBL_MAX pow ); floor(1); ceil(1); strftime(q{}); setlocale(LC_ALL); pow( 2, 3 ); my @x = ( INT_MAX, INT_MIN, DBL_MAX ); EOT like( $got, qr/\);\s+## no critic \(SomePolicy\)\n/, 'comment appended after the closing ");" of a wrapped list', ); like( $got, qr/\n {4}ceil\n/, 'perlimports 4-space indent is not re-flowed by perltidy', ); }; done_testing(); config-in-import.pl100644001750001751 20315261510600 21526 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Getopt::Long qw( :config no_auto_abbrev no_ignore_case bundling pass_through ); env-interpolated.pl100644001750001751 11115261510600 21623 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Env qw( HOME ); print "home is $HOME\n"; Foo.pl100644001750001751 015261510600 21425 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/filter-pathsFoo.pm100644001750001751 015261510600 21426 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/filter-pathsfoo.py100644001750001751 015261510600 21502 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/filter-pathsSTDOUT.pm100644001750001751 16215261510600 21174 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/lib/Localpackage Local::STDOUT; use strict; use warnings; BEGIN { print 'perlimports should trap this message' } 1; original-imports.pl100644001750001751 12215261510600 21644 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Carp; use Data::Dumper qw( Dumper ); use POSIX (); Include.pm100644001750001751 7521315261510600 21766 0ustar00olafolaf000000000000App-perlimports-0.000067/lib/App/perlimportspackage App::perlimports::Include; use Moo; our $VERSION = '0.000067'; ## no critic (Bangs::ProhibitDebuggingModules) use Data::Dumper qw( Dumper ); use List::Util qw( any none uniq ); use Memoize qw( flush_cache memoize ); use MooX::StrictConstructor; use PPI::Document (); use PPIx::Utils::Classification qw( is_function_call is_perl_builtin ); use Ref::Util qw( is_plain_arrayref is_plain_hashref ); use Sub::HandlesVia; use Try::Tiny qw( catch try ); use Types::Standard qw(ArrayRef Bool HashRef InstanceOf Int Maybe Object Str); with 'App::perlimports::Role::Logger'; memoize('is_function_call'); sub BUILD { flush_cache('is_function_call'); } # this is a catalog of the @EXPORT's of the target module, # or @EXPORT_OK, or else whatever comes from "use Module;" has _explicit_exports => ( is => 'ro', isa => HashRef, handles_via => 'Hash', handles => { _delete_export => 'delete', _explicit_export_count => 'count', _has_explicit_exports => 'count', _import_name => 'get', _is_importable => 'exists', }, lazy => 1, builder => '_build_explicit_exports', ); has _document => ( is => 'ro', isa => InstanceOf ['App::perlimports::Document'], required => 1, init_arg => 'document', ); has _export_inspector => ( is => 'ro', isa => InstanceOf ['App::perlimports::ExportInspector'], predicate => '_has_export_inspector', # used in test lazy => 1, builder => '_build_export_inspector', ); has formatted_ppi_statement => ( is => 'ro', isa => InstanceOf ['PPI::Statement::Include'], lazy => 1, builder => '_build_formatted_ppi_statement', ); has _ignored_modules => ( is => 'ro', isa => ArrayRef, init_arg => 'ignored_modules', predicate => '_has_ignored_modules', ); has _imports => ( is => 'ro', isa => ArrayRef, lazy => 1, builder => '_build_imports', ); has _include => ( is => 'ro', isa => InstanceOf ['PPI::Statement::Include'], init_arg => 'include', required => 1, ); has _is_ignored => ( is => 'ro', isa => Bool, lazy => 1, builder => '_build_is_ignored', ); has _isa_test_builder_module => ( is => 'ro', isa => Bool, lazy => 1, default => sub { shift->_export_inspector->isa_test_builder }, ); has _is_translatable => ( is => 'ro', isa => Bool, lazy => 1, builder => '_build_is_translatable', documentation => 'Is this a require which can be converted to a use?', ); has module_name => ( is => 'ro', isa => Maybe [Str], lazy => 1, default => sub { shift->_include->module }, ); has _found_imports => ( is => 'ro', isa => Maybe [ArrayRef], init_arg => 'found_imports', ); has _indent => ( is => 'ro', isa => Int, init_arg => 'indent', default => 4, ); has _pad_brackets => ( is => 'ro', isa => Bool, init_arg => 'pad_brackets', default => 0, ); has _pad_imports => ( is => 'ro', isa => Bool, init_arg => 'pad_imports', default => 1, ); has _preserve_require => ( is => 'ro', isa => Bool, init_arg => 'preserve_require', default => 1, ); has _tidy_whitespace => ( is => 'ro', isa => Bool, init_arg => 'tidy_whitespace', lazy => 1, default => 1, ); has _will_never_export => ( is => 'ro', isa => Bool, lazy => 1, default => sub { my $self = shift; return exists $self->_document->never_exports->{ $self->module_name } || $self->_export_inspector->is_oo_class; }, ); sub _build_export_inspector { my $self = shift; return $self->_document->inspector_for( $self->module_name ); } # If we have implicit (but not explicit) exports, we will make a best guess at # what gets exported by using the implicit list. sub _build_explicit_exports { my $self = shift; # Env is a special case. It ties environment variables to Perl variables, # so there is no @EXPORT for the ExportInspector to discover -- whatever a # given "use Env" statement imports is exactly what it provides. Treat the # statement's own arguments as its exportable symbols so that unused ones # can be pruned. See t/env.t and GH #23. if ( $self->_is_env ) { return $self->_env_exports; } return $self->_export_inspector->has_explicit_exports ? $self->_export_inspector->explicit_exports : $self->_export_inspector->implicit_exports; } sub _is_env { my $self = shift; my $name = $self->module_name; return defined $name && $name eq 'Env'; } sub _env_exports { my $self = shift; my %exports; for my $arg ( @{ $self->_found_imports // [] } ) { # A bareword (FOO) and the scalar form ($FOO) both tie the scalar # $FOO; only @FOO and %FOO tie the array or hash. Key on the sigil'd # symbol we'll actually search for in the code, but keep the literal # the user wrote as the value so we preserve their original style. my $sigil = substr( $arg, 0, 1 ); my $key = ( $sigil eq '$' || $sigil eq '@' || $sigil eq '%' ) ? $arg : '$' . $arg; $exports{$key} = $arg; } return \%exports; } ## no critic (Subroutines::ProhibitExcessComplexity) sub _build_imports { my $self = shift; # This is not a real symbol, so we should never be looking for it to appear # in the code. $self->_delete_export('verbose') if $self->module_name eq 'Carp'; my %found; # Stolen from Perl::Critic::Policy::TooMuchCode::ProhibitUnfoundImport for my $word ( $self->_document->possibly_imported_tokens ) { next if exists $found{"$word"}; # stop if we've found everything that can be imported (every # possible exported symbol is being used) last unless $self->_imports_remain( \%found ); # We don't want (for instance) pragma names to be confused with # functions. # # ie: # use warnings; # use Test::Warnings; # exports warnings() # # However, we also want to catch function calls in use statements, like # "use lib catfile( 't', 'lib');" # # or # # use Mojo::File qw( curfile ); # use lib curfile->sibling('lib')->to_string; my $is_function_call = is_function_call($word); if ( $word->parent && $word->parent->isa('PPI::Statement::Include') && ( !$is_function_call && !( $word->snext_sibling && $word->snext_sibling eq '->' ) ) ) { next; } # Don't turn "use POSIX ();" into "use POSIX qw( sprintf );" # If it's a function and it's a builtin function and it's either not # included in found_imports or original imports are not implicit # then skip this. if ( defined $self->_found_imports && ( none { $_ eq $word } @{ $self->_found_imports } ) && $is_function_call && is_perl_builtin($word) ) { next; } my @found_import; my $isa_symbol = $word->isa('PPI::Token::Symbol'); # Don't confuse my @Foo with a use of @Foo which is exported by a module. if ( $isa_symbol && $word->content =~ m{\A(@|%|$)} ) { my $previous_sibling = $word->sprevious_sibling; if ( $previous_sibling && $previous_sibling->content eq 'my' ) { next; } } # If a module exports %foo and we find $foo{bar}, $word->canonical # returns $foo and $word->symbol returns %foo if ( $isa_symbol && $self->_is_importable( $word->symbol ) ) { @found_import = ( $word->symbol ); } # Match on \&is_Str as is_Str elsif ($isa_symbol && $word->symbol_type eq '&' && $self->_is_importable( substr( $word->symbol, 1 ) ) ) { @found_import = ( substr( $word->symbol, 1 ) ); } # Don't catch ${foo} here and mistake it for "foo". We deal with that # elsewhere. Don't catch @{ split_header $str }. elsif ( $self->_is_importable("$word") && !( $word =~ m{^\w} && $word->previous_token && $word->previous_token eq '{' && $word->previous_token->previous_token && $word->previous_token->previous_token eq '$' ) ) { @found_import = ("$word"); } # Maybe a subroutine ref has been exported. For instance, # Getopt::Long exports &GetOptions elsif ($is_function_call && $self->_is_importable( '&' . $word ) ) { @found_import = ( '&' . "$word" ); } # Maybe this is an inner package referencing a function in main. We # don't really deal with inner packages otherwise, so this could break # some things. elsif ($is_function_call && $word =~ m{^::\w+} && $self->_is_importable( substr( $word, 2 ) ) ) { @found_import = ( substr( $word, 2 ) ); } # PPI can think that an imported function in a ternary is a label # my $foo = $enabled ? GEOIP_MEMORY_CACHE : 0; # The content of the $word will be "GEOIP_MEMORY_CACHE :" elsif ( $word->isa('PPI::Token::Label') ) { if ( $word->content =~ m{^(\w+)} ) { my $label = $1; if ( $self->_is_importable($label) ) { @found_import = ($label); $found{$label}++; } } } # Sometimes an import is only used to set a default value for a # variable in a signature. Without treating a prototype as a signature, # we would miss the import entirely. I'm not particularly proud of # this, but since PPI doesn't yet support signatures, this will at # least help us cover some cases. If the prototype is actually a # prototype, then this just shouldn't find anything. elsif ( $word->isa('PPI::Token::Prototype') ) { my $prototype = $word->prototype; # sometimes closing parens don't get included by PPI. if ( substr( $prototype, -1, 1 ) eq '(' ) { $prototype .= ')'; } $prototype =~ s{,}{;}g; $prototype .= ';'; # Won't hurt if there's an extra ";" my $new = PPI::Document->new( \$prototype ); my $words = $new->find( sub { $_[1]->isa('PPI::Token::Word') || $_[1]->isa('PPI::Token::Symbol'); } ) || []; for my $word ( @{$words} ) { if ( $self->_is_importable("$word") ) { push @found_import, "$word"; } } } for my $found (@found_import) { # could have been imported by another Include if ( !$self->_is_already_imported($found) ) { $found{$found}++; } } } # A used import might be a variable interpolated into quotes. if ( $self->_imports_remain( \%found ) ) { for my $var ( keys %{ $self->_document->interpolated_symbols } ) { if ( $self->_is_importable($var) ) { $found{$var} = 1; } } } # A used import might be just be a symbol that just gets exported. ie. If # it appears as @EXPORT = ( 'SOME_SYMBOL') we don't want to miss it. if ( $self->_imports_remain( \%found ) && $self->_document->my_own_inspector && $self->_document->my_own_inspector->is_exporter ) { for my $symbol ( uniq( $self->_document->my_own_inspector->implicit_export_names, $self->_document->my_own_inspector->explicit_export_names ) ) { if ( $self->_is_importable($symbol) && !$self->_document->is_sub_name("$symbol") ) { $found{$symbol} = 1; } } } # A used import might just be something that gets re-exported by # Sub::Exporter if ( $self->_imports_remain( \%found ) ) { for my $func ( $self->_document->sub_exporter_export_list ) { if ( $self->_is_importable($func) ) { $found{$func}++; } } } # When a module exports a typeglob (e.g. English exports *PROGRAM_NAME), # _import_name normalizes an imported slot like $PROGRAM_NAME to the # typeglob form *PROGRAM_NAME. But if the user explicitly imported a valid # slot form, that is correct and more minimal, so preserve what they wrote # rather than expanding it to the typeglob. my %found_imports = map { $_ => 1 } @{ $self->_found_imports // [] }; my @found = map { exists $found_imports{$_} ? $_ : $self->_import_name($_); } keys %found; # Some modules have imports which are basically flags, rather than names of # symbols to export. So if a flag is already in the import, we need to # preserve it, rather than risk altering the behaviour of the module. if ( $self->_export_inspector->has_import_flags ) { for my $arg ( @{ $self->_export_inspector->import_flags } ) { if ( defined $self->_found_imports && ( any { $_ eq $arg } @{ $self->_found_imports } ) ) { push @found, $arg; } } } @found = uniq _sort_symbols(@found); if ( $self->_found_imports ) { my @preserved = grep { m{\A[!_]} } @{ $self->_found_imports }; @found = uniq( @preserved, @found ); } return \@found; } ## use critic sub _build_is_ignored { my $self = shift; if ( $self->_include->type eq 'require' ) { return 1 if !$self->_is_translatable; } # A bare "use Env;" imports every environment variable. There are no # explicit arguments to prune, so leave the statement untouched rather than # collapsing it to "use Env ();". See GH #23. return 1 if $self->_is_env && !@{ $self->_found_imports // [] }; # This will be rewritten as "use Foo ();" return 0 if $self->_will_never_export; return 1 if $self->_export_inspector->has_fatal_error; return 0 if $self->_export_inspector->is_oo_class; # A MooseX::Types type library can have a Moose metaclass (as with # MooseX::Types 0.50), which would otherwise trip the uses_moose check # below. See GH#202. return 0 if $self->_export_inspector->is_moose_type_class; return 1 if $self->_export_inspector->is_moose_class; return 1 if $self->_export_inspector->uses_moose; return 1 if $self->_export_inspector->is_moo_class; return 1 if any { $_ eq 'Moo::Object' } @{ $self->_export_inspector->pkg_isa }; return 0; } sub _build_is_translatable { my $self = shift; return 0 if !$self->_include->type; return 0 if $self->_include->type ne 'require'; # A "require Foo;" is functionally distinct from "use Foo ();" -- require # loads at runtime, use at compile time -- and is often deliberate. By # default we leave requires untouched. Disable preserve_require to restore # the old behaviour of translating them to "use Foo ();". See GH #76. return 0 if $self->_preserve_require; return 0 if $self->module_name eq 'Exporter'; # We can deal with a top level require. # require Foo; can be changed to use Foo (); # We don't want to touch requires which are inside any kind of a condition. # If there is no parent, then it's likely just a single snippet # provided by a text editor. We can process the snippet. If it's part # of a larger document and the parent is not a PPI::Document, this # would appear not to be a top level require. if ( $self->_include->parent && !$self->_include->parent->isa('PPI::Document') ) { return 0; } # Postfix conditions are a bit harder to find. If the significant # children amount to more than "require Module;", we'll just move on. my @children = $self->_include->schildren; my $statement = join q{ }, @children[ 0 .. 2 ]; if ( $statement ne 'require ' . $self->module_name . ' ;' ) { return 0; } # Any other case of "require Foo;" should be translated to "use Foo ();" # as those are functionally equivalent. return 1; } ## no critic (Subroutines::ProhibitExcessComplexity) sub _build_formatted_ppi_statement { my $self = shift; # The following steps may seem a bit out of order, but we're trying to # short circuit if at all possible. That means not building an # ExportInspector object unless we really need to. # Nothing to do here. Preserve the original statement. return $self->_include if $self->_is_ignored; my $maybe_module_version = $self->_include->module_version ? q{ } . $self->_include->module_version : q{}; # In this case we either have a module which we know will never export # symbols or a module which can export but for which we haven't found any # imported symbols. In both cases we'll want to rewrite with an empty list # of imports. if ( $self->_will_never_export || $self->_is_translatable || !@{ $self->_imports } ) { return $self->_maybe_get_new_include( sprintf( 'use %s%s ();', $self->module_name, $maybe_module_version ) ); } my $statement; my @args = $self->_include->arguments; # Don't touch a do { } block. if ( $self->_isa_test_builder_module && @args && $args[0] eq 'do' ) { return $self->_include; } # Do some contortions to turn PPI objects back into a data structure so # that we can add or replace an import hash key and then end up with a new # list which is sorted on hash keys. This makes the assumption that the # same key won't get passed twice. This is pretty gross, but I was too lazy # to try to figure out how to do this with PPI and I think it should # *mostly* work. I don't like the formatting that Data::Dumper comes up # with, so we'll run it through perltidy. if ( $self->_isa_test_builder_module && @args ) { my $all; if ( $args[0]->isa('PPI::Token::Word') ) { $all = join q{ }, map { "$_" } @args; } elsif ($args[0]->isa('PPI::Structure::List') && $args[0]->braces eq '()' ) { for my $child ( $args[0]->children ) { $all .= "$child"; } } ## no critic (BuiltinFunctions::ProhibitStringyEval) my $args; my $error; try { $args = eval( '{' . $all . '}' ); } catch { $self->logger->info($_); $error = 1; }; ## use critic if ( !$error && !is_plain_hashref($args) ) { $self->logger->info( 'Not a hashref: ' . Dumper($args) ); $error = 1; } # We will replace these with our own parsed imports. delete $args->{import}; # Ignore this line if we can't parse it. This will happen if the arg to # test is a do block, for example. return $self->_include if $error; local $Data::Dumper::Terse = 1; local $Data::Dumper::Indent = 0; local $Data::Dumper::Sortkeys = 1; local $Data::Dumper::Quotekeys = 0; local $Data::Dumper::Useqq = 0; local $Data::Dumper::Trailingcomma = 1; local $Data::Dumper::Deparse = 1; my $dumped = Dumper($args); my $non_import_args; my $import_arg; if ( $dumped =~ m/^{(.*)}$/ ) { $non_import_args = $1; } if ( $self->_imports ) { # Always emit tight brackets here; the -sbt flag passed to # Perl::Tidy below controls whether padding is added. $import_arg = sprintf( 'import => [qw( %s )]', join( q{ }, @{ $self->_imports } ) ); } my $all_args = join ', ', grep { $_ && $_ =~ m{\w} } ( $import_arg, $non_import_args ); $statement = sprintf( 'use %s%s %s;', $self->module_name, $maybe_module_version, $all_args ); # save ~60ms in cases where we don't need Perl::Tidy require Perl::Tidy; ## no perlimports my $sbt = $self->_pad_brackets ? 0 : 1; my $indent = $self->_indent; Perl::Tidy::perltidy( argv => "-npro -sbt=$sbt -i=$indent", source => \$statement, destination => \$statement ); } else { my $padding = $self->_pad_imports ? q{ } : q{}; my $bp = $self->_pad_brackets ? q{ } : q{}; my $template = $self->_isa_test_builder_module ? "use %s%s import => [${bp}qw(%s%s%s)${bp}];" : 'use %s%s qw(%s%s%s);'; $statement = sprintf( $template, $self->module_name, $maybe_module_version, $padding, join( q{ }, @{ $self->_imports } ), $padding, ); } # Don't deal with Test::Builder classes here to keep it simple for now if ( length($statement) > 78 && !$self->_isa_test_builder_module ) { $statement = sprintf( "use %s%s qw(\n", $self->module_name, $maybe_module_version, ); my $indent = q{ } x $self->_indent; for ( @{ $self->_imports } ) { $statement .= "$indent$_\n"; } $statement .= ');'; } return $self->_maybe_get_new_include($statement); } ## use critic sub _imports_remain { my $self = shift; my $found = shift; return keys %{$found} < $self->_explicit_export_count; } # Comments which live *inside* the original include statement (e.g. a # "## no critic (...)" annotation between the module name and the import list, # or a comment nested inside an explicit "( ... )" import list) are # descendants of the PPI::Statement::Include and always appear before its # terminating ";". Because we rebuild the statement from scratch, they would # otherwise be silently dropped (see #50), so we collect them here, in source # order, to be re-attached as a trailing side comment. Only the comment # *content* is preserved, not its original position: every embedded comment is # moved to the end of the rewritten statement. A comment which already trails # the ";" is a sibling of the statement rather than a descendant, so it is left # in place by the document and is intentionally not collected here. sub _original_side_comments { my $self = shift; my $comments = $self->_include->find( sub { $_[1]->isa('PPI::Token::Comment') } ); return q{} unless $comments; return join q{ }, map { $_->content =~ s{\s+\z}{}r } @{$comments}; } # Takes a string 'use SomeModule ...', returns a PPI:Statement:Include. # The returned obj could be one made from the string, if its different from # the existing one, else it is just the original. sub _maybe_get_new_include { my $self = shift; my $statement = shift; my $orig = $self->_include; # Re-attach any comments which were embedded in the original statement as a # trailing side comment so they survive the rewrite (#50). Four spaces of # separation matches perltidy's default --minimum-space-to-comment, so the # result is stable under a subsequent perltidy run. We only pipe through # Perl::Tidy for single-line statements: running it over an already-wrapped # (multi-line) import list would re-flow the indentation and fight our own # --indent handling. # # Known limitation: whenever a rewrite ends up with more than one comment on # the single collapsed line -- multiple comments embedded in the original # statement (collected here), or one embedded plus one already trailing the # ";" (kept in place by the document) -- their text is preserved, but # Perl::Critic honours only the first "## no critic" on a physical line, so a # second such annotation stops suppressing. These cases are rare and we # deliberately keep every comment rather than drop one; a human can merge the # annotations if needed. my $comments = $self->_original_side_comments; if ( length $comments ) { $statement .= q{ } . $comments; if ( $statement !~ m{\n} ) { require Perl::Tidy; ## no perlimports my $sbt = $self->_pad_brackets ? 0 : 1; my $indent = $self->_indent; my $tidied; Perl::Tidy::perltidy( argv => "-npro -sbt=$sbt -i=$indent", source => \$statement, destination => \$tidied, ); $tidied =~ s{\s+\z}{}; $statement = $tidied; } } return $orig if $statement eq $orig; # quick exit # Prefix newlines to reproduce original's location ## no critic (BuiltinFunctions::ProhibitLvalueSubstr) my $doc = do { my $line = $orig->line_number || 1; my $text = "\n" x $line; substr( $text, -1 ) = $statement; PPI::Document->new( \$text, filename => $orig->logical_filename ); }; ## use critic # Cloning is necessary because the tokens in the found statement belong # to the document. When the document is destroyed, the tokens go with it. # With the clone, the duplicated tokens are independent of the doc. my $rewrite = do { $doc->index_locations; my $includes = $doc->find('Statement::Include'); my $found = $includes->[0]; my $clone = $found->clone; # A re-attached side comment sits *after* the terminating ";", so PPI # parses it as a sibling of the include rather than a child. Pull those # trailing comment tokens into the clone so they are not lost when the # document is destroyed. if ( length $comments ) { my @trailing; my $sibling = $found; while ( $sibling = $sibling->next_sibling ) { last if $sibling->isa('PPI::Statement'); push @trailing, $sibling; } pop @trailing while @trailing && !$trailing[-1]->isa('PPI::Token::Comment'); $clone->add_element( $_->clone ) for @trailing; } $clone; }; # If the -only- difference is some whitespace before the symbol list, we # keep the original statement. This is because perltidy often adds space # to align successive import lists, and we don't want to fight. So: # use AAAAAAA qw( thing ); # use Foo qw( bar ); <== leave this spacing alone # strip away extra spaces before the symbol list.. my $untidied_include = do { my $string = "$orig"; $string =~ s{\s+(qw|\()}{ $1}; $string; }; if ( "$rewrite" eq $untidied_include ) { return $orig; } return $rewrite if $self->_tidy_whitespace; # We will return the rewritten include if a newline has been added or # removed. This is a formatting change that we *probably* want. ( my $a = $orig . q{} ) =~ s{\s+}{}g; ( my $b = $rewrite . q{} ) =~ s{\s+}{}g; return ( $a eq $b ) ? $orig : $rewrite; } # If there's a different module in this document which has already imported # a symbol of the same name in its original imports, the we should make # sure we don't accidentally create a duplicate import here. For example, # Path::Tiny and Test::TempDir::Tiny both export a tempdir() function. # Without this check we'd add a "tempdir" to both modules if we find it # being used in the document. sub _is_already_imported { my $self = shift; my $symbol = shift; # a string, not an object my $duplicate = 0; if ( $self->_document->is_constant_name($symbol) ) { $self->logger->debug("$symbol is defined as a constant"); return 1; } foreach my $module ( grep { $_ ne $self->module_name } keys %{ $self->_document->found_imports } ) { $self->logger->debug( "checking $module for previous imports of $symbol"); my @imports; if ( is_plain_arrayref( $self->_document->found_imports->{$module} ) ) { @imports = @{ $self->_document->found_imports->{$module} }; $self->logger->debug( 'Explicit imports found: ' . Dumper( [ sort @imports ] ) ); } else { if ( my $inspector = $self->_document->inspector_for($module) ) { @imports = $inspector->implicit_export_names; $self->logger->debug( 'Implicit imports found: ' . Dumper( [ sort @imports ] ) ); } } if ( any { $_ eq $symbol } @imports ) { $duplicate = 1; $self->logger->debug("$symbol already imported via $module"); last; } } return $duplicate; } sub _sort_symbols { my @list = @_; ## no critic (BuiltinFunctions::RequireSimpleSortBlock) my @sorted = sort { my $A = _transform_before_cmp($a); my $B = _transform_before_cmp($b); "\L$A" cmp "\L$B"; } @list; return @sorted; } # This looks a little weird, but basically we want to maintain a stable sort # order with lists that look like (foo, $foo, @foo, %foo). We use "-" to begin # the suffix because it comes earliest in a sorted list of letters and digits. sub _transform_before_cmp { my $thing = shift; if ( $thing =~ m{\A[\$]} ) { $thing = substr( $thing, 1 ) . '-0'; } elsif ( $thing =~ m{\A[@]} ) { $thing = substr( $thing, 1 ) . '-1'; } elsif ( $thing =~ m{\A[%]} ) { $thing = substr( $thing, 1 ) . '-2'; } return $thing; } 1; # ABSTRACT: Encapsulate one use statement in a document __END__ =pod =encoding UTF-8 =head1 NAME App::perlimports::Include - Encapsulate one use statement in a document =head1 VERSION version 0.000067 =head1 METHODS =head2 formatted_ppi_statement Returns an L object. This can be stringified into an import statement or used to replace an existing L. =head1 AUTHOR Olaf Alders =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2020 by Olaf Alders. 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 Sandbox.pm100644001750001751 532615261510600 21757 0ustar00olafolaf000000000000App-perlimports-0.000067/lib/App/perlimportspackage App::perlimports::Sandbox; use strict; use warnings; our $VERSION = '0.000067'; use Data::UUID (); { my $du = Data::UUID->new; sub pkg_for { my $module_name = shift; my $unique = 'A' . $du->create_str; $unique =~ s{-}{}g; return sprintf( 'Local::%s::%s', $module_name, $unique ); } } sub eval_pkg { my $module_name = shift; my $content = shift; my $pkg = pkg_for($module_name); my $to_eval = <<"EOF"; package $pkg; $content; 1; EOF ## no critic (Variables::RequireInitializationForLocalVars) local $@; # We only care about whether the eval throws an error. Trial-loading an # arbitrary module can emit the "Attempt to call undefined import method" # warning when a module has no import(), which we don't want to leak to # the user's terminal. We suppress only that specific noise and re-dispatch # anything else, so genuine diagnostics from a broken module still surface. my $prev_warn = $SIG{__WARN__}; local $SIG{__WARN__} = sub { my ($msg) = @_; return if _is_trial_load_warning($msg); $prev_warn ? $prev_warn->($msg) : print {*STDERR} $msg; }; ## no critic (BuiltinFunctions::ProhibitStringyEval,ErrorHandling::RequireCheckingReturnValueOfEval) eval $to_eval; my $e = $@; return $e; } # Recognize the noisy warning emitted when we trial-load a module that has no # import() method. Perl's wording for this diagnostic changed from "undefined" # to "missing" in the 5.44 development cycle, so match either variant. sub _is_trial_load_warning { my $msg = shift; return defined $msg && $msg =~ m{Attempt to call (?:undefined|missing) import method}; } 1; # ABSTRACT: Internal Tools for perlimports __END__ =pod =encoding UTF-8 =head1 NAME App::perlimports::Sandbox - Internal Tools for perlimports =head1 VERSION version 0.000067 =head2 pkg_for( $string ) Returns a random module/package name, which can be used to eval arbitrary code. Requires the name of the module which will be imported into the package to be created. =head2 eval_pkg( $module_name, $pkg_content ) Takes a module name and content to eval. Returns the contents of C<$@>. So, if it returns true, the C failed. Returns a random module/package name, which can be used to eval arbitrary code. Requires the name of the module which will be imported into the package to be created. =head1 AUTHOR Olaf Alders =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2020 by Olaf Alders. 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 module-with-inner-packages.t100644001750001751 127115261510600 21723 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use lib 't/lib'; use TestHelper qw( doc ); use Test::More import => [qw( done_testing is $TODO )]; my ($doc) = doc( filename => 'test-data/lib/Local/WithInnerPkg.pm' ); my $expected = <<'EOF'; use strict; use warnings; package Local::WithInnerPkg; use HTTP::Status qw( HTTP_OK ); sub foo { HTTP_OK(); } 1; package MyInnerPkgOne; use HTTP::Status qw( HTTP_CREATED ); sub foo { HTTP_CREATED(); } 1; package MyInnerPkgTwo; use HTTP::Status qw( HTTP_ACCEPTED ); sub foo { HTTP_ACCEPTED(); } 1; EOF TODO: { local $TODO = 'Cannot yet handle inner packages'; is( $doc->tidied_document, $expected, 'inner packages handled' ); } done_testing(); re-export-via-sub-exporter.t100755001750001751 113615261510600 21742 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use lib 't/lib'; use Test::Differences qw( eq_or_diff ); use TestHelper qw( doc ); use Test::More import => [qw( done_testing )]; my ($doc) = doc( filename => 'test-data/lib/Local/ReExportViaSubExporter.pm', preserve_unused => 0, ); my $expected = <<'EOF'; package Local::ReExportViaSubExporter; use strict; use warnings; use Carp qw( croak ); use Sub::Exporter -setup => { exports => [ 'croak', 'other_func', ] }; sub other_func { } 1; EOF eq_or_diff( $doc->tidied_document, $expected, 'croak detected' ); done_testing(); script-with-inner-packages.t100644001750001751 62615261510600 21725 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use lib 't/lib'; use TestHelper qw( doc ); use Test::More import => [qw( done_testing is )]; use Test::Needs qw( HTTP::Status ); my ($doc) = doc( filename => 'test-data/inner-package.pl', selection => 'use HTTP::Status;', ); is( $doc->tidied_document, 'use HTTP::Status qw( is_redirect is_success );', 'functions with :: prefix found' ); done_testing(); foo.txt100644001750001751 015261510600 21671 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/filter-pathshash-unquoted-key.pl100644001750001751 11515261510600 21722 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use HTTP::Status (); my %foo; $foo{is_info} = 1; UsesMoo.pm100644001750001751 11115261510600 21536 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/lib/Localpackage Local::UsesMoo; use Moo; __PACKAGE__->meta->make_immutable; 1; regex-replacement.pl100644001750001751 12715261510600 21761 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause IP::Random; s/($RE{net}{IPv4})/${\( $store{$1} ||= IP::Random::random_ipv4() )}/g; Document.pm100644001750001751 14454315261510600 22204 0ustar00olafolaf000000000000App-perlimports-0.000067/lib/App/perlimportspackage App::perlimports::Document; use Moo; use utf8; our $VERSION = '0.000067'; use App::perlimports::Annotations (); use App::perlimports::ExportInspector (); use App::perlimports::Include (); use App::perlimports::Sandbox (); use App::perlimports::Sorter (); use File::Basename qw( fileparse ); use List::Util qw( any uniq ); use Module::Runtime qw( module_notional_filename ); use MooX::StrictConstructor; use Path::Tiny qw( path ); use PPI::Document (); use PPIx::Utils::Classification qw( is_class_name is_function_call is_hash_key is_method_call is_package_declaration ); use PPIx::Utils::Traversal qw( split_nodes_on_comma ); use Ref::Util qw( is_plain_arrayref is_plain_hashref ); use Scalar::Util qw( refaddr ); use Sub::HandlesVia; use Text::Diff (); use Try::Tiny qw( catch try ); use Types::Standard qw( ArrayRef Bool HashRef InstanceOf Int Maybe Object Str ); with 'App::perlimports::Role::Logger'; has _annotations => ( is => 'ro', isa => InstanceOf ['App::perlimports::Annotations'], lazy => 1, default => sub { return App::perlimports::Annotations->new( ppi_document => shift->ppi_document ); }, ); has _cache => ( is => 'ro', isa => Bool, init_arg => 'cache', lazy => 1, default => 0, ); has _cache_dir => ( is => 'ro', isa => InstanceOf ['Path::Tiny'], lazy => 1, builder => '_build_cache_dir', ); has _filename => ( is => 'ro', isa => Str, init_arg => 'filename', required => 1, ); has _ignore_modules => ( is => 'ro', isa => HashRef, init_arg => 'ignore_modules', default => sub { +{} }, ); has _ignore_modules_pattern => ( is => 'ro', isa => ArrayRef [Str], init_arg => 'ignore_modules_pattern', default => sub { [] }, ); # list of PPI::Statement::Include (use, no, require) # (excluding pragmas, ignored modules, and 'use VERSION') has includes => ( is => 'ro', isa => ArrayRef [Object], # PPI::Statement::Include lazy => 1, builder => '_build_includes', ); # Deliberately an explicit accessor rather than a Sub::HandlesVia 'elements' # delegation. Under the Sub::HandlesVia::XS backend the array handler caches the # Perl stack pointer, then invokes this lazy builder via call_sv; the builder # grows (and reallocates) the stack, leaving that cached pointer dangling, and # the handler's subsequent write corrupts the heap. See issue #171. sub all_includes { return @{ $_[0]->includes }; } # constant subs defined using 'use constant' has constants => ( is => 'ro', isa => HashRef, handles_via => 'Hash', handles => { is_constant_name => 'exists', all_constants => 'keys', _set_constants => 'set', }, predicate => '_has_constants', lazy => 1, builder => '_build_constants', ); has _inspectors => ( is => 'ro', isa => HashRef [ Maybe [Object] ], handles_via => 'Hash', handles => { all_inspector_names => 'keys', _get_inspector_for => 'get', _has_inspector_for => 'exists', _set_inspector_for => 'set', }, lazy => 1, default => sub { +{} }, ); # catalog of variables seen in interpolated context (string, qr, et al) has interpolated_symbols => ( is => 'ro', isa => HashRef, lazy => 1, builder => '_build_interpolated_symbols', ); # (lint mode only) whether to output json (or else console text) has json => ( is => 'ro', isa => Bool, lazy => 1, default => 0, ); has _json_encoder => ( is => 'ro', isa => InstanceOf ['Cpanel::JSON::XS'], lazy => 1, default => sub { require Cpanel::JSON::XS; return Cpanel::JSON::XS->new; }, ); # are we processing in lint mode ? (otherwise edit mode) has lint => ( is => 'ro', isa => Bool, lazy => 1, default => 0, ); has my_own_inspector => ( is => 'ro', isa => Maybe [ InstanceOf ['App::perlimports::ExportInspector'] ], lazy => 1, builder => '_build_my_own_inspector', ); has never_exports => ( is => 'ro', isa => HashRef, lazy => 1, builder => '_build_never_exports', ); has _never_export_modules => ( is => 'ro', isa => ArrayRef [Str], init_arg => 'never_export_modules', predicate => '_has_never_export_modules', ); # catalog of symbols explicitly imported (by package), e.g. # Carp => ['croak', ..], ... # in edit mode, this will be altered after processing (tidied_document) # to reflect what we think the import statement should be. has found_imports => ( is => 'ro', isa => HashRef, handles_via => 'Hash', handles => { _reset_found_import => 'set', }, lazy => 1, builder => '_build_found_imports', ); has _indent => ( is => 'ro', isa => Int, init_arg => 'indent', default => 4, ); has _pad_brackets => ( is => 'ro', isa => Bool, init_arg => 'pad_brackets', default => 0, ); has _padding => ( is => 'ro', isa => Bool, init_arg => 'padding', default => 1, ); has _sort => ( is => 'ro', isa => Bool, init_arg => 'sort', default => 0, ); has ppi_document => ( is => 'ro', isa => Object, lazy => 1, builder => '_build_ppi_document', ); # list of tokens in the document that -could- have come from an import # (but most are keywords, built-ins, lexical vars, defined funcs, etc.) has possible_imports => ( is => 'ro', isa => ArrayRef [Object], # isa PPI:Token:Word, :Symbol, :Magic lazy => 1, builder => '_build_possible_imports', ); # Explicit accessor rather than a Sub::HandlesVia 'elements' delegation; see the # note on all_includes above and issue #171. sub possibly_imported_tokens { return @{ $_[0]->possible_imports }; } has _ppi_selection => ( is => 'ro', isa => Object, init_arg => 'ppi_selection', lazy => 1, default => sub { $_[0]->ppi_document }, ); has _preserve_duplicates => ( is => 'ro', isa => Bool, init_arg => 'preserve_duplicates', default => 1, ); has _preserve_require => ( is => 'ro', isa => Bool, init_arg => 'preserve_require', default => 1, ); has _preserve_unused => ( is => 'ro', isa => Bool, init_arg => 'preserve_unused', default => 1, ); has _sub_exporter_export_list => ( is => 'ro', isa => ArrayRef, lazy => 1, builder => '_build_sub_exporter_export_list', ); # Explicit accessor rather than a Sub::HandlesVia 'elements' delegation; see the # note on all_includes above and issue #171. sub sub_exporter_export_list { return @{ $_[0]->_sub_exporter_export_list }; } # catalog of the named subs defined, e.g. # new => 1, ... has _sub_names => ( is => 'ro', isa => HashRef, handles_via => 'Hash', handles => { is_sub_name => 'exists', }, lazy => 1, builder => '_build_sub_names', ); has _tidy_whitespace => ( is => 'ro', isa => Bool, init_arg => 'tidy_whitespace', lazy => 1, default => 1, ); has _verbose => ( is => 'ro', isa => Bool, init_arg => 'verbose', default => 0, ); around BUILDARGS => sub { my ( $orig, $class, @args ) = @_; my %args = @args; if ( my $modules = delete $args{ignore_modules} ) { my %modules = map { $_ => 1 } @{$modules}; $args{ignore_modules} = \%modules; } if ( my $selection = delete $args{selection} ) { $args{ppi_selection} = PPI::Document->new( \$selection ); } return $class->$orig(%args); }; my %default_ignore = ( 'Carp::Always' => 1, 'Class::XSAccessor' => 1, 'Constant::Generate' => 1, 'Data::Printer' => 1, 'DDP' => 1, 'Devel::Confess' => 1, 'DynaLoader' => 1, 'Encode::Guess' => 1, 'Exception::Class' => 1, 'Exporter' => 1, 'Exporter::Lite' => 1, 'Feature::Compat::Try' => 1, 'Filter::Simple' => 1, 'Git::Sub' => 1, 'HTTP::Message::PSGI' => 1, # HTTP::Request::(to|from)_psgi 'Import::Into' => 1, 'local::lib' => 1, 'LWP::ConsoleLogger::Everywhere' => 1, # wraps UAs to log requests 'MLDBM' => 1, 'Modern::Perl' => 1, 'Mojo::Base' => 1, 'Mojo::Date' => 1, 'Mojolicious::Lite' => 1, 'Moo' => 1, 'Moo::Role' => 1, 'Moose' => 1, 'Moose::Exporter' => 1, 'Moose::Role' => 1, 'MooseX::NonMoose' => 1, 'MooseX::Role::Parameterized' => 1, 'MooseX::SemiAffordanceAccessor' => 1, 'MooseX::StrictConstructor' => 1, 'MooseX::TraitFor::Meta::Class::BetterAnonClassNames' => 1, 'MooseX::Types' => 1, 'MooX::StrictConstructor' => 1, 'namespace::autoclean' => 1, 'namespace::clean' => 1, 'PerlIO::gzip' => 1, 'Regexp::Common' => 1, 'Sort::ByExample' => 1, 'Struct::Dumb' => 1, 'Sub::Exporter' => 1, 'Sub::Exporter::Progressive' => 1, 'Sub::HandlesVia' => 1, 'Syntax::Keyword::Try' => 1, 'Term::Size::Any' => 1, 'Test2::Util::HashBase' => 1, 'Test::Exception' => 1, 'Test::Needs' => 1, 'Test::NoWarnings' => 1, 'Test::Number::Delta' => 1, 'Test::Pod' => 1, 'Test::Pod::Coverage' => 1, 'Test::Requires::Git' => 1, 'Test::RequiresInternet' => 1, 'Test::Warnings' => 1, 'Test::Whitespaces' => 1, 'Test::XML' => 1, 'Types::Standard' => 1, 'URI::QueryParam' => 1, ); # Funky stuff could happen with inner packages. sub _build_my_own_inspector { my $self = shift; my $pkgs = $self->ppi_document->find( sub { $_[1]->isa('PPI::Statement::Package') && $_[1]->file_scoped } ); if ( !$pkgs || $pkgs->[0]->namespace eq 'main' ) { return; } my $pkg = $pkgs->[0]; # file_scoped() doesn't seem to be very reliable, so let's just try a crude # check to see if this is a package we might actually find on disk before # we try to require it. my $notional_file = fileparse( module_notional_filename( $pkg->namespace ) ); my $provided_file = fileparse( $self->_filename ); return unless $notional_file eq $provided_file; return App::perlimports::ExportInspector->new( logger => $self->logger, module_name => $pkg->namespace, ); } sub _build_includes { my $self = shift; # version() returns a value if this a dependency on a version of Perl, e.g # use 5.006; # require 5.006; # # We check for type so that we can filter out undef types or "no". ## no critic (Subroutines::ProhibitCallsToUnexportedSubs) return $self->_ppi_selection->find( sub { $_[1]->isa('PPI::Statement::Include') && !$_[1]->pragma # no pragmas && !$_[1]->version # Perl version requirement && $_[1]->type && ( $_[1]->type eq 'use' || $_[1]->type eq 'require' ) && !$self->_is_ignored( $_[1] ) && !$self->_has_import_switches( $_[1]->module ) && !App::perlimports::Sandbox::eval_pkg( $_[1]->module, "$_[1]" ); } ) || []; ## use critic } sub _build_constants { my $self = shift; my %constant; my $incs = $self->_ppi_selection->find( sub { $_[1]->isa('PPI::Statement::Include') && $_[1]->module eq 'constant'; } ) || []; foreach my $inc (@$incs) { next unless my @data = $self->_parse_constant($inc); # N.B. we never alter 'use constant' imports foreach my $data (@data) { $constant{ $data->{name} } = $data; } } $self->logger->debug("constants found: @{[sort keys %constant]}"); return \%constant; } # parse hashref into list of "values"; each an arrayref of tokens sub _parse_hashlist { my ($elem) = @_; return unless $elem->isa('PPI::Structure::Constructor'); my ($exp) = $elem->schildren; return unless $exp->isa('PPI::Statement::Expression'); my @tokens = $exp->schildren; # first and last commas are ignored, if no significant child exists beyond! # interior serial commas are not handled properly: {a => 1, 'b', , 'c', 4} return my @values = split_nodes_on_comma(@tokens); } # until we get a PPI::Statement::Include::Constant class ## no critic (Subroutines::ProhibitExcessComplexity) sub _parse_constant { my ( $self, $stm ) = @_; return unless $stm->isa('PPI::Statement::Include') && $stm->module eq 'constant'; my ( $expected, @kv ); return unless my @args = $stm->arguments; if ( @args > 1 ) { my ( $word, $op, @defn ) = @args; $expected = $op eq '=>' && $word->isa('PPI::Token::Word') && @defn; $expected ||= $word->isa('PPI::Token::Quote') && ( $op eq ',' || $op eq '=>' ) && @defn; @kv = ( $word, \@defn ) if $expected; } elsif ( my $first = $args[0] ) { # @args == 1 if ( $first->isa('PPI::Structure::Constructor') ) { # e.g.: use constant { FOO => 1, BAR => 3 }; # keys are arrayrefs, of (hopefully) a single token @kv = _parse_hashlist($first); $expected++; } } if ( !$expected || !@kv || @kv % 2 ) { $self->logger->error("failed to parse constant: $stm"); return; } my @constants; while (@kv) { my ( $word, $val ) = splice( @kv, 0, 2 ); if ( is_plain_arrayref($word) ) { if ( @$word > 1 ) { $self->logger->error("failed to parse constant: @$word"); next; } $word = $word->[0]; } my $name = $word->isa('PPI::Token::Quote') ? $word->string : "$word"; my %data = ( token => $word, name => $name, definition => $val, ); # position in file after which this function exists (compile time) # TODO location data can become stale if ( my $end = $stm->last_element ) { # likely PPI:Token:Structure ';' my $loc = _elem_loc($end); $data{end} = $loc->{end}; } push @constants, \%data; } return @constants; } ## use critic ## no critic (Subroutines::ProhibitExcessComplexity) sub _build_possible_imports { my $self = shift; my $before = $self->ppi_document->find( sub { $_[1]->isa('PPI::Token::Word') || $_[1]->isa('PPI::Token::Symbol') || $_[1]->isa('PPI::Token::Label') || $_[1]->isa('PPI::Token::Prototype'); } ) || []; # remember referenced package namespaces and constants my ( %pack, %const ); my @after; for my $word ( @{$before} ) { # Without the sub name check, we accidentally turn # use List::Util (); # sub any { } # # into # # use List::Util qw( any ); # sub any {} next if $self->is_sub_name("$word"); # cant validate class/instance method names: next if !$word->isa('PPI::Token::Symbol') && is_method_call($word); next if _is_word_interpreted_as_string($word); next if is_package_declaration($word); if ( my $stm = $word->statement ) { my $first = $stm->schild(0); # PPI:Element if ( $stm->isa('PPI::Statement::Package') ) { next if $word eq 'package' && $word == $first; } elsif ( $stm->isa('PPI::Statement::Include') ) { if ( my $packname = $stm->module ) { $pack{$packname} ||= 1; # even if its a pragma if ( $packname eq 'constant' ) { next unless my @data = $self->_parse_constant($stm); $const{ $_->{name} } ||= $_ for @data; next if any { $word == $_->{token} } @data; } my $package_bareword = $stm->schild(1); next if $word == $package_bareword; } next if $word eq 'use' && $word == $first; next if $stm->pragma && $word eq 'no' && $word == $first; } } next if $const{"$word"} && ( is_hash_key($word) || is_function_call($word) ); next if $pack{"$word"} && is_class_name($word); # class method calls push @after, $word; } # safe to assume our search encountered every 'use constant' statement if ( %const && !$self->_has_constants ) { $self->_set_constants(%const); $self->logger->debug("constants found: @{[sort keys %const]}"); } return \@after; } ## use critic sub _build_ppi_document { my $self = shift; return PPI::Document->new( $self->_filename ); } # Create a key for every included module. # use Carp; # use Data::Dumper qw( Dumper ); # use POSIX (); # # becomes: # # { # Carp => undef, # 'Data::Dumper' => ['Dumper'], # POSIX => [], # } # # It starts out as a list of original imports, but with each include that gets # processed, this list gets updated to what the include will import once # tidied (an empty list if the include is removed as unused). This happens in # both lint and edit mode, although lint mode never modifies the document. We # do this so that we can keep track of what previous modules are really # importing, avoiding duplicate imports. sub _build_found_imports { my $self = shift; # We're missing requires which could be followed by an import. my $found = $self->ppi_document->find( sub { $_[1]->isa('PPI::Statement::Include') && !$_[1]->pragma # no pragmas && !$_[1]->version # Perl version requirement && $_[1]->type && $_[1]->type eq 'use'; } ) || []; my %imports; for my $include ( @{$found} ) { my $pkg = $include->module; $imports{$pkg} = undef unless exists $imports{$pkg}; # this is probably wrong #next if $self->_is_ignored($pkg); # If a module has been included multiple times, we want to have a # cumulative tally of what has been explicitly imported. my $found_for_include = _imports_for_include($include); if ($found_for_include) { if ( $imports{$pkg} ) { my %catalog = map { $_ => 1 } @{ $imports{$pkg} }, @{$found_for_include}; $imports{$pkg} = [ sort keys %catalog ]; } else { $imports{$pkg} = $found_for_include; } } } return \%imports; } sub _build_sub_exporter_export_list { my $self = shift; my $sub_ex = $self->ppi_document->find( sub { $_[1]->isa('PPI::Statement::Include') && $_[1]->module eq 'Sub::Exporter'; } ) || []; return [] unless @{$sub_ex}; my @found; for my $include ( @{$sub_ex} ) { my @arguments = $include->arguments; for my $arg (@arguments) { if ( $arg->isa('PPI::Structure::Constructor') ) { ## no critic (BuiltinFunctions::ProhibitStringyEval) my $thing = eval $arg; if ( is_plain_hashref($thing) ) { if ( is_plain_arrayref( $thing->{exports} ) ) { push @found, @{ $thing->{exports} }; } } } } } return [ uniq @found ]; } sub _imports_for_include { my $include = shift; my $imports = undef; for my $child ( $include->schildren ) { if ( $child->isa('PPI::Structure::List') && !defined $imports ) { $imports = []; } if ( !$child->isa('PPI::Token::QuoteLike::Words') && !$child->isa('PPI::Token::Quote::Single') ) { next; } if ( defined $imports ) { push( @{$imports}, $child->literal ); } else { $imports = [ $child->literal ]; } } return $imports; } sub _extract_symbols_from_snippet { my $snippet = shift; return () unless defined $snippet; # Restore line breaks and tabs $snippet =~ s{\\n}{\n}g; $snippet =~ s{\\t}{\t}g; my $doc = PPI::Document->new( \$snippet ); return () unless defined $doc; my @symbols = map { $_ . q{} } @{ $doc->find('PPI::Token::Symbol') || [] }; my $casts = $doc->find('PPI::Token::Cast') || []; for my $cast ( @{$casts} ) { # PPI Edge Case: False positive casts from regex assertions # # PPI can misinterpret regex assertions like \A as casts. We don't # want to match on "A" in: if ( $thing =~ m{ \A b }x ) { ... } # # See also: Similar PPI edge case for quote operators at line ~596 next if $cast eq '\\'; my $full_cast = $cast . $cast->snext_sibling; my $cast_as_doc = PPI::Document->new( \$full_cast ); push @symbols, map { $_ . q{} } @{ $cast_as_doc->find('PPI::Token::Symbol') || [] }; my $words = $cast_as_doc->find('PPI::Token::Word') || []; ## Turn ${FOO} into $FOO if ( $words && scalar @$words == 1 && $full_cast =~ m/([\$\@\%])\{$words->[0]}/ ) { push @symbols, $1 . $words->[0]; next; } # This could likely be a source of false positives. for my $word (@$words) { push @symbols, "$word" if is_function_call($word); } } return @symbols; } sub _unnest_quotes { my $self = shift; my $token = shift; my @words = @_; if ( !$token->isa('PPI::Token::Quote') || $token->isa('PPI::Token::Quote::Single') ) { return @words; } push @words, _extract_symbols_from_snippet( $token->string ); my $doc = PPI::Document->new( \$token->string ); return @words unless $doc; my $quotes = $doc->find('PPI::Token::Quote'); return @words unless $quotes; for my $q (@$quotes) { # PPI Edge Case: False positive quote operators # # PPI sometimes misinterprets content inside double-quoted strings as # quote operators. For example, when parsing pack("qq", ...), PPI may # identify the bare "qq" as a PPI::Token::Quote even though it's just # a string literal. Calling ->string on these false positives causes # "Use of uninitialized value" errors because they lack actual content. # # Detection: Real quote operators have delimiters (e.g., q{}, qq[], # qw()). False positives are just the bare operator name. # # See also: Similar PPI edge case handling for casts at line ~546 # where regex assertions like \A can be misinterpreted as casts. my $quote_str = "$q"; next if $quote_str =~ m/\A(?:qq?|qw|qx|qr|m|s|tr|y)\z/; push @words, _extract_symbols_from_snippet("$q"); push @words, $self->_unnest_quotes($q); } return @words; } sub _build_interpolated_symbols { my $self = shift; my @symbols; for my $token ( @{ $self->ppi_document->find( sub { ( $_[1]->isa('PPI::Token::Quote') && !$_[1]->isa('PPI::Token::Quote::Single') ) || $_[1]->isa('PPI::Token::Quote::Interpolate') || $_[1]->isa('PPI::Token::QuoteLike::Regexp') || $_[1]->isa('PPI::Token::Regexp'); } ) || [] } ) { if ( $token->isa('PPI::Token::Regexp') || $token->isa('PPI::Token::QuoteLike::Regexp') ) { for my $snippet ( $token->get_match_string, $token->get_substitute_string, ) { push @symbols, _extract_symbols_from_snippet($snippet); } } push @symbols, $self->_unnest_quotes($token); } # Crude hack to catch vars like ${FOO_BAR} in heredocs. for my $heredoc ( @{ $self->ppi_document->find( sub { $_[1]->isa('PPI::Token::HereDoc'); } ) || [] } ) { my $content = join "\n", $heredoc->heredoc; next if $heredoc =~ m{'}; push @symbols, _extract_symbols_from_snippet($content); } # Catch vars like ${FOO_BAR}. This is probably not good enough. for my $cast ( @{ $self->ppi_document->find( sub { $_[1]->isa('PPI::Token::Cast'); } ) || [] } ) { if ( !$cast->snext_sibling || !$cast->snext_sibling->isa('PPI::Structure::Block') ) { next; } my $sigil = $cast . q{}; my $sibling = $cast->snext_sibling . q{}; if ( $sibling =~ m/{(\w+)}/ ) { push @symbols, $sigil . $1; } } my %symbols = map { $_ => 1 } @symbols; return \%symbols; } # Returns a HashRef of modules which will always be converted to avoid imports. # This is mostly for speed and a matter of convenience so that we don't have to # examine modules (like strictly Object Oriented modules) which we know will # not have anything to export. sub _build_never_exports { my $self = shift; my %modules = ( 'App::perlimports::Include' => 1, 'File::Spec' => 1, 'HTTP::Daemon' => 1, 'HTTP::Headers' => 1, 'HTTP::Response' => 1, 'HTTP::Tiny' => 1, 'LWP::UserAgent' => 1, 'URI' => 1, 'WWW::Mechanize' => 1, ); if ( $self->_has_never_export_modules ) { for my $module ( @{ $self->_never_export_modules } ) { $modules{$module} = 1; } } return \%modules; } sub _build_sub_names { my $self = shift; my %sub_names; for my $sub ( @{ $self->ppi_document->find( sub { $_[1]->isa('PPI::Statement::Sub') } ) || [] } ) { my @children = $sub->schildren; if ( $children[0] eq 'sub' && $children[1]->isa('PPI::Token::Word') ) { $sub_names{"$children[1]"} = 1; } } return \%sub_names; } sub _has_import_switches { my $self = shift; my $module_name = shift; # If switches are being passed to import, we can't guess as what is correct # here. # # Getopt::Long uses a leading colon rather than a dash. This overrides # Exporter's defaults. You would normally assume that :config is an export # tag, but instead it's something entirely different. # # use Getopt::Long qw(:config no_ignore_case bundling); # # We will leave this case as broken for the time being. I'm not sure how # common that invocation is. if ( exists $self->found_imports->{$module_name} && any { $_ =~ m{^[\-]} } @{ $self->found_imports->{$module_name} || [] } ) { return 1; } return 0; } sub _is_used_fully_qualified { my $self = shift; my $module_name = shift; # We could tighten this up and check that the word following "::" is a sub # which exists in that package. # # Module::function # Module::->new # isa => ArrayRef[Module::] return 1 if $self->ppi_document->find( sub { ( $_[1]->isa('PPI::Token::Word') && ( $_[1]->content =~ m{\A${module_name}::[a-zA-Z0-9_]*\z} || ( $_[1]->content eq ${module_name} && $_[1]->snext_sibling eq '->' ) || ( $_[1]->content eq ${module_name} && _is_indirect_object_notation( $_[1] ) ) ) ) || ( $_[1]->isa('PPI::Token::Symbol') && $_[1] =~ m{\A[&*\$\@\%]+${module_name}::[a-zA-Z0-9_]} ); } ); # We could combine the regexes, but this is easy to read. for my $key ( keys %{ $self->interpolated_symbols } ) { # package level variable return 1 if $key =~ m{\A[&*\$\@\%]+${module_name}::[a-zA-Z0-9_]+\z}; # function return 1 if $key =~ m/\A${module_name}::[a-zA-Z0-9_]+\z/; } return 0; } # Barewords which precede another bareword but do not introduce indirect object # syntax. These are declaration/import keywords (e.g. "sub Foo", "use Foo"), # where the following bareword is a name being defined or imported rather than a # class being acted upon. my %not_indirect_method = map { $_ => 1 } qw( no package require sub use ); # Detects indirect object syntax such as "new File $path" or "connect Database # $dsn", where a module name is used as the invocant of a method without an # arrow. In PPI this is a bareword whose previous significant sibling is another # bareword (the method name). This is a heuristic: erring towards treating the # module as used is the safe direction, since a false negative would remove an # import which is actually in use. sub _is_indirect_object_notation { my $word = shift; my $prev = $word->sprevious_sibling; return 0 unless ref $prev && $prev->isa('PPI::Token::Word'); # The method name is a simple identifier; a package-qualified name before # the module would not be indirect object syntax. return 0 unless $prev->content =~ m{\A[a-zA-Z_]\w*\z}; return !$not_indirect_method{ $prev->content }; } sub _is_ignored { my $self = shift; my $element = shift; my $res = exists $default_ignore{ $element->module } || exists $self->_ignore_modules->{ $element->module } || $self->_annotations->is_ignored($element) || ( any { $element->module =~ /$_/ } grep { $_ } @{ $self->_ignore_modules_pattern || [] } ) || ( $self->inspector_for( $element->module ) && !$self->inspector_for( $element->module )->evals_ok ); return $res; } sub inspector_for { my $self = shift; my $module = shift; # This would produce a warning and no helpful information. return undef if $module eq 'Exporter'; if ( $self->_has_inspector_for($module) ) { return $self->_get_inspector_for($module); } if ( $self->_cache ) { require Sereal::Decoder; ## no perlimports my $decoder = Sereal::Decoder->new( {} ); my $file = $self->_cache_file_for_module($module); my $inspector; if ( -e $file ) { try { $inspector = $decoder->decode_from_file($file); $self->_set_inspector_for( $module, $inspector ); } catch { $self->logger->error($_); }; if ($inspector) { $self->logger->info("Using cached version of $module"); $inspector->set_logger( $self->logger ); return $inspector; } } } try { $self->_set_inspector_for( $module, App::perlimports::ExportInspector->new( logger => $self->logger, module_name => $module, ) ); } catch { $self->logger->info( 'inspector_for' . $_ ); $self->_set_inspector_for( $module, undef ); }; return $self->_get_inspector_for($module); } # given a PPI:Statement:Include that exists in the doc, # instantiate a App:perlimports:Include to process it. sub _include_analyzer { my ( $self, $include ) = @_; return my $e = App::perlimports::Include->new( document => $self, include => $include, indent => $self->_indent, logger => $self->logger, found_imports => $self->found_imports->{ $include->module }, pad_brackets => $self->_pad_brackets, pad_imports => $self->_padding, preserve_require => $self->_preserve_require, tidy_whitespace => $self->_tidy_whitespace, ); } sub tidied_document { return shift->_lint_or_tidy_document; } sub linter_success { return shift->_lint_or_tidy_document; } # Kind of on odd interface, but right now we return either a tidied document or # the result of linting. Could probably clean this up at some point, but I'm # not sure yet how much the linting will change. # N.B. In lint mode, we never modify the document. sub _lint_or_tidy_document { my $self = shift; my $linter_error = 0; $linter_error = 1 if $self->_sort_lint_error; my %processed; # modules we changed/confirmed the use statement INCLUDE: foreach my $include ( $self->all_includes ) { # If a module is used more than once, that's usually a mistake. if ( !$self->_preserve_duplicates && exists $processed{ $include->module } ) { if ( $self->lint ) { $self->_warn_diff_for_linter( 'has already been used and should be removed', $include, $include->content, q{} ); $linter_error = 1; next INCLUDE; } $self->logger->info( $include->module . ' has already been used. Removing at line ' . $include->line_number ); _remove_with_trailing_characters($include); next INCLUDE; } $self->logger->notice( '📦 ' . "Processing include: $include" ); my $e = $self->_include_analyzer($include); my $elem; try { # may return the original include! $elem = $e->formatted_ppi_statement; } catch { my $error = $_; $self->logger->error( 'Error in ' . $self->_filename ); $self->logger->error( 'Trying to format: ' . $include ); $self->logger->error( 'Error is: ' . $error ); }; next INCLUDE unless $elem; # If this is a module with bare imports which is not used anywhere, # maybe we can just remove it. if ( !$self->_preserve_unused ) { my @args = $elem->arguments; if ( $args[0] && $args[0] eq '()' && !$self->_is_used_fully_qualified( $include->module ) ) { # This include no longer imports anything, so later includes # must not rely on it for symbols it used to import. $self->_reset_found_import( $include->module, [] ); if ( $self->lint ) { $self->_warn_diff_for_linter( 'appears to be unused and should be removed', $include, $include->content, q{} ); $linter_error = 1; next INCLUDE; } $self->logger->info( 'Removing ' . $include->module . ' as it appears to be unused' ); _remove_with_trailing_characters($include); next INCLUDE; } } # if the 'new' statement is actually just the original, skip! if ( $elem == $include ) { $processed{ $include->module } = 1; next INCLUDE; } ## no critic (Subroutines::ProhibitCallsToUnexportedSubs) # Let's see if the import itself might break something if ( my $err = App::perlimports::Sandbox::eval_pkg( $elem->module, "$elem" ) ) { $self->logger->warning( sprintf( 'New include (%s) triggers error (%s)', $elem, $err ) ); next INCLUDE; } ## use critic my $inserted = $include->replace($elem); if ( !$inserted ) { $self->logger->error( 'Could not insert ' . $elem ); } else { $processed{ $include->module } = 1; $self->logger->info("resetting imports for |$elem|"); # Track what this include will import once tidied, in lint mode # too, so that later includes are checked against it. $self->_reset_found_import( $include->module, _imports_for_include($elem) ); if ( $self->lint ) { my $before = join q{ }, map { $_->content } $include->arguments; my $after = join q{ }, map { $_->content } $elem->arguments; if ( $before ne $after ) { $self->_warn_diff_for_linter( 'import arguments need tidying', $include, $include->content, $elem->content ); $linter_error = 1; } next INCLUDE; } } } $self->_maybe_cache_inspectors; # We need to do serialize in order to preserve HEREDOCs. # See https://metacpan.org/pod/PPI::Document#serialize return !$linter_error if $self->lint; return $self->_tidied_and_sorted; } # Returns 1 (and warns via the linter) if we're linting with --sort enabled # and the current includes are not in sorted order; returns 0 otherwise. sub _sort_lint_error { my $self = shift; return 0 unless $self->lint && $self->_sort; my $before = $self->_ppi_selection->serialize; my $after = App::perlimports::Sorter->new( logger => $self->logger, source => $before, )->sorted_document; return 0 if $before eq $after; $self->_warn_unsorted_includes( $before, $after ); return 1; } # Serializes the tidied document and, when --sort is enabled, reorders its # include statements. sub _tidied_and_sorted { my $self = shift; my $tidied = $self->_ppi_selection->serialize; return $tidied unless $self->_sort; return App::perlimports::Sorter->new( logger => $self->logger, source => $tidied, )->sorted_document; } # given PPI:Element, returns hashref describing location, e.g.: # {start => {line => 3, column => 4}, end => {...}} sub _elem_loc { my ($elem) = @_; my $line = $elem->line_number; my $column = $elem->column_number; my $content = $elem->content; my @lines = split( m{\n}, $content ); my $loc = { start => { line => $line, column => $column } }; if ( @lines <= 1 ) { # A single-line statement's own indentation is not part of its # content, so the (inclusive) end column is measured from the start # column rather than from column 1. $loc->{end} = { line => $line, column => $column + length( $lines[0] // q{} ) - 1, }; } else { # Continuation lines begin at column 1 and their leading whitespace is # part of the statement content, so the final line's length is already # the absolute end column. $loc->{end} = { line => $line + @lines - 1, column => length( $lines[-1] ), }; } return $loc; } sub _warn_diff_for_linter { my $self = shift; my $reason = shift; my $include = shift; my $before = shift; my $after = shift; my $after_deleted = !$after; my $json; my $justification; if ( $self->json ) { $json = { filename => $self->_filename, location => _elem_loc($include), module => $include->module, reason => $reason, }; } else { $justification = sprintf( '❌ %s (%s) at %s line %i', $include->module, $reason, $self->_filename, $include->line_number ); } my $padding = $include->line_number - 1; $before = sprintf( "%s%s\n", "\n" x $padding, $before ); $after = sprintf( "%s%s\n", "\n" x $padding, $after ); chomp $after if $after_deleted; my $diff = Text::Diff::diff( \$before, \$after, { CONTEXT => 0, STYLE => 'Unified', } ); if ( $self->json ) { $json->{diff} = $diff; $self->logger->error( $self->_json_encoder->encode($json) ); } else { $self->logger->error($justification); $self->logger->error($diff); } } sub _warn_unsorted_includes { my ( $self, $before, $after ) = @_; my $reason = 'includes are not sorted'; # Use CONTEXT => 0 for parity with the per-include diagnostic # (_warn_diff_for_linter): the before/after are full-document # serializations whose line numbers already align, so surrounding context # lines would only bloat the output and diverge from the other shape. my $diff = Text::Diff::diff( \$before, \$after, { CONTEXT => 0, STYLE => 'Unified', } ); if ( $self->json ) { # Unlike a per-include diagnostic, this reports a reordering rather # than a single include, so there's no module to attach and we omit # "module" entirely. The location spans the lines that actually # changed rather than every include in the file: a `require` buried in # a sub far below never participates in a top-of-file reordering. my $json = { filename => $self->_filename, reason => $reason, diff => $diff, }; my $location = _changed_line_span( $before, $diff ); $json->{location} = $location if $location; $self->logger->error( $self->_json_encoder->encode($json) ); return; } $self->logger->error( sprintf( '❌ %s (%s)', $self->_filename, $reason ) ); $self->logger->error($diff); return; } # Given the original document ($before) and the unified diff describing the # reordering, return the 1-indexed line/column span of the original lines the # diff touches. This keeps a document-wide sort diagnostic pointed at the # reordered includes rather than at unrelated includes elsewhere in the file # (a `require` buried in a sub far below never participates in a top-of-file # reordering). Deriving the span from the diff -- rather than comparing lines # positionally -- is important because the Sorter can insert a blank line # after the hoisted pragmas, which shifts every following line and would make # a positional comparison flag the whole tail of the file. Columns are # 1-indexed and inclusive. When the change touches multiple non-contiguous # blocks the span covers the first changed line through the last. Returns # undef when the diff has no hunks (the caller only reaches here when the # versions differ). sub _changed_line_span { my ( $before, $diff ) = @_; # Unified hunk headers look like "@@ -L,S +l,s @@". A missing S means 1; # S == 0 marks a pure insertion positioned after original line L. We take # the union of the original-file ranges the hunks touch. my ( $first_elem, $last_elem ); while ( $diff =~ m{^\@\@ \s+ [-](\d+) (?: [,](\d+) )? \s}gmx ) { my ( $start, $size ) = ( $1, defined $2 ? $2 : 1 ); my $end = $size > 0 ? $start + $size - 1 : $start; $first_elem = $start if !defined $first_elem || $start < $first_elem; $last_elem = $end if !defined $last_elem || $end > $last_elem; } return unless defined $first_elem; my @before = split( m{\n}, $before, -1 ); my $start_line = $before[ $first_elem - 1 ]; my $start_column = ( defined $start_line && $start_line =~ m{\S} ) ? $-[0] + 1 : 1; return { start => { line => $first_elem, column => $start_column }, end => { line => $last_elem, column => length( $before[ $last_elem - 1 ] // q{} ) || 1, }, }; } sub _remove_with_trailing_characters { my $include = shift; while ( my $next = $include->next_sibling ) { if ( !$next->isa('PPI::Token::Whitespace') && !$next->isa('PPI::Token::Comment') ) { last; } $next->remove; last if $next eq "\n"; } $include->remove; return; } sub _build_cache_dir { my $base_path = defined $ENV{HOME} && -d path( $ENV{HOME}, '.cache' ) ? path( $ENV{HOME}, '.cache' ) : path('/tmp'); my $cache_dir = $base_path->child( 'perlimports', $VERSION ); $cache_dir->mkpath; return $cache_dir; } sub _cache_file_for_module { my $self = shift; my $module = shift; return $self->_cache_dir->child($module); } sub _maybe_cache_inspectors { my $self = shift; return unless $self->_cache; my @names = sort $self->all_inspector_names; $self->logger->info('maybe cache'); return unless @names; my $append = 0; require Sereal::Encoder; ## no perlimports my $encoder = Sereal::Encoder->new( { croak_on_bless => 0, undef_unknown => 1, } ); for my $name ( $self->all_inspector_names ) { my $file = $self->_cache_file_for_module($name); next if -e $file; $self->logger->info("I would like to cache $name at $file"); $encoder->encode_to_file( $file, $self->inspector_for($name), $append ); } return; } sub _is_word_interpreted_as_string { my ($word) = @_; return unless $word->statement && $word->isa('PPI::Token::Word'); my @children = $word->statement->schildren; # https://perldoc.perl.org/perlref#Not-so-symbolic-references return 1 if is_hash_key($word) && @children == 1; # The => operator (sometimes pronounced "fat comma") is a synonym for # the comma except that it causes a word on its left to be interpreted # as a string if it begins with a letter or underscore and is composed # only of letters, digits and underscores. This includes operands that # might otherwise be interpreted as operators, constants, single number # v-strings or function calls. # https://perldoc.perl.org/perlop#Comma-Operator return unless $word->content =~ /^[a-zA-Z_][a-zA-Z0-9_]*$/; while ( my $current = shift @children ) { last if refaddr($current) == refaddr($word); } return unless ( my $current = shift @children ); return 1 if $current->isa('PPI::Token::Operator') && $current->content eq '=>'; } 1; # ABSTRACT: Make implicit imports explicit __END__ =pod =encoding UTF-8 =head1 NAME App::perlimports::Document - Make implicit imports explicit =head1 VERSION version 0.000067 =head1 MOTIVATION This module is to be used internally by L. It shouldn't be relied upon by anything else. =head2 inspector_for( $module_name ) Returns an L object for the given module. =head2 linter_success Returns true if document was linted without errors, otherwise false. =head2 tidied_document Returns a serialized PPI document with (hopefully) tidy import statements. =head1 ATTRIBUTES =over 4 =item constants Hashref catalog of detected constants in the document. So the line: use constant FIRST_IDX => 0; results in a corresponding entry in the constants hashref: FIRST_IDX => { name => 'FIRST_IDX', # (plain string) token => 'FIRST_IDX', # (PPI::Token::Word usually) definition => [ PPI::Token.. ], end => { line => 9, column => 32 }, }, The C is the (line, character) position of the last character of the constant import statement. This might be useful since the constant is only defined (at compile time!) after this statement. (Note: locations can become stale!) The C field is useful when the constant was defined using atypical syntax (no fat arrow), since the token doesn't stringify the same: use constant 'FIRST_IDX', 0; # token eq "'FIRST_IDX'", # (PPI::Token::Quote::Single) # name eq 'FIRST_IDX', # same as $token->string =item includes An arrayref of L statements found in the document, excluding pragmas, ignored modules, and 'use VERSION' statements. =item found_imports A hashref catalog of symbols imported from each package by a use statement, e.g. { Carp => ['croak', ..], ... } When L or L is called, with each include that gets processed, this list gets updated to what we think it should be (an empty list if the include is removed as unused). Lint mode updates this attribute too, even though it never modifies the document. We do this so that we can keep track of what previous modules are really importing, to avoid duplicate imports (same symbol name from different packages). =back =head1 AUTHOR Olaf Alders =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2020 by Olaf Alders. 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 SubExporter.t100644001750001751 554015261510600 22235 0ustar00olafolaf000000000000App-perlimports-0.000067/t/ExportInspector#!perl use strict; use warnings; use lib 't/lib', 'test-data/lib'; use Test::Differences qw( eq_or_diff ); use Test::More import => [qw( done_testing is is_deeply ok subtest )]; use TestHelper qw( inspector ); use Test::Needs qw( Import::Into MetaCPAN::Moose Moose MooseX::Types::Moose MooseX::Types::Path::Class Path::Class ); subtest 'Moose Type Library' => sub { my ($inspector) = inspector('Local::MooseTypeLibrary'); my $exports = $inspector->explicit_exports; is( $exports->{is_Bool}, 'Bool', 'is_ aliased' ); is( $exports->{to_File}, 'File', 'to_ aliased' ); ok( !exists $exports->{to_Str}, 'Coercion does not exist' ); }; subtest 'Moo' => sub { my ($inspection) = inspector('Moo'); is_deeply( $inspection->implicit_exports, { after => 'after', around => 'around', before => 'before', extends => 'extends', has => 'has', with => 'with', }, 'exports' ); }; subtest 'ViaSubExporter' => sub { my ($inspector) = inspector('Local::ViaSubExporter'); is_deeply( $inspector->explicit_exports, { bar => 'bar', foo => 'foo', }, 'exports' ); }; subtest 'MyOwnMoose' => sub { my ($inspector) = inspector('Local::MyOwnMoose'); is_deeply( $inspector->implicit_exports, { after => 'after', around => 'around', augment => 'augment', before => 'before', blessed => 'blessed', confess => 'confess', extends => 'extends', has => 'has', inner => 'inner', isa => 'isa', meta => 'meta', override => 'override', super => 'super', with => 'with', }, 'exports' ); }; subtest 'MetaCPAN::Moose' => sub { my ( $inspector, $log ) = inspector('MetaCPAN::Moose'); my $expected_export_list = { after => 'after', around => 'around', augment => 'augment', before => 'before', blessed => 'blessed', confess => 'confess', extends => 'extends', has => 'has', inner => 'inner', isa => 'isa', meta => 'meta', override => 'override', super => 'super', with => 'with', }; is_deeply( $inspector->implicit_exports, $expected_export_list, 'exports' ); ( $inspector, $log ) = inspector('MetaCPAN::Moose'); # Test again to ensure code can still run after removing and re-importing # Import::Into. eq_or_diff( $inspector->implicit_exports, $expected_export_list, 'exports' ); }; done_testing(); missing-semicolon-in-import.t100644001750001751 77515261510600 22143 0ustar00olafolaf000000000000App-perlimports-0.000067/tuse strict; use warnings; use lib 't/lib'; use Test::Differences qw( eq_or_diff ); use TestHelper qw( doc ); use Test::More import => [qw( diag done_testing )]; my ( $doc, $log ) = doc( filename => 'test-data/missing-semicolon-in-import.pl' ); my $expected = <<'EOF'; use strict; use warnings; use Carp use POSIX; EOF eq_or_diff( $doc->tidied_document, $expected, 'broken imports are untouched' ) || do { require Data::Dumper; diag Data::Dumper::Dumper($log); }; done_testing(); via-sub-exporter-exception.pl100755001750001751 62615261510600 22146 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!perl use strict; use warnings; use lib 'test-data/lib', 't/lib'; use Path::Tiny qw( path ); use TestHelper qw( doc ); use Test::More import => [qw( done_testing is )]; my $filename = 'test-data/via-sub-exporter-exception.pl'; my ($doc) = doc( filename => $filename, preserve_unused => 0, ); is( $doc->tidied_document, path($filename)->slurp, 'doc has not changed' ); done_testing(); exported-variables.pl100644001750001751 16215261510600 22151 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Local::ViaExporter qw( %foo @foo ); print $foo[0]; print $foo{bar}; print ${foo}; function-reference.pl100644001750001751 20615261510600 22131 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Cpanel::JSON::XS; my $true_ref = \&Cpanel::JSON::XS::true; my $false_ref = \&Cpanel::JSON::XS::false; Explodes.pm100644001750001751 23715261510600 21740 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/lib/Localpackage Local::Explodes; use strict; use warnings; BEGIN { die 'oof'; } require Exporter; our @EXPORT = qw(foo); sub foo { return 'from sub foo' } 1; LongList.pm100644001750001751 56515261510600 21714 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/lib/Localpackage Local::LongList; use strict; use warnings; use Exporter qw( import ); sub alpha { } sub bravo { } sub charlie { } sub delta { } sub echo { } sub foxtrot { } sub golf { } sub hotel { } sub india { } sub juliet { } our @EXPORT_OK = qw( alpha bravo charlie delta echo foxtrot golf hotel india juliet ); 1; MyOwnMoo.pm100644001750001751 22015261510600 21671 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/lib/Localpackage Local::MyOwnMoo; use strict; use warnings; use Import::Into; sub import { $_->import::into( scalar caller ) for qw( Moo ); } 1; NoImport.pm100644001750001751 67215261510600 21727 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/lib/Localpackage Local::NoImport; use strict; use warnings; our $VERSION = '1.00'; # Intentionally defines no import() method and no exports. Calling # `use Local::NoImport qw( ... )` therefore makes Perl emit its "Attempt to # call undefined/missing import method" diagnostic. t/Sandbox.t uses this to # verify App::perlimports::Sandbox suppresses that trial-load noise, whatever # wording the running Perl uses for the warning (see GH #181). 1; moosex-types-moose.pl100644001750001751 26315261510600 22147 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use MooseX::Types::Moose qw( ArrayRef Str); use MooseX::Types -declare => [ qw( Module ) ]; # exports subtype, as subtype Module, as ArrayRef [ Str ]; qualified-bareword.pl100644001750001751 12515261510600 22116 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Path::Tiny; my $path = Path::Tiny::->new('foo.txt'); switches-in-import.pl100644001750001751 12015261510600 22110 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use CustomImport qw( -ignore blib -ignore \\wB\\w ); moose-type-library-with-meta.t100644001750001751 154715261510600 22246 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!/usr/bin/env perl use strict; use warnings; use lib 't/lib', 'test-data/lib'; use TestHelper qw( doc inspector ); use Test::More import => [qw( done_testing is ok )]; use Test::Needs qw( MooseX::Types ); # A MooseX::Types type library which also has a Moose metaclass, as type # libraries did with MooseX::Types 0.50. See GH#202. my ($ei) = inspector('Local::MooseTypeLibraryWithMeta'); ok( $ei->uses_moose, 'library has a Moose metaclass' ); ok( $ei->is_moose_type_class, 'library is a Moose type class' ); ok( !$ei->is_moose_class, 'library is not a Moose class' ); my ($doc) = doc( filename => 'test-data/moose-type-library-with-meta.pl', selection => 'use Local::MooseTypeLibraryWithMeta;', ); is( $doc->tidied_document, 'use Local::MooseTypeLibraryWithMeta qw( TheType );', 'missing type import is added' ); done_testing; annotate-everything.pl100644001750001751 14715261510600 22347 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data## no perlimports use strict; use warnings; use Carp; use Cwd; use Digest; use Encode; use POSIX (); hash-key-expression.pl100644001750001751 16215261510600 22257 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use HTTP::Status qw(is_info); my %foo; my $code = 100; $foo{ is_info $code } = 'bar'; MaxFacade.pm100644001750001751 27315261510600 21766 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/lib/Localpackage Local::MaxFacade; use strict; use warnings; use Exporter qw( import ); use Local::MaxA qw( max ); our @EXPORT_OK = qw( max facade_only ); sub facade_only { return 'f' } 1; UsesMoose.pm100644001750001751 20115261510600 22066 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/lib/Localpackage Local::UsesMoose; use Moose; has foo => ( is => 'ro', isa => 'Str', ); __PACKAGE__->meta->make_immutable; 1; sort-includes-multi.pl100644001750001751 6715261510600 22260 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use Foo; use Bar; use Zoo; use Apple; 1; symbol-in-signature.pl100644001750001751 11715261510600 22261 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use HTTP::Status; sub foo ( $status = HTTP_OK ) {} same-symbol-different-modules.t100644001750001751 1174215261510600 22466 0ustar00olafolaf000000000000App-perlimports-0.000067/t#!perl use strict; use warnings; use lib 'test-data/lib', 't/lib'; use PPI::Document (); use Test::Differences qw( eq_or_diff ); use TestHelper qw( doc ); use Test::More import => [qw( diag done_testing is ok subtest )]; # GH#197: when the same symbol is imported from more than one module, it must # stay imported by at least one of them. It is kept on the last import, since # that is the one which wins at runtime. sub _doc { my $source = shift; return doc( filename => 'none', ppi_document => PPI::Document->new( \$source ), @_, ); } sub _script { my $imports = shift; my $calls = shift; return <<"EOF"; use strict; use warnings; $imports $calls EOF } my @cases = ( { name => 'same symbol only, two modules', imports => "use Local::MaxA qw( max );\nuse Local::MaxB qw( max );", calls => 'max();', tidied => 'use Local::MaxB qw( max );', }, { name => 'same symbol plus other symbols, two modules', imports => "use Local::MaxA qw( max a_only );\nuse Local::MaxB qw( max b_only );", calls => 'max(); a_only(); b_only();', tidied => "use Local::MaxA qw( a_only );\nuse Local::MaxB qw( b_only max );", }, { name => 'same symbol only, re-exported by a facade', imports => "use Local::MaxA qw( max );\nuse Local::MaxFacade qw( max );", calls => 'max();', tidied => 'use Local::MaxFacade qw( max );', }, { name => 'same symbol plus other symbols, re-exported by a facade', imports => "use Local::MaxA qw( max );\nuse Local::MaxFacade qw( max facade_only );", calls => 'max(); facade_only();', tidied => 'use Local::MaxFacade qw( facade_only max );', }, ); for my $case (@cases) { subtest "tidy without preserve_unused: $case->{name}" => sub { my ($doc) = _doc( _script( $case->{imports}, $case->{calls} ), preserve_unused => 0, ); is( $doc->tidied_document, _script( $case->{tidied}, $case->{calls} ), 'used symbol is still imported' ); }; } subtest 'tidy with preserve_unused: same symbol only, two modules' => sub { my ($doc) = _doc( _script( $cases[0]{imports}, $cases[0]{calls} ) ); is( $doc->tidied_document, _script( "use Local::MaxA ();\nuse Local::MaxB qw( max );", $cases[0]{calls} ), 'max is kept on the last import' ); }; for my $case ( @cases[ 0, 1 ] ) { for my $preserve_unused ( 0, 1 ) { subtest "lint (preserve_unused => $preserve_unused): $case->{name}" => sub { my ( $doc, $log ) = _doc( _script( $case->{imports}, $case->{calls} ), lint => 1, preserve_unused => $preserve_unused, ); is( $doc->linter_success, q{}, 'lint fails' ); my $diff = join "\n", map { $_->{message} } grep { $_->{message} =~ /^[-+]/m } @{$log}; # MaxB must either be left alone or be rewritten to keep max. ok( $diff !~ m{^-use Local::MaxB\b}m || $diff =~ m{^\+use Local::MaxB\b.*\bmax\b}m, 'lint does not ask MaxB to drop max' ) or diag $diff; ok( $diff =~ m{^-use Local::MaxA}m, 'lint asks to change the MaxA import' ) or diag $diff; }; } } for my $preserve_unused ( 0, 1 ) { subtest "exact lint errors (preserve_unused => $preserve_unused): $cases[1]{name}" => sub { my ( $doc, $log ) = _doc( _script( $cases[1]{imports}, $cases[1]{calls} ), lint => 1, preserve_unused => $preserve_unused, ); is( $doc->linter_success, q{}, 'lint fails' ); ## no critic (ValuesAndExpressions::ProhibitImplicitNewlines) eq_or_diff( [ grep { $_->{level} eq 'error' } @{$log} ], [ { level => 'error', message => "\x{274c}" . ' Local::MaxA (import arguments need tidying) at none line 4', }, { level => 'error', message => '@@ -4 +4 @@ -use Local::MaxA qw( max a_only ); +use Local::MaxA qw( a_only ); ', }, { level => 'error', message => "\x{274c}" . ' Local::MaxB (import arguments need tidying) at none line 5', }, { level => 'error', message => '@@ -5 +5 @@ -use Local::MaxB qw( max b_only ); +use Local::MaxB qw( b_only max ); ', }, ], 'linting errors logged' ); }; } done_testing(); carp-with-no-imports.pl100644001750001751 6415261510600 22335 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Carp; croak('oof'); carp-without-verbose.pl100644001750001751 10015261510600 22432 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Carp qw( croak ); croak('oof'); english-program-name.pl100644001750001751 12615261510600 22365 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use English qw( $PROGRAM_NAME ); print "$PROGRAM_NAME\n"; MyOwnMoose.pm100644001750001751 22415261510600 22225 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/lib/Localpackage Local::MyOwnMoose; use strict; use warnings; use Import::Into; sub import { $_->import::into( scalar caller ) for qw( Moose ); } 1; sort-includes-sorted.pl100644001750001751 5415261510600 22422 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use Bar; use Baz; use Foo; 1; Annotations.pm100755001750001751 567515261510600 22670 0ustar00olafolaf000000000000App-perlimports-0.000067/lib/App/perlimportspackage App::perlimports::Annotations; # Some of this logic was lifted directly from Perl::Critic::Annotation use Moo; our $VERSION = '0.000067'; use Types::Standard qw( ArrayRef Object ); has _annotations => ( is => 'ro', isa => ArrayRef, lazy => 1, builder => '_build_annotations', ); has _ppi_document => ( is => 'ro', isa => Object, init_arg => 'ppi_document', required => 1, ); sub _build_annotations { my $self = shift; my @found = (); my $comments = $self->_ppi_document->find('PPI::Token::Comment') || return []; my $disable_rx = qr{[#][#] \s* no \s+ perlimports}xms; my $enable_rx = qr{[#][#] \s* use \s+ perlimports}xms; my @enabled = ( grep { $_ =~ $enable_rx } @{$comments} ); for my $element ( grep { $_ =~ $disable_rx } @{$comments} ) { my %found = ( column_number => $element->column_number, line_number => $element->logical_line_number, range => [ $element->logical_line_number, $element->column_number > 1 ? ( $element->logical_line_number ) : () ], ); # Seek ahead to see if/when perlimpts is re-enabled if ( $element->column_number == 1 ) { for my $on (@enabled) { if ( $on->column_number == 1 && $on->logical_line_number > $element->logical_line_number ) { $found{range}->[1] = $on->logical_line_number; } } } push @found, \%found; } return \@found; } sub is_ignored { my $self = shift; my $element = shift; unless ( $element && ref($element) && $element->isa('PPI::Element') ) { die 'PPI::Element required'; } my $line = $element->logical_line_number; for my $a ( @{ $self->_annotations } ) { my ( $min, $max ) = @{ $a->{range} }; if ( $line >= $min && ( !$max || $line <= $max ) ) { return 1; } # Any further annotations do not apply to this element last if $line < $max; } return 0; } 1; # ABSTRACT: Find line ranges where perlimports has been disabled __END__ =pod =encoding UTF-8 =head1 NAME App::perlimports::Annotations - Find line ranges where perlimports has been disabled =head1 VERSION version 0.000067 =head1 SYNOPSIS my $anno = App::perlimports::Annotations->new( ppi_document => $ppi_doc ); print 'skip include' if $anno->is_ignored( $ppi_element ); =head2 is_ignored( $ppi_element ) Returns true if the provided L is in an ignored line range. =head1 AUTHOR Olaf Alders =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2020 by Olaf Alders. 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 Role000755001750001751 015261510600 20556 5ustar00olafolaf000000000000App-perlimports-0.000067/lib/App/perlimportsLogger.pm100644001750001751 143215261510600 22473 0ustar00olafolaf000000000000App-perlimports-0.000067/lib/App/perlimports/Rolepackage App::perlimports::Role::Logger; use Moo::Role; our $VERSION = '0.000067'; use Types::Standard qw( InstanceOf ); has logger => ( is => 'ro', isa => InstanceOf ['Log::Dispatch'], predicate => '_has_logger', writer => 'set_logger', ); 1; # ABSTRACT: Provide a logger attribute to App::perlimports objects __END__ =pod =encoding UTF-8 =head1 NAME App::perlimports::Role::Logger - Provide a logger attribute to App::perlimports objects =head1 VERSION version 0.000067 =head1 AUTHOR Olaf Alders =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2020 by Olaf Alders. 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 ViaExporter.pm100644001750001751 33715261510600 22426 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/lib/Localpackage Local::ViaExporter; use strict; use warnings; use Exporter 'import'; our @EXPORT = qw(foo $foo @foo %foo); sub foo { return 'from sub foo' } our $foo = 1; our @foo = ( 1 .. 10 ); our %foo = ( foo => 'bar' ); 1; never-export-modules.txt100644001750001751 3115261510600 22634 0ustar00olafolaf000000000000App-perlimports-0.000067/test-dataNever::Three Never::Four preserve-some-padding.pl100644001750001751 11315261510600 22545 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Carp qw( croak verbose ); croak('oof'); symbol-as-method-call.pl100644001750001751 17615261510600 22453 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use HTML::TableExtract; use Object::Tap; my $te = HTML::TableExtract->new->$_tap(parse => $html); various-quote-strings.pl100644001750001751 144415261510600 22707 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; # Test various quote-like strings that should not cause errors use List::Util; # Simple cases from the issue my $str1 = "q"; my $str2 = "qq"; # Other quote operators my $str3 = "qw"; my $str4 = "qx"; my $str5 = "qr"; # Regex operators my $str6 = "m"; my $str7 = "s"; my $str8 = "tr"; my $str9 = "y"; # Combinations my $str10 = "q and qq"; my $str11 = pack("qq", 10, 0); # Words that start with these letters but aren't operators my $str12 = "quest"; my $str13 = "query"; my $str14 = "queue"; # Real quote operators that should still be processed correctly my $str15 = q{single quoted string}; my $str16 = qq[double quoted string]; my @str17 = qw(list of words); my $str18 = qr/regex pattern/; my $str19 = q(nested (parens) work); my $str20 = qq|alternative delimiters|; indirect-object-syntax.pl100644001750001751 31015261510600 22735 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; my $file = new File $path, $data; my $conn = connect Database $dsn; my $json = JSON::PP->new; use Unused; no Forbidden; require Deferred; package Ignored; sub Widget { } CustomImport.pm100644001750001751 11415261510600 22614 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/lib/Localpackage Local::CustomImport; use strict; use warnings; sub import { } 1; UsesMyOwnMoo.pm100644001750001751 12215261510600 22532 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/lib/Localpackage Local::UsesMyOwnMoo; use strict; use warnings; use Local::MyOwnMoo; 1; WithInnerPkg.pm100644001750001751 52515261510600 22526 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/lib/Local use warnings; package Local::WithInnerPkg; use HTTP::Status qw( HTTP_FOUND HTTP_OK ); sub foo { HTTP_OK(); } 1; package MyInnerPkgOne; use HTTP::Status qw( HTTP_CREATED HTTP_FOUND ); sub foo { HTTP_CREATED(); } 1; package MyInnerPkgTwo; use HTTP::Status qw( HTTP_ACCEPTED HTTP_FOUND ); sub foo { HTTP_ACCEPTED(); } 1; sort-includes-comments.pl100644001750001751 6015261510600 22744 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data# uses Foo use Foo; # foo trailing use Bar; 1; ignore-modules-pattern.txt100644001750001751 3315261510600 23136 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data ^(Foo|Foo::Bar) ^(CGI::*) SymbolInExport.pm100644001750001751 26615261510600 23115 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/lib/Localpackage Local::SymbolInExport; use strict; use warnings; use HTTP::Request::Common; use base 'Exporter'; our @EXPORT = ( 'DELETE' ); our @EXPORT_OK = qw( GET POST ); UsesMyOwnMoose.pm100644001750001751 12615261510600 23066 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/lib/Localpackage Local::UsesMyOwnMoose; use strict; use warnings; use Local::MyOwnMoose; 1; ViaSubExporter.pm100644001750001751 25615261510600 23100 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/lib/Localpackage Local::ViaSubExporter; use strict; use warnings; use Sub::Exporter -setup => { exports => [ 'bar', 'foo', ] }; sub bar { } sub foo { } 1; lint-failure-import-args.pl100644001750001751 14215261510600 23204 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Perl::Critic::Utils; my %foo = ( $QUOTE => q{description}, ); ExportInspector.pm100644001750001751 3770415261510600 23556 0ustar00olafolaf000000000000App-perlimports-0.000067/lib/App/perlimportspackage App::perlimports::ExportInspector; use Moo; ## no critic (Modules::RequireExplicitInclusion, Subroutines::ProhibitCallsToUnexportedSubs, TestingAndDebugging::ProhibitNoStrict) our $VERSION = '0.000067'; use App::perlimports::Sandbox (); use Class::Inspector (); use List::Util qw( any ); use Module::Runtime qw( require_module ); use Sub::HandlesVia; use Try::Tiny qw( catch try ); use Types::Standard qw(ArrayRef Bool HashRef Int InstanceOf Str); with 'App::perlimports::Role::Logger'; has at_export => ( is => 'ro', isa => ArrayRef [Str], lazy => 1, default => sub { shift->_implicit->{export} }, ); # Explicit accessor rather than a Sub::HandlesVia 'count' delegation. Array # handlers route through the Sub::HandlesVia::XS backend, whose XS array handler # caches the Perl stack pointer across the attribute builder's call_sv and can # write through it after the builder has reallocated the stack. See issue #171. sub has_at_export { return scalar @{ $_[0]->at_export }; } has at_export_ok => ( is => 'ro', isa => ArrayRef [Str], lazy => 1, default => sub { shift->_implicit->{export_ok} }, ); # Explicit accessor rather than a Sub::HandlesVia 'count' delegation; see the # note on has_at_export above and issue #171. (An unused 'elements' delegation # was dropped here at the same time.) sub has_at_export_ok { return scalar @{ $_[0]->at_export_ok }; } has at_export_fail => ( is => 'ro', isa => ArrayRef [Str], lazy => 1, default => sub { shift->_implicit->{export_fail} }, ); has at_export_tags => ( is => 'ro', isa => ArrayRef [Str], lazy => 1, default => sub { shift->_implicit->{export_tags} }, ); has class_isa => ( is => 'ro', isa => ArrayRef [Str], lazy => 1, default => sub { shift->_implicit->{class_isa} }, ); has has_fatal_error => ( is => 'ro', isa => Bool, lazy => 1, default => sub { my $self = shift; ( $self->_implicit->{fatal_error} || $self->explicit_exports->{fatal_error} ) ? 1 : 0; }, ); has _implicit => ( is => 'ro', isa => HashRef, lazy => 1, builder => '_build_implicit', ); has import_flags => ( is => 'ro', isa => ArrayRef, lazy => 1, builder => '_build_import_flags', ); # Explicit accessor rather than a Sub::HandlesVia 'count' delegation; see the # note on has_at_export above and issue #171. sub has_import_flags { return scalar @{ $_[0]->import_flags }; } has is_exporter => ( is => 'ro', isa => Bool, lazy => 1, builder => '_build_is_exporter', ); has isa_test_builder => ( is => 'ro', isa => Bool, lazy => 1, builder => '_build_isa_test_builder', ); has explicit_exports => ( is => 'ro', isa => HashRef, lazy => 1, handles_via => 'Hash', handles => { has_explicit_exports => 'count', explicit_export_names => 'keys', explicit_export_values => 'values', }, builder => '_build_explicit_exports', ); has implicit_exports => ( is => 'ro', isa => HashRef, lazy => 1, handles_via => 'Hash', handles => { has_implicit_exports => 'count', implicit_export_names => 'keys', implicit_export_values => 'values', }, builder => '_build_implicit_exports', ); sub _build_implicit_exports { my $self = shift; my $pkg = $self->_pkg_for_implicit; return $self->is_exporter ? $self->_list_to_hash( $pkg, $self->at_export ) : $self->_list_to_hash( $pkg, $self->_implicit->{_maybe_exports} ); } has is_moose_class => ( is => 'ro', isa => Bool, lazy => 1, builder => '_build_is_moose_class', ); has is_moo_class => ( is => 'ro', isa => Bool, lazy => 1, builder => '_build_is_moo_class', ); has is_moose_type_class => ( is => 'ro', isa => Bool, lazy => 1, builder => '_build_is_moose_type_class', ); has is_oo_class => ( is => 'ro', isa => Bool, lazy => 1, builder => '_build_is_oo_class', ); has _module_name => ( is => 'ro', isa => Str, init_arg => 'module_name', required => 1, ); has pkg_isa => ( is => 'ro', isa => ArrayRef [Str], lazy => 1, default => sub { no strict 'refs'; return [ @{ shift->_pkg_for_implicit . '::ISA' } ]; }, ); has _pkg_for_implicit => ( is => 'ro', isa => Str, lazy => 1, default => sub { return shift()->_random_pkg_name }, ); has success_counter => ( traits => ['Counter'], is => 'ro', isa => Int, default => 0, handles => { _increment_success_counter => 'inc', }, ); has uses_moose => ( is => 'ro', isa => Bool, lazy => 1, builder => '_build_uses_moose', ); sub evals_ok { my $self = shift; $self->explicit_exports; $self->implicit_exports; return $self->success_counter; } sub _build_explicit_exports { my $self = shift; # If this is Exporter, then the exportable symbols will be listed in either # @EXPORT or @EXPORT_OK. Maybe in both? if ( $self->has_at_export_ok || $self->has_at_export ) { return $self->_list_to_hash( $self->_pkg_for_implicit, # reuse package name [ @{ $self->at_export }, @{ $self->at_export_ok } ] ); } # If this is Sub::Exporter, we can cheat and see what's in the :all tag my $pkg = $self->_random_pkg_name; my $use_statement = sprintf( 'use %s qw(:all);', $self->_module_name ); my ( $exports, $fatal_error ) = $self->_exports_for_include( $pkg, $use_statement ); if ($fatal_error) { return { fatal_error => $fatal_error }; } return $self->_list_to_hash( $pkg, $exports ); # If this module uses something other than Exporter or Sub::Exporter, we # probably returned an empty hash above. We could guess and say it's the # default exports + possibly something else. It's probably less confusing # to leave it up to the code which uses this object to decide how to handle # it. } sub _build_import_flags { my $self = shift; my %modules = ( Carp => ['verbose'], English => ['-no_match_vars'], ); return exists $modules{ $self->_module_name } ? $modules{ $self->_module_name } : []; } sub _build_is_exporter { my $self = shift; return 1 if any { $_ eq 'Exporter' } @{ $self->class_isa }; return $self->has_at_export || $self->has_at_export_ok ? 1 : 0; } sub _build_is_oo_class { my $self = shift; return 0 if $self->has_implicit_exports || $self->has_explicit_exports; my $methods = Class::Inspector->methods( $self->_module_name, 'full', 'public' ); return any { $_ eq 'Moose::Object::BUILDALL' || $_ eq 'Moo::Object::BUILDALL' } @{$methods}; } sub _build_isa_test_builder { my $self = shift; if ( any { $_ eq 'Test::Builder::Module' } @{ $self->_implicit->{class_isa} } ) { return 1; } return 0 if $self->_module_name !~ m{\ATest}; my $err = App::perlimports::Sandbox::eval_pkg( $self->_module_name, sprintf( 'use %s qw( some_function );', $self->_module_name ) ); # Catch cases like Test::HTML::Lint, where, which doesn't subclass # Test::Builder, but essentially calls Tester::Builder->new->plan(@_); in # its import(). The error will be something like "plan() doesn't understand # some_function at" if ( $err =~ m{plan} ) { return 1; } return 0; } sub _list_to_hash { my $self = shift; my $pkg = shift; my $list = shift; my %hash; for my $item ( @{$list} ) { my $value = $item; $value =~ s{^&}{}; $hash{$item} = $value; } # Specifically for File::chdir, which exports a typeglob, but doesn't # implement every possibility. for my $key ( keys %hash ) { if ( substr( $key, 0, 1 ) eq '*' ) { my $thing = substr( $key, 1 ); for my $sigil ( '&', '$', '@', '%' ) { my $symbol_name = $sigil . $pkg . '::' . $thing; if ( Symbol::Get::get($symbol_name) ) { $hash{ $sigil . $thing } = $key; } } } } # Treat Moose type libraries a bit differently. Importing ArrayRef, for # instance, also imports is_ArrayRef and to_ArrayRef (if a coercion) # exists. So, let's deal with that here. if ( $self->is_moose_type_class ) { for my $key ( keys %hash ) { if ( $key =~ m{^(is_|to_)} ) { $hash{$key} = substr( $key, 3 ); } } } return \%hash; } sub _build_implicit { my $self = shift; my $module_name = $self->_module_name; my $pkg = $self->_pkg_for_implicit; my $use_statement = "use $module_name;"; my ( $maybe_exports, $fatal_error ) = $self->_exports_for_include( $pkg, $use_statement ); no strict 'refs'; my $aggregated = { class_isa => [ @{ $self->_module_name . '::ISA' } ], export => [ @{ $self->_module_name . '::EXPORT' } ], export_fail => [ @{ $self->_module_name . '::EXPORT_FAIL' } ], export_ok => [ @{ $self->_module_name . '::EXPORT_OK' } ], export_tags => [ @{ $self->_module_name . '::EXPORT_TAGS' } ], fatal_error => $fatal_error, _maybe_exports => $maybe_exports, }; return $aggregated; } sub _exports_for_include { my $self = shift; my $pkg = shift; my $use_statement = shift; my $logger = $self->logger; # If you're importing Moose into a namespace and following that with an # import of namespace::autoclean, you may find that symbols like "after" # and "around" are no longer found. # # We log available symbols inside the BEGIN block in order to defeat # namespace::autoclean, which removes symbols from the stash after # compilation but before runtime. Thanks to Florian Ragwitz for the tip and # the preceding explanation. my $to_eval = <<"EOF"; package $pkg; use Symbol::Get; $use_statement our \@__EXPORTABLES; BEGIN { \@__EXPORTABLES = Symbol::Get::get_names(); } 1; EOF $self->logger->debug($to_eval); my $logger_cb = sub { my $msg = shift; my $level = 'info'; # Mojo classes tend to throw "Can't locate :all.pm in @INC". This is # expected and shouldn't be raised to the warning level. if ( $msg =~ qr{Can't locate} && $msg !~ m{\:all\.pm in \@INC} ) { $level = 'warning'; } $logger->log( level => $level, message => sprintf( "Problem trying to eval %s\n%s", $pkg, $msg, ), ); }; local $SIG{__WARN__} = $logger_cb; local $@ = undef; ## no critic (BuiltinFunctions::ProhibitStringyEval) ## no critic (ErrorHandling::RequireCheckingReturnValueOfEval) eval $to_eval; if ($@) { $logger_cb->($@); return undef, $@; } else { $self->_increment_success_counter; } ## no critic (TestingAndDebugging::ProhibitNoStrict) no strict 'refs'; my @export = grep { $_ !~ m{(?:BEGIN|ISA|__EXPORTABLES)} && $_ !~ m{^__ANON__} } @{ $pkg . '::__EXPORTABLES' }; use strict; ## use critic return \@export, undef; } sub _random_pkg_name { my $self = shift; return App::perlimports::Sandbox::pkg_for( $self->_module_name ); } sub _build_is_moose_class { my $self = shift; return any { $_ eq 'Moose::Object' || $_ eq 'Test::Class::Moose' } @{ $self->pkg_isa }; } sub _build_uses_moose { my $self = shift; # Make sure the module itself has been loaded before looking for a # metaclass. _implicit is cached and tolerates load failures. $self->_implicit; if ( $self->_maybe_require_module('Moose::Util') ) { return Moose::Util::find_meta( $self->_module_name ) ? 1 : 0; } return 0; } sub _build_is_moo_class { my $self = shift; if ( $self->_maybe_require_module('Class::Inspector') ) { return 1 if any { $_ eq 'Moo::is_class' } @{ Class::Inspector->methods( $self->_module_name, 'full', 'public' ) || [] }; } return 0; } sub _build_is_moose_type_class { my $self = shift; return any { $_ eq 'MooseX::Types::Base' || $_ eq 'MooseX::Types::Combine' } @{ $self->class_isa }; } sub explicit_export_names_match_values { my $self = shift; return join( q{}, sort $self->explicit_export_names ) eq join( q{}, sort $self->explicit_export_values ); } sub implicit_export_names_match_values { my $self = shift; return join( q{}, sort $self->implicit_export_names ) eq join( q{}, sort $self->implicit_export_values ); } sub _maybe_require_module { my $self = shift; my $module_to_require = shift; $self->logger->info("going to require $module_to_require"); my $success; try { require_module($module_to_require); $success = 1; } catch { $self->logger->info("$module_to_require error. $_"); }; return $success; } 1; # ABSTRACT: Inspect code for exportable symbols __END__ =pod =encoding UTF-8 =head1 NAME App::perlimports::ExportInspector - Inspect code for exportable symbols =head1 VERSION version 0.000067 =head1 SYNOPSIS use strict; use warnings; use App::perlimport::ExportInspector (); my $ei = App::perlimport::ExportInspector->new( module_name => 'Carp', ); my $exports = $ei->explicit_exports; =head1 DESCRIPTION Inspect modules to see what they might export. =head1 MOTIVATION Since we're (maybe) importing symbols as part of this process, we've sandboxed it a little bit by not doing it in L directly. =head1 METHODS The following methods are available. =head2 implicit_exports A HashRef with keys representing symbols which a module implicitly exports (i.e. via C. The values represent the import value which you would need in order to explicitly import the symbol. Often these will be the same, but there are exceptions. For example, a type library may export C, but you import it via C. =head2 explicit_exports A HashRef with keys representing symbols which a module explicitly exports (i.e. via C. The values represent the import value which you would need in order to explicitly import the symbol. Often these will be the same, but there are exceptions. For example, a type library may export C, but you import it via C. In cases where we cannot be certain about the explicit exports, you can try to fall back to the implicit exports to get an idea of what this module can export. =head2 evals_ok Returns true if either implicit or explicit exports can be built without setting C<$@>. =head2 implicit_export_names_match_values Returns true if the keys and values in C match. =head2 explicit_export_names_match_values Returns true if the keys and values in C match. =head2 success_counter Returns an integer representing the number of times we were able to execute eval statements for this package which did not pollute C<$@>. =head1 CAVEATS This may not work with modules using some creative way of managing symbol exports. =head1 AUTHOR Olaf Alders =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2020 by Olaf Alders. 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 ImportException.pm100644001750001751 50215261510600 23301 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/lib/Localpackage Local::ImportException; use strict; use warnings; require Exporter; our @ISA = qw( Exporter ); our @EXPORT_OK = qw( exceptional ); sub import { my $pkg = shift; my $first_arg = shift; if ( $first_arg && $first_arg eq 'exceptional' ) { die 'oof'; } } sub exceptional { } 1; RequireExporter.pm100644001750001751 21415261510600 23315 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/lib/Localpackage Local::RequireExporter; use strict; use warnings; require Exporter; our @EXPORT = qw(foo); sub foo { return 'from sub foo' } 1; MooseTypeLibrary.pm100644001750001751 50115261510600 23420 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/lib/Localpackage Local::MooseTypeLibrary; use strict; use warnings; use MooseX::Types::Moose; use MooseX::Types::Path::Class; use Path::Class (); use parent 'MooseX::Types::Combine'; __PACKAGE__->provide_types_from( 'MooseX::Types::Moose', 'MooseX::Types::Path::Class', ); 1; # Copied from Database::Migrator::Types lint-failure-unused-import.pl100644001750001751 5515261510600 23536 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data#!perl use strict; use warnings; use Carp; via-sub-exporter-exception.pl100644001750001751 7215261510600 23541 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data#!perl use 5.12.0; use Local::ViaSubExporter::Exception; UsesTypesStandard.pm100644001750001751 7415261510600 23561 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/lib/Localpackage Local::UsesTypesStandard; use Types::Standard; 1; missing-semicolon-in-import.pl100644001750001751 5715261510600 23707 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Carp use POSIX; sort-includes-noncontiguous.pl100644001750001751 13515261510600 24054 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use Foo; use Bar; my $x = 1; sub thing { require Zzz; return $x; } 1; UsesUsesImportInto.pm100644001750001751 12715261510600 23757 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/lib/Localpackage Local::UsesUsesImportInto; use strict; use warnings; use UsesImportInto; 1; moose-type-library-with-meta.pl100644001750001751 12515261510600 24010 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use Local::MooseTypeLibraryWithMeta; my $type = TheType; lint-failure-duplicate-import.pl100644001750001751 11415261510600 24221 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data#!perl use strict; use warnings; use Carp qw( croak ); use Carp; croak(); lint-failure-indented-duplicate.pl100644001750001751 13415261510600 24503 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data#!perl use strict; use warnings; { use Carp qw( croak ); use Carp; croak(); } indirect-object-syntax-preserved.pl100644001750001751 15215261510600 24736 0ustar00olafolaf000000000000App-perlimports-0.000067/test-datause strict; use warnings; use lib 'test-data/lib'; use Local::NoImport; my $obj = new Local::NoImport; ReExportViaSubExporter.pm100644001750001751 30515261510600 24564 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/lib/Localpackage Local::ReExportViaSubExporter; use strict; use warnings; use Carp; use Sub::Exporter -setup => { exports => [ 'croak', 'other_func', ] }; sub other_func { } 1; MooseTypeLibraryWithMeta.pm100644001750001751 72615261510600 25074 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/lib/Localpackage Local::MooseTypeLibraryWithMeta; use strict; use warnings; use Moose (); use MooseX::Types -declare => ['TheType']; use MooseX::Types::Moose qw( Str ); subtype TheType, as Str; # MooseX::Types 0.50 did "use Moose" in MooseX::Types and MooseX::Types::Base, # so type libraries ended up with a Moose metaclass. Initialize one explicitly # so that we can test this behaviour regardless of the installed version. Moose::Meta::Class->initialize(__PACKAGE__); 1; ViaSubExporter000755001750001751 015261510600 22417 5ustar00olafolaf000000000000App-perlimports-0.000067/test-data/lib/LocalException.pm100644001750001751 25515261510600 25035 0ustar00olafolaf000000000000App-perlimports-0.000067/test-data/lib/Local/ViaSubExporterpackage Local::ViaSubExporter::Exception; use strict; use warnings; use Sub::Exporter -setup => { exports => [ 'bar', 'foo', ] }; sub bar { } 1;