bleachbit-3.9.0/0000755000175000017500000000000013635746635012226 5ustar zz00000000000000bleachbit-3.9.0/CONTRIBUTING.md0000644000175000017500000000573513635746634014470 0ustar zz00000000000000# How to contribute to BleachBit Thank you for your interest in contributing. ## When to file a bug report Are you using the [latest version](https://www.bleachbit.org/download)? ## Where to file an issue Most bug reports should be filed in [GitHub under the BleachBit repository](https://github.com/bleachbit/bleachbit/issues/new). Bug reports were managed in [Launchpad](https://bugs.launchpad.net/bleachbit/) between about 2009 and 2016. Launchpad still contains some active issue tickets, but more recently users are encouraged to file issue tickets in GitHub. ## Information to include with bug reports When filing a bug report, please include: * The version of BleachBit * The type and version of the operating system (for example, Windows 10 or Ubuntu 16.04) * The exact error message * Which exact steps you took before the error happened If you are reporting an error that happens while cleaning ([example screenshot](https://user-images.githubusercontent.com/22394276/31048383-42d469d8-a61c-11e7-9a7d-d149887ce2f3.jpg)), please try to narrow it down a single cleaning option (in other words, a single checkbox). See also [prioritization of issues](https://www.bleachbit.org/contribute/prioritization-issues). ## Development environment BleachBit runs on Python 2.7 with PyGTK 2. See also [running from source](https://docs.bleachbit.org/dev/running-from-source-code.html) regarding dependencies. The modernization branch supports GTK+ 3, but it is not yet ready. See the GitHub issues. ## Procedure for creating and submitting patch Following this process will help your changes get merged sooner. If you plan to write a major change, please consider first opening a GitHub issue to discuss. * Log in to GitHub. * Fork the right BleachBit repository, as there are several repositories. * Check out your forked repository. * Make your changes. * Test your changes. Consider adding or expanding a unit test. * Run the unit tests by running ```` python tests/TestAll.py ```` * Make commits in small, logical units to make them easier to review. * Submit the pull request. * Check that it passes the tests by Travis CI and AppVeyor. If you have multiple commits around multiple themes (such as adding two, unrelated features), please consider breaking them up into multiple pull requests by using multiple branches. Smaller pull requests are easier to review and commit. Please consider reviewing someone else's pull requests and asking him or her to do the same for you. This can improve quality and get your changes merged sooner. ## Coding style * Indent with four spaces instead of tabs. * Format your code using PEP-8 standards like this: ````autopep8 -i bleachbit/Action.py```` * Follow other best practices such as they relate to readability, documentation, error handling, and performance. * See OpenStack [Git Commit Good Practice](https://wiki.openstack.org/wiki/GitCommitMessages) for advice on writing good Git commit messages. In particular, the first line of the commit message is important. bleachbit-3.9.0/COPYING0000644000175000017500000010451713635746634013270 0ustar zz00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . bleachbit-3.9.0/MANIFEST.in0000644000175000017500000000147013635746634013765 0ustar zz00000000000000include CONTRIBUTING.md include COPYING include MANIFEST include MANIFEST.in include Makefile include README.md include bleachbit.png include bleachbit.py include bleachbit.spec include cleaners/*xml include cleaners/Makefile include data/app-menu.ui include debian/bleachbit.dsc include debian/compat include debian/copyright include debian/debian.changelog include debian/debian.control include debian/debian.rules include doc/cleaner_markup_language.xsd include doc/example_cleaner.xml include org.bleachbit.BleachBit.desktop include org.bleachbit.BleachBit.metainfo.xml include org.bleachbit.policy include po/*po include po/Makefile include setup.py include tests/*py include windows/bleachbit.ico include windows/bleachbit.nsi include windows/gtk20.pot include windows/setup_py2exe.bat recursive-include bleachbit *py bleachbit-3.9.0/Makefile0000644000175000017500000000770313635746634013674 0ustar zz00000000000000# Copyright (C) 2008-2020 Andrew Ziem. All rights reserved. # License GPLv3+: GNU GPL version 3 or later . # This is free software: You are free to change and redistribute it. # There is NO WARRANTY, to the extent permitted by law. # # Makefile edited by https://github.com/Tobias-B-Besemer # Done on 2019-03-13 # On some systems if not explicitly given, make uses /bin/sh SHELL := /bin/bash .PHONY: clean install tests build prefix ?= /usr/local bindir ?= $(prefix)/bin datadir ?= $(prefix)/share INSTALL = install INSTALL_DATA = $(INSTALL) -m 644 # if not specified, do not check coverage PYTHON ?= python3 COVERAGE ?= $(PYTHON) build: echo Nothing to build clean: @rm -vf {.,bleachbit,tests,windows}/*{pyc,pyo,~} @rm -vrf build dist # created by py2exe @rm -rf BleachBit-Portable # created by windows/setup_py2exe.bat @rm -rf BleachBit-*-portable.zip @rm -vf MANIFEST # created by setup.py make -C po clean @rm -vrf locale @rm -vrf {*/,./}*.{pychecker,pylint,pyflakes}.log @rm -vrf windows/BleachBit-*-setup*.{exe,zip} @rm -vrf htmlcov .coverage # code coverage reports install: # "binary" mkdir -p $(DESTDIR)$(bindir) $(INSTALL_DATA) bleachbit.py $(DESTDIR)$(bindir)/bleachbit chmod 0755 $(DESTDIR)$(bindir)/bleachbit # application launcher mkdir -p $(DESTDIR)$(datadir)/applications $(INSTALL_DATA) org.bleachbit.BleachBit.desktop $(DESTDIR)$(datadir)/applications/ # AppStream metadata mkdir -p $(DESTDIR)$(datadir)/metainfo $(INSTALL_DATA) org.bleachbit.BleachBit.metainfo.xml $(DESTDIR)$(datadir)/metainfo/ # Python code mkdir -p $(DESTDIR)$(datadir)/bleachbit/markovify $(INSTALL_DATA) bleachbit/*.py $(DESTDIR)$(datadir)/bleachbit $(INSTALL_DATA) bleachbit/markovify/*.py $(DESTDIR)$(datadir)/bleachbit/markovify #note: compileall is recursive cd $(DESTDIR)$(datadir)/bleachbit && \ $(PYTHON) -O -c "import compileall; compileall.compile_dir('.')" && \ $(PYTHON) -c "import compileall; compileall.compile_dir('.')" # cleaners mkdir -p $(DESTDIR)$(datadir)/bleachbit/cleaners $(INSTALL_DATA) cleaners/*.xml $(DESTDIR)$(datadir)/bleachbit/cleaners # menu $(INSTALL_DATA) data/app-menu.ui $(DESTDIR)$(datadir)/bleachbit # icon mkdir -p $(DESTDIR)$(datadir)/pixmaps $(INSTALL_DATA) bleachbit.png $(DESTDIR)$(datadir)/pixmaps/ # translations make -C po install DESTDIR=$(DESTDIR) # PolicyKit mkdir -p $(DESTDIR)$(datadir)/polkit-1/actions $(INSTALL_DATA) org.bleachbit.policy $(DESTDIR)$(datadir)/polkit-1/actions/ lint: [ -x "$$(command -v pychecker)" ] || echo "WARNING: pychecker not found" [ -x "$$(command -v pyflakes)" ] || echo "WARNING: pyflakes not found" [ -x "$$(command -v pylint)" ] || echo "WARNING: pylint not found" for f in *py */*py; \ do \ echo "$$f"; \ ( [ -x "$$(command -v pychecker)" ] && pyflakes "$$f" > "$$f".pychecker.log ); \ ( [ -x "$$(command -v pyflakes)" ] && pyflakes "$$f" > "$$f".pyflakes.log ); \ ( [ -x "$$(command -v pylint)" ] && pylint "$$f" > "$$f".pylint.log ); \ done; \ exit 0 delete_windows_files: # This is used for building .deb and .rpm packages. # Remove Windows-specific cleaners. awk '/os=\"windows/ && /id=\"/ {print FILENAME}' cleaners/*.xml | xargs rm -f # Remove Windows-specific modules. rm -f bleachbit/Windows*.py downgrade_desktop: # This will downgrade the version of the .desktop file for older Linux distributions. # See https://github.com/bleachbit/bleachbit/issues/750 desktop-file-validate org.bleachbit.BleachBit.desktop || \ sed --regexp-extended -i '/^(Keywords|Version)=/d' org.bleachbit.BleachBit.desktop tests: make -C cleaners tests; cleaners_status=$$?; \ $(COVERAGE) -m unittest discover -p Test*.py -v; py_status=$$?; \ exit $$(($$cleaners_status + $$py_status)) pretty: autopep8 -i {.,bleachbit,tests}/*py dos2unix {.,bleachbit,tests}/*py make -C cleaners pretty xmllint --format doc/cleaner_markup_language.xsd > doc/cleaner_markup_language.xsd.tmp mv doc/cleaner_markup_language.xsd.tmp doc/cleaner_markup_language.xsd bleachbit-3.9.0/PKG-INFO0000644000175000017500000000105313635746635013322 0ustar zz00000000000000Metadata-Version: 1.1 Name: bleachbit Version: 3.9.0 Summary: BleachBit - Free space and maintain privacy Home-page: https://www.bleachbit.org Author: Andrew Ziem Author-email: andrew@bleachbit.org License: GPLv3 Download-URL: https://www.bleachbit.org/download Description: BleachBit frees space and maintains privacy by quickly wiping files you don't need and didn't know you had. Supported applications include Firefox, Flash, Internet Explorer, Java, Opera, Safari, GNOME, and many others. Platform: Linux and Windows; Python v2.6 and 2.7; GTK v3.12+ bleachbit-3.9.0/README.md0000644000175000017500000000305413635746634013506 0ustar zz00000000000000# BleachBit BleachBit cleans files to free disk space and to maintain privacy. ## Running from source To run BleachBit without installation, unpack the tarball and then run these commands: make -C po local # build translations python3 bleachbit.py Then, review the preferences. Then, select some options, and click Preview. Review the files, toggle options accordingly, and click Delete. For information regarding the command line interface, run: python3 bleachbit.py --help ## Links * [BleachBit home page](https://www.bleachbit.org) * [Support](https://www.bleachbit.org/help) * [Documentation](https://docs.bleachbit.org) ## Licenses BleachBit itself, including source code and cleaner definitions, is licensed under the [GNU General Public License version 3](COPYING), or at your option, any later version. markovify is licensed under the [MIT License](https://github.com/jsvine/markovify/blob/master/LICENSE.txt). ### Development * [BleachBit on AppVeyor](https://ci.appveyor.com/project/az0/bleachbit) [![Build status](https://ci.appveyor.com/api/projects/status/7p8amofd7rv7n268?svg=true)](https://ci.appveyor.com/project/az0/bleachbit) * [BleachBit on Travis CI](https://travis-ci.org/bleachbit/bleachbit) [![Build Status](https://travis-ci.org/bleachbit/bleachbit.svg?branch=master)](https://travis-ci.org/bleachbit/bleachbit) * [CleanerML Repository](https://github.com/az0/cleanerml) * [BleachBit Miscellaneous Repository](https://github.com/bleachbit/bleachbit-misc) * [Winapp2.ini Repository](https://github.com/bleachbit/winapp2.ini) bleachbit-3.9.0/bleachbit/0000755000175000017500000000000013635746635014143 5ustar zz00000000000000bleachbit-3.9.0/bleachbit/Action.py0000755000175000017500000005353013635746634015742 0ustar zz00000000000000# vim: ts=4:sw=4:expandtab # -*- coding: UTF-8 -*- # BleachBit # Copyright (C) 2008-2020 Andrew Ziem # https://www.bleachbit.org # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . """ Actions that perform cleaning """ from bleachbit import Command, FileUtilities, General, Special from bleachbit import _ import glob import logging import os import re if 'posix' == os.name: re_flags = 0 from bleachbit import Unix else: re_flags = re.IGNORECASE logger = logging.getLogger(__name__) def has_glob(s): """Checks whether the string contains any glob characters""" return re.search('[?*\[\]]', s) is not None def expand_multi_var(s, variables): """Expand strings with potentially-multiple values. The placeholder is written in the format $$foo$$. The function always returns a list of one or more strings. """ if not variables or s.find('$$') == -1: # The input string is missing $$ or no variables are given. return (s,) var_keys_used = [] ret = [] for var_key in variables.keys(): sub = '$$%s$$' % var_key if s.find(sub) > -1: var_keys_used.append(var_key) if not var_keys_used: # No matching variables used, so return input string unmodified. return (s,) # filter the dictionary to the keys used vars_used = {key: value for key, value in variables.items() if key in var_keys_used} # create a product of combinations from itertools import product vars_product = (dict(zip(vars_used, x)) for x in product(*vars_used.values())) for var_set in vars_product: ms = s # modified version of input string for var_key, var_value in var_set.items(): sub = '$$%s$$' % var_key ms = ms.replace(sub, var_value) ret.append(ms) if ret: return ret else: # The string has $$, but it did not match anything return (s,) # # Plugin framework # http://martyalchin.com/2008/jan/10/simple-plugin-framework/ # class PluginMount(type): """A simple plugin framework""" def __init__(cls, name, bases, attrs): if not hasattr(cls, 'plugins'): cls.plugins = [] else: cls.plugins.append(cls) class ActionProvider(metaclass=PluginMount): """Abstract base class for performing individual cleaning actions""" def __init__(self, action_node, path_vars=None): """Create ActionProvider from CleanerML """ pass def get_deep_scan(self): """Return a dictionary used to construct a deep scan""" raise StopIteration def get_commands(self): """Yield each command (which can be previewed or executed)""" pass # # base class # class FileActionProvider(ActionProvider): """Base class for providers which work on individual files""" action_key = '_file' CACHEABLE_SEARCHERS = ('walk.files',) # global cache cache = ('nothing', '', tuple()) def __init__(self, action_element, path_vars=None): """Initialize file search""" ActionProvider.__init__(self, action_element, path_vars) self.regex = action_element.getAttribute('regex') assert(isinstance(self.regex, (str, type(None)))) self.nregex = action_element.getAttribute('nregex') assert(isinstance(self.nregex, (str, type(None)))) self.wholeregex = action_element.getAttribute('wholeregex') assert(isinstance(self.wholeregex, (str, type(None)))) self.nwholeregex = action_element.getAttribute('nwholeregex') assert(isinstance(self.nwholeregex, (str, type(None)))) self.search = action_element.getAttribute('search') self.object_type = action_element.getAttribute('type') self._set_paths(action_element.getAttribute('path'), path_vars) self.ds = {} if 'deep' == self.search: self.ds['regex'] = self.regex self.ds['nregex'] = self.nregex self.ds['command'] = action_element.getAttribute('command') self.ds['path'] = self.paths[0] if not len(self.paths) == 1: logger.warning( # TRANSLATORS: Multi-value variables are explained in the online documentation. # Basically, they are like an environment variable, but each multi-value variable # can have multiple values. They're a way to make CleanerML files more concise. _("Deep scan does not support multi-value variable.")) if not any([self.object_type, self.regex, self.nregex, self.wholeregex, self.nwholeregex]): # If the filter is not needed, bypass it for speed. self.get_paths = self._get_paths def _set_paths(self, raw_path, path_vars): """Set the list of paths to work on""" self.paths = [] # expand special $$foo$$ which may give multiple values for path2 in expand_multi_var(raw_path, path_vars): path3 = os.path.expanduser(os.path.expandvars(path2)) if os.name == 'nt' and path3: # convert forward slash to backslash for compatibility with getsize() # and for display. Do not convert an empty path, or it will become # the current directory (.). path3 = os.path.normpath(path3) self.paths.append(path3) def get_deep_scan(self): if 0 == len(self.ds): return yield self.ds def get_paths(self): """Process the filters: regex, nregex, type If a filter is defined and it fails to match, this function returns False. Otherwise, this function returns True.""" # optimize tight loop, avoid slow python "." regex = self.regex nregex = self.nregex wholeregex = self.wholeregex nwholeregex = self.nwholeregex basename = os.path.basename object_type = self.object_type if self.regex: regex_c_search = re.compile(self.regex, re_flags).search else: regex_c_search = None if self.nregex: nregex_c_search = re.compile(self.nregex, re_flags).search else: nregex_c_search = None if self.wholeregex: wholeregex_c_search = re.compile(self.wholeregex, re_flags).search else: wholeregex_c_search = None if self.nwholeregex: nwholeregex_c_search = re.compile( self.nwholeregex, re_flags).search else: nwholeregex_c_search = None for path in self._get_paths(): if regex and not regex_c_search(basename(path)): continue if nregex and nregex_c_search(basename(path)): continue if wholeregex and not wholeregex_c_search(path): continue if nwholeregex and nwholeregex_c_search(path): continue if object_type: if 'f' == object_type and not os.path.isfile(path): continue elif 'd' == object_type and not os.path.isdir(path): continue yield path def _get_paths(self): """Return a filtered list of files""" def get_file(path): if os.path.lexists(path): yield path def get_walk_all(top): """Delete files and directories inside a directory but not the top directory""" for expanded in glob.iglob(top): path = None # sentinel value for path in FileUtilities.children_in_directory(expanded, True): yield path # This condition executes when there are zero iterations # in the loop above. if path is None: # This is a lint checker because this scenario may # indicate the cleaner developer made a mistake. if os.path.isfile(expanded): logger.debug( # TRANSLATORS: This is a lint-style warning that there seems to be a # mild mistake in the CleanerML file because walk.all is expected to # be used with directories instead of with files. _('search="walk.all" used with regular file path="%s"'), expanded, ) def get_walk_files(top): """Delete files inside a directory but not any directories""" for expanded in glob.iglob(top): for path in FileUtilities.children_in_directory(expanded, False): yield path def get_top(top): """Delete directory contents and the directory itself""" for f in get_walk_all(top): yield f if os.path.exists(top): yield top if 'deep' == self.search: return elif 'file' == self.search: func = get_file elif 'glob' == self.search: func = glob.iglob elif 'walk.all' == self.search: func = get_walk_all elif 'walk.files' == self.search: func = get_walk_files elif 'walk.top' == self.search: func = get_top else: raise RuntimeError("invalid search='%s'" % self.search) cache = self.__class__.cache for input_path in self.paths: if self.search == 'glob' and not has_glob(input_path): # TRANSLATORS: This is a lint-style warning that the CleanerML file # specified a search for glob, but the path specified didn't have any # wildcard patterns. Therefore, maybe the developer either missed # the wildcard or should search using path="file" which does not # expect or support wildcards in the path. logger.debug(_('path="%s" is not a glob pattern'), input_path) # use cache if self.search in self.CACHEABLE_SEARCHERS and cache[0] == self.search and cache[1] == input_path: #logger.debug(_('using cached walk for path %s'), input_path) for x in cache[2]: yield x return else: # if self.search in self.CACHEABLE_SEARCHERS: # logger.debug('not using cache because it has (%s,%s) and we want (%s,%s)', # cache[0], cache[1], self.search, input_path) self.__class__.cache = ('cleared by', input_path, tuple()) # build new cache #logger.debug('%s walking %s', id(self), input_path) if self.search in self.CACHEABLE_SEARCHERS: cache = self.__class__.cache = (self.search, input_path, []) for path in func(input_path): cache[2].append(path) yield path else: for path in func(input_path): yield path def get_commands(self): raise NotImplementedError('not implemented') # # Action providers # class AptAutoclean(ActionProvider): """Action to run 'apt-get autoclean'""" action_key = 'apt.autoclean' def __init__(self, action_element, path_vars=None): ActionProvider.__init__(self, action_element, path_vars) def get_commands(self): # Checking executable allows auto-hide to work for non-APT systems if FileUtilities.exe_exists('apt-get'): yield Command.Function(None, Unix.apt_autoclean, 'apt-get autoclean') class AptAutoremove(ActionProvider): """Action to run 'apt-get autoremove'""" action_key = 'apt.autoremove' def __init__(self, action_element, path_vars=None): ActionProvider.__init__(self, action_element, path_vars) def get_commands(self): # Checking executable allows auto-hide to work for non-APT systems if FileUtilities.exe_exists('apt-get'): yield Command.Function(None, Unix.apt_autoremove, 'apt-get autoremove') class AptClean(ActionProvider): """Action to run 'apt-get clean'""" action_key = 'apt.clean' def __init__(self, action_element, path_vars=None): ActionProvider.__init__(self, action_element, path_vars) def get_commands(self): # Checking executable allows auto-hide to work for non-APT systems if FileUtilities.exe_exists('apt-get'): yield Command.Function(None, Unix.apt_clean, 'apt-get clean') class ChromeAutofill(FileActionProvider): """Action to clean 'autofill' table in Google Chrome/Chromium""" action_key = 'chrome.autofill' def get_commands(self): for path in self.get_paths(): yield Command.Function( path, Special.delete_chrome_autofill, _('Clean file')) class ChromeDatabases(FileActionProvider): """Action to clean Databases.db in Google Chrome/Chromium""" action_key = 'chrome.databases_db' def get_commands(self): for path in self.get_paths(): yield Command.Function( path, Special.delete_chrome_databases_db, _('Clean file')) class ChromeFavicons(FileActionProvider): """Action to clean 'Favicons' file in Google Chrome/Chromium""" action_key = 'chrome.favicons' def get_commands(self): for path in self.get_paths(): yield Command.Function( path, Special.delete_chrome_favicons, _('Clean file')) class ChromeHistory(FileActionProvider): """Action to clean 'History' file in Google Chrome/Chromium""" action_key = 'chrome.history' def get_commands(self): for path in self.get_paths(): yield Command.Function( path, Special.delete_chrome_history, _('Clean file')) class ChromeKeywords(FileActionProvider): """Action to clean 'keywords' table in Google Chrome/Chromium""" action_key = 'chrome.keywords' def get_commands(self): for path in self.get_paths(): yield Command.Function( path, Special.delete_chrome_keywords, _('Clean file')) class Delete(FileActionProvider): """Action to delete files""" action_key = 'delete' def get_commands(self): for path in self.get_paths(): yield Command.Delete(path) class Ini(FileActionProvider): """Action to clean .ini configuration files""" action_key = 'ini' def __init__(self, action_element, path_vars=None): FileActionProvider.__init__(self, action_element, path_vars) self.section = action_element.getAttribute('section') self.parameter = action_element.getAttribute('parameter') if self.parameter == "": self.parameter = None def get_commands(self): for path in self.get_paths(): yield Command.Ini(path, self.section, self.parameter) class Journald(ActionProvider): """Action to run 'journalctl --vacuum-time=1'""" action_key = 'journald.clean' def __init__(self, action_element, path_vars=None): ActionProvider.__init__(self, action_element, path_vars) def get_commands(self): if FileUtilities.exe_exists('journalctl'): yield Command.Function(None, Unix.journald_clean, 'journalctl --vacuum-time=1') class Json(FileActionProvider): """Action to clean JSON configuration files""" action_key = 'json' def __init__(self, action_element, path_vars=None): FileActionProvider.__init__(self, action_element, path_vars) self.address = action_element.getAttribute('address') def get_commands(self): for path in self.get_paths(): yield Command.Json(path, self.address) class MozillaUrlHistory(FileActionProvider): """Action to clean Mozilla (Firefox) URL history in places.sqlite""" action_key = 'mozilla.url.history' def get_commands(self): for path in self.get_paths(): yield Command.Function(path, Special.delete_mozilla_url_history, _('Clean file')) class OfficeRegistryModifications(FileActionProvider): """Action to delete LibreOffice history""" action_key = 'office_registrymodifications' def get_commands(self): for path in self.get_paths(): yield Command.Function( path, Special.delete_office_registrymodifications, _('Clean')) class Process(ActionProvider): """Action to run a process""" action_key = 'process' def __init__(self, action_element, path_vars=None): ActionProvider.__init__(self, action_element, path_vars) self.cmd = os.path.expandvars(action_element.getAttribute('cmd')) # by default, wait self.wait = True wait = action_element.getAttribute('wait') if wait and wait.lower()[0] in ('f', 'n'): # false or no self.wait = False def get_commands(self): def run_process(): try: if self.wait: args = self.cmd.split(' ') (rc, stdout, stderr) = General.run_external(args) else: rc = 0 # unknown because we don't wait from subprocess import Popen Popen(self.cmd) except Exception as e: raise RuntimeError( 'Exception in external command\nCommand: %s\nError: %s' % (self.cmd, str(e))) else: if not 0 == rc: msg = 'Command: %s\nReturn code: %d\nStdout: %s\nStderr: %s\n' logger.warning(msg, self.cmd, rc, stdout, stderr) return 0 yield Command.Function(path=None, func=run_process, label=_("Run external command: %s") % self.cmd) class Shred(FileActionProvider): """Action to shred files (override preference)""" action_key = 'shred' def get_commands(self): for path in self.get_paths(): yield Command.Shred(path) class SqliteVacuum(FileActionProvider): """Action to vacuum SQLite databases""" action_key = 'sqlite.vacuum' def get_commands(self): for path in self.get_paths(): yield Command.Function( path, FileUtilities.vacuum_sqlite3, # TRANSLATORS: Vacuum is a verb. The term is jargon # from the SQLite database. Microsoft Access uses # the term 'Compact Database' (which you may translate # instead). Another synonym is 'defragment.' _('Vacuum')) class Truncate(FileActionProvider): """Action to truncate files""" action_key = 'truncate' def get_commands(self): for path in self.get_paths(): yield Command.Truncate(path) class WinShellChangeNotify(ActionProvider): """Action to clean the Windows Registry""" action_key = 'win.shell.change.notify' def get_commands(self): from bleachbit import Windows yield Command.Function( None, Windows.shell_change_notify, None) class Winreg(ActionProvider): """Action to clean the Windows Registry""" action_key = 'winreg' def __init__(self, action_element, path_vars=None): ActionProvider.__init__(self, action_element, path_vars) self.keyname = action_element.getAttribute('path') self.name = action_element.getAttribute('name') def get_commands(self): yield Command.Winreg(self.keyname, self.name) class YumCleanAll(ActionProvider): """Action to run 'yum clean all'""" action_key = 'yum.clean_all' def __init__(self, action_element, path_vars=None): ActionProvider.__init__(self, action_element, path_vars) def get_commands(self): # Checking allows auto-hide to work for non-APT systems if not FileUtilities.exe_exists('yum'): return yield Command.Function( None, Unix.yum_clean, 'yum clean all') class DnfCleanAll(ActionProvider): """Action to run 'dnf clean all'""" action_key = 'dnf.clean_all' def __init__(self, action_element, path_vars=None): ActionProvider.__init__(self, action_element, path_vars) def get_commands(self): # Checking allows auto-hide to work for non-APT systems if not FileUtilities.exe_exists('dnf'): return yield Command.Function( None, Unix.dnf_clean, 'dnf clean all') class DnfAutoremove(ActionProvider): """Action to run 'dnf autoremove'""" action_key = 'dnf.autoremove' def __init__(self, action_element, path_vars=None): ActionProvider.__init__(self, action_element, path_vars) def get_commands(self): # Checking allows auto-hide to work for non-APT systems if not FileUtilities.exe_exists('dnf'): return yield Command.Function( None, Unix.dnf_autoremove, 'dnf autoremove') bleachbit-3.9.0/bleachbit/CLI.py0000755000175000017500000002322513635746634015132 0ustar zz00000000000000#!/usr/bin/env python # vim: ts=4:sw=4:expandtab # BleachBit # Copyright (C) 2008-2020 Andrew Ziem # https://www.bleachbit.org # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . """ Command line interface """ from bleachbit.Cleaner import backends, create_simple_cleaner, register_cleaners from bleachbit import _, APP_VERSION from bleachbit import Diagnostic, Options, Worker import logging import optparse import os import sys logger = logging.getLogger(__name__) class CliCallback: """Command line's callback passed to Worker""" def append_text(self, msg, tag=None): """Write text to the terminal""" print(msg.strip('\n')) def update_progress_bar(self, status): """Not used""" pass def update_total_size(self, size): """Not used""" pass def update_item_size(self, op, opid, size): """Not used""" pass def worker_done(self, worker, really_delete): """Not used""" pass def cleaners_list(): """Yield each cleaner-option pair""" list(register_cleaners()) for key in sorted(backends): c_id = backends[key].get_id() for (o_id, o_name) in backends[key].get_options(): yield "%s.%s" % (c_id, o_id) def list_cleaners(): """Display available cleaners""" for cleaner in cleaners_list(): print (cleaner) def preview_or_clean(operations, really_clean): """Preview deletes and other changes""" cb = CliCallback() worker = Worker.Worker(cb, really_clean, operations).run() while next(worker): pass def args_to_operations(args, preset): """Read arguments and return list of operations""" list(register_cleaners()) operations = {} if preset: # restore presets from the GUI for key in sorted(backends): c_id = backends[key].get_id() for (o_id, o_name) in backends[key].get_options(): if Options.options.get_tree(c_id, o_id): args.append('.'.join([c_id, o_id])) for arg in args: if 2 != len(arg.split('.')): logger.warning(_("not a valid cleaner: %s"), arg) continue (cleaner_id, option_id) = arg.split('.') # enable all options (for example, firefox.*) if '*' == option_id: if cleaner_id in operations: del operations[cleaner_id] operations[cleaner_id] = [] for (option_id2, o_name) in backends[cleaner_id].get_options(): operations[cleaner_id].append(option_id2) continue # add the specified option if cleaner_id not in operations: operations[cleaner_id] = [] if option_id not in operations[cleaner_id]: operations[cleaner_id].append(option_id) for (k, v) in operations.items(): operations[k] = sorted(v) return operations def process_cmd_line(): """Parse the command line and execute given commands.""" # TRANSLATORS: This is the command line usage. Don't translate # %prog, but do translate options, cleaner, and option. # Don't translate and add "usage:" - it gets added by Python. # More information about the command line is here # https://www.bleachbit.org/documentation/command-line usage = _("usage: %prog [options] cleaner.option1 cleaner.option2") parser = optparse.OptionParser(usage) parser.add_option("-l", "--list-cleaners", action="store_true", help=_("list cleaners")) parser.add_option("-c", "--clean", action="store_true", # TRANSLATORS: predefined cleaners are for applications, such as Firefox and Flash. # This is different than cleaning an arbitrary file, such as a # spreadsheet on the desktop. help=_("run cleaners to delete files and make other permanent changes")) parser.add_option( '--debug', help=_("set log level to verbose"), action="store_true") parser.add_option('--debug-log', help=_("log debug messages to file")) parser.add_option("-s", "--shred", action="store_true", help=_("shred specific files or folders")) parser.add_option("--sysinfo", action="store_true", help=_("show system information")) parser.add_option("--gui", action="store_true", help=_("launch the graphical interface")) parser.add_option('--exit', action='store_true', help=optparse.SUPPRESS_HELP) if 'nt' == os.name: uac_help = _("do not prompt for administrator privileges") else: uac_help = optparse.SUPPRESS_HELP parser.add_option("--no-uac", action="store_true", help=uac_help) parser.add_option("-p", "--preview", action="store_true", help=_("preview files to be deleted and other changes")) parser.add_option('--pot', action='store_true', help=optparse.SUPPRESS_HELP) parser.add_option("--preset", action="store_true", help=_("use options set in the graphical interface")) if 'nt' == os.name: parser.add_option("--update-winapp2", action="store_true", help=_("update winapp2.ini, if a new version is available")) parser.add_option("-w", "--wipe-free-space", action="store_true", help=_("wipe free space in the given paths")) parser.add_option("-v", "--version", action="store_true", help=_("output version information and exit")) parser.add_option('-o', '--overwrite', action='store_true', help=_('overwrite files to hide contents')) (options, args) = parser.parse_args() cmd_list = (options.list_cleaners, options.wipe_free_space, options.preview, options.clean) cmd_count = sum(x is True for x in cmd_list) if cmd_count > 1: logger.error( _('Specify only one of these commands: --list-cleaners, --wipe-free-space, --preview, --clean')) sys.exit(1) did_something = False if options.debug: # set in __init__ so it takes effect earlier pass if options.debug_log: logger.addHandler(logging.FileHandler(options.debug_log)) logger.info(Diagnostic.diagnostic_info()) if options.version: print(""" BleachBit version %s Copyright (C) 2008-2020 Andrew Ziem. All rights reserved. License GPLv3+: GNU GPL version 3 or later . This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law.""" % APP_VERSION) sys.exit(0) if 'nt' == os.name and options.update_winapp2: from bleachbit import Update logger.info(_("Checking online for updates to winapp2.ini")) Update.check_updates(False, True, lambda x: sys.stdout.write("%s\n" % x), lambda: None) # updates can be combined with --list-cleaners, --preview, --clean did_something = True if options.list_cleaners: list_cleaners() sys.exit(0) if options.pot: from bleachbit.CleanerML import create_pot create_pot() sys.exit(0) if options.wipe_free_space: if len(args) < 1: logger.error(_("No directories given for --wipe-free-space")) sys.exit(1) for wipe_path in args: if not os.path.isdir(wipe_path): logger.error( _("Path to wipe must be an existing directory: %s"), wipe_path) sys.exit(1) logger.info(_("Wiping free space can take a long time.")) for wipe_path in args: logger.info('Wiping free space in path: %s', wipe_path) import bleachbit.FileUtilities for ret in bleachbit.FileUtilities.wipe_path(wipe_path): pass sys.exit(0) if options.preview or options.clean: operations = args_to_operations(args, options.preset) if not operations: logger.error(_("No work to do. Specify options.")) sys.exit(1) if options.preview: preview_or_clean(operations, False) sys.exit(0) if options.overwrite: if not options.clean or options.shred: logger.warning( _("--overwrite is intended only for use with --clean")) Options.options.set('shred', True, commit=False) if options.clean: preview_or_clean(operations, True) sys.exit(0) if options.gui: import bleachbit.GUI app = bleachbit.GUI.Bleachbit( uac=not options.no_uac, shred_paths=args, auto_exit=options.exit) sys.exit(app.run()) if options.shred: # delete arbitrary files without GUI # create a temporary cleaner object backends['_gui'] = create_simple_cleaner(args) operations = {'_gui': ['files']} preview_or_clean(operations, True) sys.exit(0) if options.sysinfo: print(Diagnostic.diagnostic_info()) sys.exit(0) if not did_something: parser.print_help() if __name__ == '__main__': process_cmd_line() bleachbit-3.9.0/bleachbit/Chaff.py0000644000175000017500000002731513635746634015533 0ustar zz00000000000000# vim: ts=4:sw=4:expandtab # -*- coding: UTF-8 -*- # BleachBit # Copyright (C) 2008-2020 Andrew Ziem # https://www.bleachbit.org # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import email.generator from email.mime.text import MIMEText import json import logging import os import random import tempfile from datetime import datetime from bleachbit import _, bleachbit_exe_path from bleachbit import options_dir from . import markovify logger = logging.getLogger(__name__) RECIPIENTS = ['0emillscd@state.gov', '1ilotylc@state.gov', 'abdinh@state.gov', 'abedin@state.gov', 'abedinh@state.gov', 'abendinh@state.gov', 'adedinh@state.gov', 'adlerce@state.gov', 'aliilscd@state.gov', 'baerdb@state.gov', 'baldersonkm@state.gov', 'balderstonkm@state.gov', 'bam@mikuiski.senate.gov', 'bam@mikulski.senate.gov', 'bealeca@state.gov', 'bedinh@state.gov', 'benjamin_moncrief@lemieux.senate.gov', 'blaker2@state.gov', 'brimmere@state.gov', 'brod17@clintonemail.com', 'burnswj@state.gov', 'butzgych2@state.gov', 'campbelikm@state.gov', 'carsonj@state.gov', 'cholletdh@state.gov', 'cindy.buhl@mail.house.gov', 'colemancl@state.gov', 'crowleypj@state.gov', 'danielil@state.gov', 'daniew@state.gov', 'david_garten@lautenberg.senate.gov', 'dewanll@state.gov', 'dilotylc@state.gov', 'eabedinh@state.gov', 'emillscd@state.gov', 'esullivanjj@state.gov', 'feltmanjd@state.gov', 'filotylc@state.gov', 'fuchsmh@state.gov', 'gll@state.gov', 'goldbergps@state.gov', 'goldenjr@state.gov', 'gonzalezjs@state.gov', 'gordonph@state.gov', 'h@state.gov', 'hanieymr@state.gov', 'hanleymr@state.gov', 'hanleyrnr@state.gov', 'harileymr@state.gov', 'hdr22@clintonemai1.com', 'hilicr@state.gov', 'hillcr@state.gov', 'holbrookerc@state.gov', 'hormatsrd@state.gov', 'hr15@att.blackberry.net', 'hr15@mycingular.blackberry.net', 'hrod17@clintonemail.com', 'huma@clintonemail.com', 'hyded@state.gov', 'ian1evqr@state.gov', 'ieltmanjd@state.gov', 'iewjj@state.gov', 'iilotylc@state.gov', 'imillscd@state.gov', 'info@mailva.evite.com', 'inh@state.gov', 'iviillscd@state.gov', 'jilotylc@state.gov', 'jj@state.gov', 'jonespw2@state.gov', 'kellyc@state.gov', 'klevorickcb@state.gov', 'kohhh@state.gov', 'kohliff@state.gov', 'laszczychj@state.gov', 'lc@state.gov', 'lewij@state.gov', 'lewjj@state.gov', 'lewn@state.gov', 'lilotylc@state.gov', 'macmanusje@state.gov', 'marshalicp@state.gov', 'marshallcp@state.gov', 'mchaleja@state.gov', 'mhcaleja@state.gov', 'millscd@state.aov', 'millscd@state.gov', 'millscd@tate.gov', 'mr@state.gov', 'muscantinel@state.gov', 'muscatinel@state.gov', 'nidestr@state.gov', 'njj@state.gov', 'nulandvi@state.gov', 'ogordonph@state.gov', 'oterom2@state.gov', 'posnermh@state.gov', 'postmaster@state.gov', 'r@state.gov', 'reines@state.gov', 'reinesp@state.gov', 'reinespi@state.gov', 'ricese@state.gov', 'rnillscd@state.gov', 'rodriguezme@state.gov', 'rooneym@state.gov', 's_specialassistants@state.gov', 'schwerindb@state.gov', 'shannonta@state.gov', 'shapiroa@state.gov', 'shermanwr@state.gov', 'slaughtera@state.gov', 'smithje@state.gov', 'steinbertjb@state.gov', 'sterntd@state.gov', 'stillivaral@state.gov', 'sullivanjj@state.gov', 'tanleyrnr@state.gov', 'tauschere0@state.gov', 'tauschereo@state.gov', 'tillemannts@state.gov', 'toivnf@state.gov', 'tommy_ross@reid.senate.gov', 'u@state.gov', 'ullivanjj@state.gov', 'vaimorou@state.gov', 'valenzuelaaa@state.gov', 'valmdrou@state.gov', 'valmmorolj@state.gov', 'valmorolj@state.gov', 'vermarr@state.gov', 'verveerms@state.gov', 'walmorou@state.gov', 'werveerms@state.gov', 'woodardew@state.gov', 'yeryeerms@state.gov'] DEFAULT_SUBJECT_LENGTH = 64 DEFAULT_NUMBER_OF_SENTENCES_CLINTON = 50 DEFAULT_NUMBER_OF_SENTENCES_2600 = 50 URL_CLINTON_SUBJECT = 'https://sourceforge.net/projects/bleachbit/files/chaff/clinton_subject_model.json.bz2/download' URL_CLINTON_CONTENT = 'https://sourceforge.net/projects/bleachbit/files/chaff/clinton_content_model.json.bz2/download' URL_2600 = 'https://sourceforge.net/projects/bleachbit/files/chaff/2600_model.json.bz2/download' DEFAULT_CONTENT_MODEL_PATH = os.path.join( options_dir, 'clinton_content_model.json.bz2') DEFAULT_SUBJECT_MODEL_PATH = os.path.join( options_dir, 'clinton_subject_model.json.bz2') DEFAULT_2600_MODEL_PATH = os.path.join( options_dir, '2600_model.json.bz2') def _load_model(model_path): _open = open if model_path.endswith('.bz2'): import bz2 _open = bz2.open with _open(model_path, 'rt', encoding='utf-8') as model_file: return markovify.Text.from_dict(json.load(model_file)) def load_subject_model(model_path): return _load_model(model_path) def load_content_model(model_path): return _load_model(model_path) def load_2600_model(model_path): return _load_model(model_path) def _get_random_recipient(): return random.choice(RECIPIENTS) def _get_random_datetime(min_year=2011, max_year=2012): date = datetime.strptime('{} {}'.format(random.randint( 1, 365), random.randint(min_year, max_year)), '%j %Y') # Saturday, September 15, 2012 2:20 PM return date.strftime('%A, %B %d, %Y %I:%M %p') def _get_random_content(content_model, number_of_sentences=DEFAULT_NUMBER_OF_SENTENCES_CLINTON): content = [] for _ in range(number_of_sentences): content.append(content_model.make_sentence()) content.append(random.choice([' ', ' ', '\n\n'])) try: return MIMEText(''.join(content)) except UnicodeEncodeError: return _get_random_content(content_model, number_of_sentences=number_of_sentences) def _generate_email(subject_model, content_model, number_of_sentences=DEFAULT_NUMBER_OF_SENTENCES_CLINTON, subject_length=DEFAULT_SUBJECT_LENGTH): message = _get_random_content( content_model, number_of_sentences=number_of_sentences) message['Subject'] = subject_model.make_short_sentence(subject_length) message['To'] = _get_random_recipient() message['From'] = _get_random_recipient() message['Sent'] = _get_random_datetime() return message def download_url_to_fn(url, fn, on_error=None, max_retries=2, backoff_factor=0.5): """Download a URL to the given filename""" logger.info('Downloading %s to %s', url, fn) import requests import sys if hasattr(sys, 'frozen'): # when frozen by py2exe, certificates are in alternate location CA_BUNDLE = os.path.join(bleachbit_exe_path, 'cacert.pem') requests.utils.DEFAULT_CA_BUNDLE_PATH = CA_BUNDLE requests.adapters.DEFAULT_CA_BUNDLE_PATH = CA_BUNDLE from urllib3.util.retry import Retry from requests.adapters import HTTPAdapter session = requests.Session() # 408: request timeout # 429: too many requests # 500: internal server error # 502: bad gateway # 503: service unavailable # 504: gateway_timeout status_forcelist = (408, 429, 500, 502, 503, 504) # sourceforge.net directories to download mirror retries = Retry(total=max_retries, backoff_factor=backoff_factor, status_forcelist=status_forcelist, redirect=5) session.mount('http://', HTTPAdapter(max_retries=retries)) msg = _('Downloading url failed: %s') % url from bleachbit.Update import user_agent headers = {'user_agent': user_agent()} def do_error(msg2): if on_error: on_error(msg, msg2) from bleachbit.FileUtilities import delete delete(fn, ignore_missing=True) # delete any partial download try: response = session.get(url, headers=headers) content = response.content except requests.exceptions.RequestException as exc: msg2 = '{}: {}'.format(type(exc).__name__, exc) logger.exception(msg) do_error(msg2) return False else: if not response.status_code == 200: logger.error(msg) msg2 = 'Status code: %s' % response.status_code do_error(msg2) return False with open(fn, 'wb') as f: f.write(content) return True def download_models(content_model_path=DEFAULT_CONTENT_MODEL_PATH, subject_model_path=DEFAULT_SUBJECT_MODEL_PATH, twentysixhundred_model_path=DEFAULT_2600_MODEL_PATH, on_error=None): """Download models Calls on_error(primary_message, secondary_message) in case of error Returns success as boolean value """ for (url, fn) in ((URL_CLINTON_SUBJECT, subject_model_path), (URL_CLINTON_CONTENT, content_model_path), (URL_2600, twentysixhundred_model_path)): if os.path.exists(fn): logger.debug('File %s already exists', fn) continue if not download_url_to_fn(url, fn): return False return True def generate_emails(number_of_emails, email_output_dir, content_model_path=DEFAULT_CONTENT_MODEL_PATH, subject_model_path=DEFAULT_SUBJECT_MODEL_PATH, number_of_sentences=DEFAULT_NUMBER_OF_SENTENCES_CLINTON, on_progress=None, *kwargs): logger.debug('Loading two email models') subject_model = load_subject_model(subject_model_path) content_model = load_content_model(content_model_path) logger.debug('Generating {:,} emails'.format(number_of_emails)) generated_file_names = [] for i in range(1, number_of_emails + 1): with tempfile.NamedTemporaryFile(mode='w+', prefix='outlook-', suffix='.eml', dir=email_output_dir, delete=False) as email_output_file: email_generator = email.generator.Generator(email_output_file) msg = _generate_email( subject_model, content_model, number_of_sentences=number_of_sentences) email_generator.write(msg.as_string()) generated_file_names.append(email_output_file.name) if on_progress: on_progress(1.0*i/number_of_emails) return generated_file_names def _generate_2600_file(model, number_of_sentences=DEFAULT_NUMBER_OF_SENTENCES_2600): content = [] for _ in range(number_of_sentences): content.append(model.make_sentence()) # The space is repeated to make paragraphs longer. content.append(random.choice([' ', ' ', '\n\n'])) return ''.join(content) def generate_2600(file_count, output_dir, model_path=DEFAULT_2600_MODEL_PATH, on_progress=None): logger.debug('Loading 2600 model') model = _load_model(model_path) logger.debug('Generating {:,} files'.format(file_count)) generated_file_names = [] for i in range(1, file_count + 1): with tempfile.NamedTemporaryFile(mode='w+', encoding='utf-8', prefix='2600-', suffix='.txt', dir=output_dir, delete=False) as output_file: txt = _generate_2600_file(model) output_file.write(txt) generated_file_names.append(output_file.name) if on_progress: on_progress(1.0*i/file_count) return generated_file_names def have_models(): """Check whether the models exist in the default location. Used to check whether download is needed.""" for fn in (DEFAULT_CONTENT_MODEL_PATH, DEFAULT_SUBJECT_MODEL_PATH, DEFAULT_2600_MODEL_PATH): if not os.path.exists(fn): return False return True bleachbit-3.9.0/bleachbit/Cleaner.py0000755000175000017500000007636413635746634016110 0ustar zz00000000000000# vim: ts=4:sw=4:expandtab # BleachBit # Copyright (C) 2008-2020 Andrew Ziem # https://www.bleachbit.org # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . """ Perform (or assist with) cleaning operations. """ import glob import logging import os.path import re import sys from bleachbit import _ from bleachbit.FileUtilities import children_in_directory from bleachbit.Options import options from bleachbit import Command, FileUtilities, Memory, Special # Suppress GTK warning messages while running in CLI #34 import warnings warnings.simplefilter("ignore", Warning) try: from bleachbit.GuiBasic import Gtk, Gdk HAVE_GTK = Gdk.get_default_root_window() is not None except (ImportError, RuntimeError, ValueError) as e: # ImportError happens when GTK is not installed. # RuntimeError can happen when X is not available (e.g., cron, ssh). # ValueError seen on BleachBit 3.0 with GTK 3 (GitHub issue 685) HAVE_GTK = False if 'posix' == os.name: from bleachbit import Unix elif 'nt' == os.name: from bleachbit import Windows # a module-level variable for holding cleaners backends = {} class Cleaner: """Base class for a cleaner""" def __init__(self): self.actions = [] self.id = None self.description = None self.name = None self.options = {} self.running = [] self.warnings = {} self.regexes_compiled = [] def add_action(self, option_id, action): """Register 'action' (instance of class Action) to be executed for ''option_id'. The actions must implement list_files and other_cleanup()""" self.actions += ((option_id, action), ) def add_option(self, option_id, name, description): """Register option (such as 'cache')""" self.options[option_id] = (name, description) def add_running(self, detection_type, pathname): """Add a way to detect this program is currently running""" self.running += ((detection_type, pathname), ) def auto_hide(self): """Return boolean whether it is OK to automatically hide this cleaner""" for (option_id, __name) in self.get_options(): try: for cmd in self.get_commands(option_id): for dummy in cmd.execute(False): return False for ds in self.get_deep_scan(option_id): if isinstance(ds, dict): return False except Exception: logger = logging.getLogger(__name__) logger.exception('exception in auto_hide(), cleaner=%s, option=%s', self.name, option_id) return True def get_commands(self, option_id): """Get list of Command instances for option 'option_id'""" for action in self.actions: if option_id == action[0]: for cmd in action[1].get_commands(): yield cmd if option_id not in self.options: raise RuntimeError("Unknown option '%s'" % option_id) def get_deep_scan(self, option_id): """Get dictionary used to build a deep scan""" for action in self.actions: if option_id == action[0]: try: for ds in action[1].get_deep_scan(): yield ds except StopIteration: return if option_id not in self.options: raise RuntimeError("Unknown option '%s'" % option_id) def get_description(self): """Brief description of the cleaner""" return self.description def get_id(self): """Return the unique name of this cleaner""" return self.id def get_name(self): """Return the human name of this cleaner""" return self.name def get_option_descriptions(self): """Yield the names and descriptions of each option in a 2-tuple""" if self.options: for key in sorted(self.options.keys()): yield (self.options[key][0], self.options[key][1]) def get_options(self): """Return user-configurable options in 2-tuple (id, name)""" if self.options: for key in sorted(self.options.keys()): yield (key, self.options[key][0]) def get_warning(self, option_id): """Return a warning as string.""" if option_id in self.warnings: return self.warnings[option_id] else: return None def is_running(self): """Return whether the program is currently running""" logger = logging.getLogger(__name__) for running in self.running: test = running[0] pathname = running[1] if 'exe' == test and 'posix' == os.name: if Unix.is_running(pathname): logger.debug("process '%s' is running", pathname) return True elif 'exe' == test and 'nt' == os.name: if Windows.is_process_running(pathname): logger.debug("process '%s' is running", pathname) return True elif 'pathname' == test: expanded = os.path.expanduser(os.path.expandvars(pathname)) for globbed in glob.iglob(expanded): if os.path.exists(globbed): logger.debug( "file '%s' exists indicating '%s' is running", globbed, self.name) return True else: raise RuntimeError( "Unknown running-detection test '%s'" % test) return False def is_usable(self): """Return whether the cleaner is usable (has actions)""" return len(self.actions) > 0 def set_warning(self, option_id, description): """Set a warning to be displayed when option is selected interactively""" self.warnings[option_id] = description class OpenOfficeOrg(Cleaner): """Delete OpenOffice.org cache""" def __init__(self): Cleaner.__init__(self) self.options = {} self.add_option('cache', _('Cache'), _('Delete the cache')) self.add_option('recent_documents', _('Most recently used'), _( "Delete the list of recently used documents")) self.id = 'openofficeorg' self.name = 'OpenOffice.org' self.description = _("Office suite") # reference: http://katana.oooninja.com/w/editions_of_openoffice.org if 'posix' == os.name: self.prefixes = ["~/.ooo-2.0", "~/.openoffice.org2", "~/.openoffice.org2.0", "~/.openoffice.org/3"] self.prefixes += ["~/.ooo-dev3"] if 'nt' == os.name: self.prefixes = [ "$APPDATA\\OpenOffice.org\\3", "$APPDATA\\OpenOffice.org2"] def get_commands(self, option_id): # paths for which to run expand_glob_join egj = [] if 'recent_documents' == option_id: egj.append( "user/registry/data/org/openoffice/Office/Histories.xcu") egj.append( "user/registry/cache/org.openoffice.Office.Histories.dat") if 'recent_documents' == option_id and not 'cache' == option_id: egj.append("user/registry/cache/org.openoffice.Office.Common.dat") for egj_ in egj: for prefix in self.prefixes: for path in FileUtilities.expand_glob_join(prefix, egj_): if 'nt' == os.name: path = os.path.normpath(path) if os.path.lexists(path): yield Command.Delete(path) if 'cache' == option_id: dirs = [] for prefix in self.prefixes: dirs += FileUtilities.expand_glob_join( prefix, "user/registry/cache/") for dirname in dirs: if 'nt' == os.name: dirname = os.path.normpath(dirname) for filename in children_in_directory(dirname, False): yield Command.Delete(filename) if 'recent_documents' == option_id: for prefix in self.prefixes: for path in FileUtilities.expand_glob_join(prefix, "user/registry/data/org/openoffice/Office/Common.xcu"): if os.path.lexists(path): yield Command.Function(path, Special.delete_ooo_history, _('Delete the usage history')) # ~/.openoffice.org/3/user/registrymodifications.xcu # Apache OpenOffice.org 3.4.1 from openoffice.org on Ubuntu 13.04 # %AppData%\OpenOffice.org\3\user\registrymodifications.xcu # Apache OpenOffice.org 3.4.1 from openoffice.org on Windows XP for path in FileUtilities.expand_glob_join(prefix, "user/registrymodifications.xcu"): if os.path.lexists(path): yield Command.Function(path, Special.delete_office_registrymodifications, _('Delete the usage history')) class System(Cleaner): """Clean the system in general""" def __init__(self): Cleaner.__init__(self) # # options for Linux and BSD # if 'posix' == os.name: # TRANSLATORS: desktop entries are .desktop files in Linux that # make up the application menu (the menu that shows BleachBit, # Firefox, and others. The .desktop files also associate file # types, so clicking on an .html file in Nautilus brings up # Firefox. # More information: # http://standards.freedesktop.org/menu-spec/latest/index.html#introduction self.add_option('desktop_entry', _('Broken desktop files'), _( 'Delete broken application menu entries and file associations')) self.add_option('cache', _('Cache'), _('Delete the cache')) # TRANSLATORS: Localizations are files supporting specific # languages, so applications appear in Spanish, etc. self.add_option('localizations', _('Localizations'), _( 'Delete files for unwanted languages')) self.set_warning( 'localizations', _("Configure this option in the preferences.")) # TRANSLATORS: 'Rotated logs' refers to old system log files. # Linux systems often have a scheduled job to rotate the logs # which means compress all except the newest log and then delete # the oldest log. You could translate this 'old logs.' self.add_option( 'rotated_logs', _('Rotated logs'), _('Delete old system logs')) self.add_option('recent_documents', _('Recent documents list'), _( 'Delete the list of recently used documents')) self.add_option('trash', _('Trash'), _('Empty the trash')) # # options just for Linux # if sys.platform.startswith('linux'): self.add_option('memory', _('Memory'), # TRANSLATORS: 'free' means 'unallocated' _('Wipe the swap and free memory')) self.set_warning( 'memory', _('This option is experimental and may cause system problems.')) # # options just for Microsoft Windows # if 'nt' == os.name: self.add_option('logs', _('Logs'), _('Delete the logs')) self.add_option( 'memory_dump', _('Memory dump'), _('Delete the file')) self.add_option('muicache', 'MUICache', _('Delete the cache')) # TRANSLATORS: Prefetch is Microsoft Windows jargon. self.add_option('prefetch', _('Prefetch'), _('Delete the cache')) self.add_option( 'recycle_bin', _('Recycle bin'), _('Empty the recycle bin')) # TRANSLATORS: 'Update' is a noun, and 'Update uninstallers' is an option to delete # the uninstallers for software updates. self.add_option('updates', _('Update uninstallers'), _( 'Delete uninstallers for Microsoft updates including hotfixes, service packs, and Internet Explorer updates')) # # options for GTK+ # if HAVE_GTK: self.add_option('clipboard', _('Clipboard'), _( 'The desktop environment\'s clipboard used for copy and paste operations')) # # options common to all platforms # # TRANSLATORS: "Custom" is an option allowing the user to specify which # files and folders will be erased. self.add_option('custom', _('Custom'), _( 'Delete user-specified files and folders')) # TRANSLATORS: 'free' means 'unallocated' self.add_option('free_disk_space', _('Free disk space'), # TRANSLATORS: 'free' means 'unallocated' _('Overwrite free disk space to hide deleted files')) self.set_warning('free_disk_space', _('This option is very slow.')) self.add_option( 'tmp', _('Temporary files'), _('Delete the temporary files')) self.description = _("The system in general") self.id = 'system' self.name = _("System") def get_commands(self, option_id): # cache if 'posix' == os.name and 'cache' == option_id: dirname = os.path.expanduser("~/.cache/") for filename in children_in_directory(dirname, True): if not self.whitelisted(filename): yield Command.Delete(filename) # custom if 'custom' == option_id: for (c_type, c_path) in options.get_custom_paths(): if 'file' == c_type: yield Command.Delete(c_path) elif 'folder' == c_type: for path in children_in_directory(c_path, True): yield Command.Delete(path) yield Command.Delete(c_path) else: raise RuntimeError( 'custom folder has invalid type %s' % c_type) # menu menu_dirs = ['~/.local/share/applications', '~/.config/autostart', '~/.gnome/apps/', '~/.gnome2/panel2.d/default/launchers', '~/.gnome2/vfolders/applications/', '~/.kde/share/apps/RecentDocuments/', '~/.kde/share/mimelnk', '~/.kde/share/mimelnk/application/ram.desktop', '~/.kde2/share/mimelnk/application/', '~/.kde2/share/applnk'] if 'posix' == os.name and 'desktop_entry' == option_id: for dirname in menu_dirs: for filename in [fn for fn in children_in_directory(dirname, False) if fn.endswith('.desktop')]: if Unix.is_broken_xdg_desktop(filename): yield Command.Delete(filename) # unwanted locales if 'posix' == os.name and 'localizations' == option_id: for path in Unix.locales.localization_paths(locales_to_keep=options.get_languages()): if os.path.isdir(path): for f in FileUtilities.children_in_directory(path, True): yield Command.Delete(f) yield Command.Delete(path) # Windows logs if 'nt' == os.name and 'logs' == option_id: paths = ( '$ALLUSERSPROFILE\\Application Data\\Microsoft\\Dr Watson\\*.log', '$ALLUSERSPROFILE\\Application Data\\Microsoft\\Dr Watson\\user.dmp', '$LocalAppData\\Microsoft\\Windows\\WER\\ReportArchive\\*\\*', '$LocalAppData\\Microsoft\\Windows\WER\\ReportQueue\\*\\*', '$programdata\\Microsoft\\Windows\\WER\\ReportArchive\\*\\*', '$programdata\\Microsoft\\Windows\\WER\\ReportQueue\\*\\*', '$localappdata\\Microsoft\\Internet Explorer\\brndlog.bak', '$localappdata\\Microsoft\\Internet Explorer\\brndlog.txt', '$windir\\*.log', '$windir\\imsins.BAK', '$windir\\OEWABLog.txt', '$windir\\SchedLgU.txt', '$windir\\ntbtlog.txt', '$windir\\setuplog.txt', '$windir\\REGLOCS.OLD', '$windir\\Debug\\*.log', '$windir\\Debug\\Setup\\UpdSh.log', '$windir\\Debug\\UserMode\\*.log', '$windir\\Debug\\UserMode\\ChkAcc.bak', '$windir\\Debug\\UserMode\\userenv.bak', '$windir\\Microsoft.NET\Framework\*\*.log', '$windir\\pchealth\\helpctr\\Logs\\hcupdate.log', '$windir\\security\\logs\\*.log', '$windir\\security\\logs\\*.old', '$windir\\SoftwareDistribution\\*.log', '$windir\\SoftwareDistribution\\DataStore\\Logs\\*', '$windir\\system32\\TZLog.log', '$windir\\system32\\config\\systemprofile\\Application Data\\Microsoft\\Internet Explorer\\brndlog.bak', '$windir\\system32\\config\\systemprofile\\Application Data\\Microsoft\\Internet Explorer\\brndlog.txt', '$windir\\system32\\LogFiles\\AIT\\AitEventLog.etl.???', '$windir\\system32\\LogFiles\\Firewall\\pfirewall.log*', '$windir\\system32\\LogFiles\\Scm\\SCM.EVM*', '$windir\\system32\\LogFiles\\WMI\\Terminal*.etl', '$windir\\system32\\LogFiles\\WMI\\RTBackup\EtwRT.*etl', '$windir\\system32\\wbem\\Logs\\*.lo_', '$windir\\system32\\wbem\\Logs\\*.log', ) for path in paths: expanded = os.path.expandvars(path) for globbed in glob.iglob(expanded): yield Command.Delete(globbed) # memory if sys.platform.startswith('linux') and 'memory' == option_id: yield Command.Function(None, Memory.wipe_memory, _('Memory')) # memory dump # how to manually create this file # http://www.pctools.com/guides/registry/detail/856/ if 'nt' == os.name and 'memory_dump' == option_id: fname = os.path.expandvars('$windir\\memory.dmp') if os.path.exists(fname): yield Command.Delete(fname) for fname in glob.iglob(os.path.expandvars('$windir\\Minidump\\*.dmp')): yield Command.Delete(fname) # most recently used documents list if 'posix' == os.name and 'recent_documents' == option_id: ru_fn = os.path.expanduser("~/.recently-used") if os.path.lexists(ru_fn): yield Command.Delete(ru_fn) # GNOME 2.26 (as seen on Ubuntu 9.04) will retain the list # in memory if it is simply deleted, so it must be shredded # (or at least truncated). # # GNOME 2.28.1 (Ubuntu 9.10) and 2.30 (10.04) do not re-read # the file after truncation, but do re-read it after # shredding. # # https://bugzilla.gnome.org/show_bug.cgi?id=591404 def gtk_purge_items(): """Purge GTK items""" Gtk.RecentManager().purge_items() yield 0 for pathname in ["~/.recently-used.xbel", "~/.local/share/recently-used.xbel"]: pathname = os.path.expanduser(pathname) if os.path.lexists(pathname): yield Command.Shred(pathname) if HAVE_GTK: # Use the Function to skip when in preview mode yield Command.Function(None, gtk_purge_items, _('Recent documents list')) if 'posix' == os.name and 'rotated_logs' == option_id: for path in Unix.rotated_logs(): yield Command.Delete(path) # temporary files if 'posix' == os.name and 'tmp' == option_id: dirnames = ['/tmp', '/var/tmp'] for dirname in dirnames: for path in children_in_directory(dirname, True): is_open = FileUtilities.openfiles.is_open(path) ok = not is_open and os.path.isfile(path) and \ not os.path.islink(path) and \ FileUtilities.ego_owner(path) and \ not self.whitelisted(path) if ok: yield Command.Delete(path) # temporary files if 'nt' == os.name and 'tmp' == option_id: dirname1 = os.path.expandvars( "$USERPROFILE\\Local Settings\\Temp\\") dirname2 = os.path.expandvars(r'%temp%') dirname3 = os.path.expandvars("%windir%\\temp\\") dirnames = [] if Windows.get_windows_version() >= 6.0: # Windows Vista or later dirnames.append(dirname2) else: # Windows XP dirnames.append(dirname1) dirnames.append(dirname3) # whitelist the folder %TEMP%\Low but not its contents # https://bugs.launchpad.net/bleachbit/+bug/1421726 for dirname in dirnames: low = os.path.join(dirname, 'low').lower() for filename in children_in_directory(dirname, True): if not low == filename.lower(): yield Command.Delete(filename) # trash if 'posix' == os.name and 'trash' == option_id: dirname = os.path.expanduser("~/.Trash") for filename in children_in_directory(dirname, False): yield Command.Delete(filename) # fixme http://www.ramendik.ru/docs/trashspec.html # http://standards.freedesktop.org/basedir-spec/basedir-spec-0.6.html # ~/.local/share/Trash # * GNOME 2.22, Fedora 9 # * KDE 4.1.3, Ubuntu 8.10 dirname = os.path.expanduser("~/.local/share/Trash/files") for filename in children_in_directory(dirname, True): yield Command.Delete(filename) dirname = os.path.expanduser("~/.local/share/Trash/info") for filename in children_in_directory(dirname, True): yield Command.Delete(filename) dirname = os.path.expanduser("~/.local/share/Trash/expunged") # desrt@irc.gimpnet.org tells me that the trash # backend puts files in here temporary, but in some situations # the files are stuck. for filename in children_in_directory(dirname, True): yield Command.Delete(filename) # clipboard if HAVE_GTK and 'clipboard' == option_id: def clear_clipboard(): clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD) clipboard.set_text(' ',1) clipboard.clear() return 0 yield Command.Function(None, clear_clipboard, _('Clipboard')) # overwrite free space shred_drives = options.get_list('shred_drives') if 'free_disk_space' == option_id and shred_drives: for pathname in shred_drives: # TRANSLATORS: 'Free' means 'unallocated.' # %s expands to a path such as C:\ or /tmp/ display = _("Overwrite free disk space %s") % pathname def wipe_path_func(): for ret in FileUtilities.wipe_path(pathname, idle=True): # Yield control to GTK idle because this process # is very slow. Also display progress. yield ret yield 0 yield Command.Function(None, wipe_path_func, display) # MUICache if 'nt' == os.name and 'muicache' == option_id: keys = ( 'HKCU\\Software\\Microsoft\\Windows\\ShellNoRoam\\MUICache', 'HKCU\\Software\\Classes\\Local Settings\\Software\\Microsoft\\Windows\\Shell\\MuiCache') for key in keys: yield Command.Winreg(key, None) # prefetch if 'nt' == os.name and 'prefetch' == option_id: for path in glob.iglob(os.path.expandvars('$windir\\Prefetch\\*.pf')): yield Command.Delete(path) # recycle bin if 'nt' == os.name and 'recycle_bin' == option_id: # This method allows shredding recycled_any = False for path in Windows.get_recycle_bin(): recycled_any = True yield Command.Delete(path) # If there were any files deleted, Windows XP will show the # wrong icon for the recycle bin indicating it is not empty. # The icon will be incorrect until logging in to Windows again # or until it is emptied using the Windows API call for emptying # the recycle bin. # Windows 10 refreshes the recycle bin icon when the user # opens the recycle bin folder. # This is a hack to refresh the icon. def empty_recycle_bin_func(): import tempfile tmpdir = tempfile.mkdtemp() Windows.move_to_recycle_bin(tmpdir) try: Windows.empty_recycle_bin(None, True) except: logging.getLogger(__name__).info( 'error in empty_recycle_bin()', exc_info=True) yield 0 # Using the Function Command prevents emptying the recycle bin # when in preview mode. if recycled_any: yield Command.Function(None, empty_recycle_bin_func, _('Empty the recycle bin')) # Windows Updates if 'nt' == os.name and 'updates' == option_id: for wu in Windows.delete_updates(): yield wu def init_whitelist(self): """Initialize the whitelist only once for performance""" regexes = [ '^/tmp/.X0-lock$', '^/tmp/.truecrypt_aux_mnt.*/(control|volume)$', '^/tmp/.vbox-[^/]+-ipc/lock$', '^/tmp/.wine-[0-9]+/server-.*/lock$', '^/tmp/gconfd-[^/]+/lock/ior$', '^/tmp/fsa/', # fsarchiver '^/tmp/kde-', '^/tmp/kdesudo-', '^/tmp/ksocket-', '^/tmp/orbit-[^/]+/bonobo-activation-register[a-z0-9-]*.lock$', '^/tmp/orbit-[^/]+/bonobo-activation-server-[a-z0-9-]*ior$', '^/tmp/pulse-[^/]+/pid$', '^/var/tmp/kdecache-', '^' + os.path.expanduser('~/.cache/wallpaper/'), # Flatpak mount point '^' + os.path.expanduser('~/.cache/doc($|/)'), # Clean Firefox cache from Firefox cleaner (LP#1295826) '^' + os.path.expanduser('~/.cache/mozilla/'), # Clean Google Chrome cache from Google Chrome cleaner (LP#656104) '^' + os.path.expanduser('~/.cache/google-chrome/'), '^' + os.path.expanduser('~/.cache/gnome-control-center/'), # Clean Evolution cache from Evolution cleaner (GitHub #249) '^' + os.path.expanduser('~/.cache/evolution/'), # iBus Pinyin # https://bugs.launchpad.net/bleachbit/+bug/1538919 '^' + os.path.expanduser('~/.cache/ibus/'), # Linux Bluetooth daemon obexd directory is typically empty, so be careful # not to delete the empty directory. '^' + os.path.expanduser('~/.cache/obexd($|/)')] for regex in regexes: self.regexes_compiled.append(re.compile(regex)) def whitelisted(self, pathname): """Return boolean whether file is whitelisted""" if os.name == 'nt': # Whitelist is specific to POSIX return False if not self.regexes_compiled: self.init_whitelist() for regex in self.regexes_compiled: if regex.match(pathname) is not None: return True return False def register_cleaners(cb_progress=lambda x: None, cb_done=lambda: None): """Register all known cleaners: system, CleanerML, and Winapp2""" global backends # wipe out any registrations # Because this is a global variable, cannot use backends = {} backends.clear() # initialize "hard coded" (non-CleanerML) backends backends["openofficeorg"] = OpenOfficeOrg() backends["system"] = System() # register CleanerML cleaners from bleachbit import CleanerML cb_progress(_('Loading native cleaners.')) for ret in CleanerML.load_cleaners(cb_progress): yield ret # register Winapp2.ini cleaners if 'nt' == os.name: cb_progress(_('Importing cleaners from Winapp2.ini.')) from bleachbit import Winapp for ret in Winapp.load_cleaners(cb_progress): yield ret cb_done() yield False # end the iteration def create_simple_cleaner(paths): """Shred arbitrary files (used in CLI and GUI)""" cleaner = Cleaner() cleaner.add_option(option_id='files', name='', description='') cleaner.name = _("System") # shows up in progress bar from bleachbit import Action class CustomFileAction(Action.ActionProvider): action_key = '__customfileaction' def get_commands(self): for path in paths: if not isinstance(path, (str)): raise RuntimeError( 'expected path as string but got %s' % str(path)) if not os.path.isabs(path): path = os.path.abspath(path) if os.path.isdir(path): for child in children_in_directory(path, True): yield Command.Shred(child) yield Command.Shred(path) else: yield Command.Shred(path) provider = CustomFileAction(None) cleaner.add_action('files', provider) return cleaner def create_wipe_cleaner(path): """Wipe free disk space of arbitrary paths (used in GUI)""" cleaner = Cleaner() cleaner.add_option( option_id='free_disk_space', name='', description='') cleaner.name = '' # create a temporary cleaner object display = _("Overwrite free disk space %s") % path def wipe_path_func(): for ret in FileUtilities.wipe_path(path, idle=True): yield ret yield 0 from bleachbit import Action class CustomWipeAction(Action.ActionProvider): action_key = '__customwipeaction' def get_commands(self): yield Command.Function(None, wipe_path_func, display) provider = CustomWipeAction(None) cleaner.add_action('free_disk_space', provider) return cleaner bleachbit-3.9.0/bleachbit/CleanerML.py0000755000175000017500000003117713635746634016332 0ustar zz00000000000000# vim: ts=4:sw=4:expandtab # BleachBit # Copyright (C) 2008-2020 Andrew Ziem # https://www.bleachbit.org # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . """ Create cleaners from CleanerML (markup language) """ import bleachbit from bleachbit.Action import ActionProvider from bleachbit import _ from bleachbit.General import boolstr_to_bool, getText from bleachbit.FileUtilities import expand_glob_join, listdir from bleachbit import Cleaner import logging import os import sys import xml.dom.minidom logger = logging.getLogger(__name__) def default_vars(): """Return default multi-value variables""" ret = {} if not os.name == 'nt': return ret # Expand ProgramFiles to also be ProgramW6432, etc. wowvars = (('ProgramFiles', 'ProgramW6432'), ('CommonProgramFiles', 'CommonProgramW6432')) for v1, v2 in wowvars: # Remove None, if variable is not found. # Make list unique. mylist = list(set([x for x in (os.getenv(v1), os.getenv(v2)) if x])) ret[v1] = mylist return ret class CleanerML: """Create a cleaner from CleanerML""" def __init__(self, pathname, xlate_cb=None): """Create cleaner from XML in pathname. If xlate_cb is set, use it as a callback for each translate-able string. """ self.action = None self.cleaner = Cleaner.Cleaner() self.option_id = None self.option_name = None self.option_description = None self.option_warning = None self.vars = default_vars() self.xlate_cb = xlate_cb if self.xlate_cb is None: self.xlate_mode = False self.xlate_cb = lambda x, y=None: None # do nothing else: self.xlate_mode = True dom = xml.dom.minidom.parse(pathname) self.handle_cleaner(dom.getElementsByTagName('cleaner')[0]) def get_cleaner(self): """Return the created cleaner""" return self.cleaner def os_match(self, os_str, platform=sys.platform): """Return boolean whether operating system matches Keyword arguments: os_str -- the required operating system as written in XML platform -- used only for unit tests """ # If blank or if in .pot-creation-mode, return true. if len(os_str) == 0 or self.xlate_mode: return True # Otherwise, check platform. # Define the current operating system. if platform == 'darwin': current_os = ('darwin', 'bsd', 'unix') elif platform.startswith('linux'): current_os = ('linux', 'unix') elif platform.startswith('openbsd'): current_os = ('bsd', 'openbsd', 'unix') elif platform.startswith('netbsd'): current_os = ('bsd', 'netbsd', 'unix') elif platform.startswith('freebsd'): current_os = ('bsd', 'freebsd', 'unix') elif platform == 'win32': current_os = ('windows') else: raise RuntimeError('Unknown operating system: %s ' % sys.platform) # Compare current OS against required OS. return os_str in current_os def handle_cleaner(self, cleaner): """ element""" if not self.os_match(cleaner.getAttribute('os')): return self.cleaner.id = cleaner.getAttribute('id') self.handle_cleaner_label(cleaner.getElementsByTagName('label')[0]) description = cleaner.getElementsByTagName('description') if description and description[0].parentNode == cleaner: self.handle_cleaner_description(description[0]) for var in cleaner.getElementsByTagName('var'): self.handle_cleaner_var(var) for option in cleaner.getElementsByTagName('option'): try: self.handle_cleaner_option(option) except: exc_msg = _( "Error in handle_cleaner_option() for cleaner id = {cleaner_id}, option XML={option_xml}") logger.exception(exc_msg.format( cleaner_id=exc_dict, option_xml=option.toxml())) self.handle_cleaner_running(cleaner.getElementsByTagName('running')) self.handle_localizations( cleaner.getElementsByTagName('localizations')) def handle_cleaner_label(self, label): """