pax_global_header00006660000000000000000000000064126733462110014517gustar00rootroot0000000000000052 comment=91b794b8b0bf48b5d5bb44e053ff7e68aac27de9 mussort-0.4/000077500000000000000000000000001267334621100130765ustar00rootroot00000000000000mussort-0.4/.gitignore000066400000000000000000000000311267334621100150600ustar00rootroot00000000000000*~ *.swp *.bz2 mussort.1 mussort-0.4/COPYING000066400000000000000000001043741267334621100141420ustar00rootroot00000000000000 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 . mussort-0.4/Makefile000066400000000000000000000027601267334621100145430ustar00rootroot00000000000000# mussort makefile VERSION=$(shell ./mussort --version|perl -pi -e 's/^\D+//; chomp') ifndef prefix # This little trick ensures that make install will succeed both for a local # user and for root. It will also succeed for distro installs as long as # prefix is set by the builder. prefix=$(shell perl -e 'if($$< == 0 or $$> == 0) { print "/usr" } else { print "$$ENV{HOME}/.local"}') endif BINDIR ?= $(prefix)/bin DATADIR ?= $(prefix)/share DISTFILES = COPYING Makefile mussort NEWS TODO mussort.1 # Install mussort install: mkdir -p "$(BINDIR)" cp mussort "$(BINDIR)" chmod 755 "$(BINDIR)/mussort" [ -e mussort.1 ] && mkdir -p "$(DATADIR)/man/man1" && cp mussort.1 "$(DATADIR)/man/man1" || true localinstall: mkdir -p "$(BINDIR)" ln -sf $(shell pwd)/mussort $(BINDIR)/ [ -e mussort.1 ] && mkdir -p "$(DATADIR)/man/man1" && ln -sf $(shell pwd)/mussort.1 "$(DATADIR)/man/man1" || true # Unisntall an installed mussort uninstall: rm -f "$(BINDIR)/mussort" rm -f "$(DATADIR)/man/man1/mussort.1" # Clean up the tree clean: rm -f `find|egrep '~$$'` rm -f mussort-$(VERSION).tar.bz2 rm -rf mussort-$(VERSION) rm -f mussort.1 # Verify syntax test: @perl -c mussort # Create a manpage from the POD man: pod2man --name "mussort" --center "" --release "mussort $(VERSION)" ./mussort ./mussort.1 # Create the tarball distrib: clean test man mkdir -p mussort-$(VERSION) cp $(DISTFILES) ./mussort-$(VERSION) tar -jcvf mussort-$(VERSION).tar.bz2 ./mussort-$(VERSION) rm -rf mussort-$(VERSION) rm -f mussort.1 mussort-0.4/NEWS000066400000000000000000000036271267334621100136050ustar00rootroot00000000000000Version 0.4 - Now ignores .git (improves speed when running in trees managed by git-annex) - Now consistently (case insensitively) sorts filenames internally before sorting them, fixing issues with certain files that "always" got renamed - Improved track-number fallback detection - Various improvements when operating on a symlink-heavy collection (ie. a collection managed by git-annex) - Fixed problems with very long names - Added a dry run mode (by Achim Schaefer) - Will now attempt to move folder/cover images as well Version 0.3 - Caching is now enabled by default, can be disabled with --no-cache - Added support for multi-disc albums - Added --refresh-cache (write-only cache mode) - Added --consistent which makes mussort generate consistent directory names - Minor improvements to --insensitive - Fixed an issue with parts of the cache being invalidated when sorting changed - Improved support for id3v1 tags - Added cleaning of empty entries in the cache, allows --cleancache to be used to force all skipped files to be re-evaluated - Improved fallbacks when a tag reading method fails - No longer perfers to use Audio::File for OGG Vorbis files - Added support for using Ogg::Vorbis::Header (and ::PurePerl) (which is now the preferred way to read ogg tags) - --keepdupes is now default instead of --largest - Added --fileinfo - Added FLAC support Version 0.2 - Better dependency checking - Better case-insensitive sorting - Some cleanup - Support for Audio::File which significantly speeds up ogg vorbis sorting - Added --compilation - a mode where mussort will attempt to detect compilation albums and sort those properly as well - Now sets the terminal title - Better support for later versions of id3 information utils - Added --verbose and --quiet - Added --cache - significantly speeds up subsequent runs on large collections - Major optimizations - Added --keepdupes Version 0.1 - Initial public release mussort-0.4/TODO000066400000000000000000000000001267334621100135540ustar00rootroot00000000000000mussort-0.4/mussort000077500000000000000000001774471267334621100145640ustar00rootroot00000000000000#!/usr/bin/perl # vim: set noexpandtab : # # mussort - a simple program for sorting music collections # Copyright (C) Eskild Hustvedt 2007, 2008, 2009, 2010, 2011 # # 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 . use strict; use warnings; use utf8; use File::Find; use File::Basename qw(dirname basename); use File::Path qw(rmtree); use File::Copy; use Getopt::Long; use IPC::Open2; use Cwd qw(realpath); use Storable; use constant { true => 1, false => 0, # Verbosity levels M_STANDARD => 1, M_VERBOSE => 2, M_VERYVERBOSE => 3, M_DEBUG => 4, # Directory types, used for getDirectoriesIn() DIR_TYPE_PRIMARY => 1, DIR_TYPE_SECONDARY => 2, # Duplicate actions DUPE_REPLACE => 1, DUPE_NOREMOVE => 2, DUPE_KEEP => 3, }; our $VERSION = '0.4'; # Hash of which information sources we have my %Has = ( 'Audio::File' => false, 'Ogg::Vorbis::Header::PurePerl' => false, 'Ogg::Vorbis::Header' => false, 'id3v2' => false, 'id3info' => false, 'ogginfo' => false, 'metaflac' => false, ); # Dir hash, used for the final directory cleanup my %cleanTree; # Dir preferance hash, used for case-insensitive searches my %DirPreferance; # The file information cache (as used by --cache) my %cachedInfo; # The directory information cache my @dirInfoCache; # The number of entries added to the cache since it was last saved. # Used to write the cache file during runtime my $cacheAdditions = 0; # -- The following are altered through command-line parameters -- # Int, the action to perform when detecting duplicates my $dupeAction = DUPE_KEEP; # Bool, true if we should prefer Audio::File over the other programs my $PreferAudioFile = false; # Verbosity level (0-4) my $verbosity = 1; # Bool, true if we should allow special characters in file names my $AllowSpecialChars = false; # Bool, true if we should work in case-insensitive mode my $DirInsensitive = false; # Bool, true if we should work in case-insensitive consistent mode my $DirConsistent = false; # Bool, true if we should silently skip files (not outputting information about it) my $SilentSkip = false; # Bool, true if we should my $CompilationDetection; # Bool, true or a string if caching is enabled (string would be path to the cache file) my $cacheFile = true; # Bool, true if we should *read* from the cache (as opposed to only writing updated # info to it) my $readFromCache = true; # Bool, true if we should add all directories to the clean process my $addAllCleanTree = false; # Bool, true if we just output what will be done, don't actually do anything my $DryRunMove; # This makes sure the children are slayed properly $SIG{CHLD} = sub { my $PID = wait; return(1) }; # -- # File information # -- # Purpose: Get information about an ogg vorbis file using ogginfo # Usage: my %Info = GetOggVorbisInfo(FILE); sub GetOggVorbisInfo { my $InfoFile = shift; $InfoFile = realpath($InfoFile); my %Information = (); local *STDERR; open(STDERR,'>','/dev/null'); my $PID = open2(my $Child_OUT, my $Child_IN, 'ogginfo', $InfoFile) or FatalError("Unable to open2(): $!\n"); my $hadInfo = false; while(<$Child_OUT>) { next if not m/=/; chomp; s/^\s+//g; my $Opt = $_; my $Val = $_; $Opt =~ s/^\s*(.*)\s*=.*/$1/; $Opt =~ tr[a-z][A-Z]; $Val =~ s/^.*=\s*(.*)\s*/$1/; if($Val =~ /\S/) { if(not $Opt eq 'TRACKNUMBER') { $hadInfo = true; } $Information{$Opt} = $Val; } } close($Child_OUT); close($Child_IN); $Information{TRACKNUMBER} =~ s#/.*##; if ($hadInfo) { my %FileInfo; $FileInfo{Title} = getTag(\%Information,'title'); $FileInfo{Band} = getTag(\%Information,'artist'); $FileInfo{Album} = getTag(\%Information,'album'); $FileInfo{Track} = getTag(\%Information,'track'); $FileInfo{SetNo} = getTag(\%Information,'setNo'); $FileInfo{Ext} = 'ogg'; return %FileInfo; } return; } # Purpose: Get information about an mp3 file # Usage: my %Info = GetMP3Info(FILE); sub GetMP3Info { my $InfoFile = shift; my $type = shift; my $Information; my $hadInfo = false; if ($type eq 'id3v2') { ($hadInfo,$Information) = GetMP3Info_id3v2($InfoFile); } elsif($type eq 'id3info') { ($hadInfo,$Information) = GetMP3Info_id3info($InfoFile); } else { die("GetMP3Info: unknown type: $type\n"); } if ($hadInfo) { my %FileInfo; $FileInfo{Title} = getTag($Information,'title'); $FileInfo{Band} = getTag($Information,'artist'); $FileInfo{Album} = getTag($Information,'album'); $FileInfo{Track} = getTag($Information,'track'); $FileInfo{SetNo} = getTag($Information,'setNo'); $FileInfo{Ext} = 'mp3'; return(%FileInfo); } return; } # Purpose: Get information about a flac file # Usage: my %Info = GetFLACInfo(FILE); sub GetFLACInfo { my $InfoFile = shift; $InfoFile = realpath($InfoFile); my %Information = (); local *STDERR; open(STDERR,'>','/dev/null'); my $PID = open2(my $Child_OUT, my $Child_IN, 'metaflac','--list', $InfoFile) or FatalError("Unable to open2(): $!\n"); my $hadInfo = false; while(<$Child_OUT>) { next if not s/^\s*comment\[[^\]]+\]:\s*//; chomp; s/^\s+//g; my $Opt = $_; my $Val = $_; $Opt =~ s/^\s*(.*)\s*=.*/$1/; $Opt =~ tr[a-z][A-Z]; $Val =~ s/^.*=\s*(.*)\s*/$1/; if($Val =~ /\S/) { if(not $Opt eq 'TRACKNUMBER') { $hadInfo = true; } $Information{$Opt} = $Val; } } close($Child_OUT); close($Child_IN); $Information{TRACKNUMBER} =~ s#/.*##; if ($hadInfo) { my %FileInfo; $FileInfo{Title} = getTag(\%Information,'title'); $FileInfo{Band} = getTag(\%Information,'artist'); $FileInfo{Album} = getTag(\%Information,'album'); $FileInfo{Track} = getTag(\%Information,'track'); $FileInfo{SetNo} = getTag(\%Information,'setNo'); $FileInfo{Ext} = 'flac'; return %FileInfo; } return; } # Purpose: Get information about an mp3 file using id3v2 # Usage: my ($hasInfo, $info) = GetMP3Info_id3v2(FILE); sub GetMP3Info_id3v2 { my $InfoFile = shift; my %Information = (); my %AlternateInfo = (); my $o = $ENV{LC_ALL}; $ENV{LC_ALL} = 'C'; my $PID = open2(my $Child_OUT, my $Child_IN, 'id3v2', '--list', $InfoFile) or FatalError("Unable to open2(): $!"); $ENV{LC_ALL} = $o; my $hadInfo = false; while(<$Child_OUT>) { if (/^(Title|Album|Comment)\s*:/) { chomp; my ($first,$second,$clean); if (/^Title/) { $first = 'Title'; $second = 'Artist'; } elsif(/^Album/) { $first = 'Album'; $second = 'Year'; $clean = ',\s*Genre\s*:.*'; } elsif(/^Comment/) { $first = 'Comment'; $second = 'Track'; } my $f = $_; my $s = $_; if(not $f =~ s/^$first\s*:\s*//) { next; } $f =~ s/\s*$second:.*//g; if(not $s =~ s/^$first.*$second\s*:\s*//) { next; } $s =~ s/,\s*Genre\s*:.*//g; if ($f or $s and not $first eq 'Comment') { $hadInfo = true; } $Information{$first} = $f; $Information{$second} = $s; } else { next if not /\):/; chomp; my $Opt = $_; my $Val = $_; $Opt =~ s/^(\w+)\s.*/$1/g; $Val =~ s/^.+\):\s(.+)$/$1/g; if($Val =~ /\S/) { if(not $Opt eq 'TRCK') { $hadInfo = true; } $Information{$Opt} = $Val; } } } close($Child_OUT); close($Child_IN); return($hadInfo,\%Information); } # Purpose: Get information about an mp3 file using id3info # Usage: my ($hasInfo, $info) = GetMP3Info_id3info(FILE); sub GetMP3Info_id3info { my $InfoFile = shift; my %Information = (); my $PID = open2(my $Child_OUT, my $Child_IN, 'id3info', $InfoFile) or FatalError("Unable to open2(): $!"); my $hadInfo = false; while(<$Child_OUT>) { next if not /^==/; chomp; my $Opt = $_; my $Val = $_; $Opt =~ s/^===\s(\w+)\s.*/$1/g; $Val =~ s/^.+\):\s(.+)$/$1/g; if($Val =~ /\S/) { if(not $Opt =~ /^TRC?K$/) { $hadInfo = true; } $Information{$Opt} = $Val; } } close($Child_OUT); close($Child_IN); return($hadInfo,\%Information); } # Purpose: Get information about an Ogg Vorbis file using # Ogg::Vorbis::Header::PurePerl # Usage: my %Info = GetInfoFromVorbisHeader(FILE); sub GetInfoFromVorbisHeader { my $File = shift; my $modType = shift; my %FileInfo; my %Information; my $hadInfo = false; eval { local *STDERR; # Ogg::Vorbis::Header(::PurePerl) outputs junk to STDERR we don't want, # so temporarily redirect it to the black hole open(STDERR,'>','/dev/null'); my $modName = 'Ogg::Vorbis::Header'; my $ov; if ($modType eq 'PurePerl') { $modName .= '::PurePerl'; if(Ogg::Vorbis::Header::PurePerl->can('load')) { $ov = Ogg::Vorbis::Header::PurePerl->load($File); } else { $ov = Ogg::Vorbis::Header::PurePerl->new($File); } } else { $ov = Ogg::Vorbis::Header->load($File); } foreach my $t (qw(title artist album tracknumber discnumber)) { $Information{$t} = $ov->comment($t); if(defined $Information{$t} and length $Information{$t} and $Information{$t} ne '1') { $hadInfo = true; } } 1; } or do { my $err = $@; if ($Has{'ogginfo'} || $Has{'Audio::File'}) { printv(M_DEBUG,"Ogg::Vorbis::Header::PurePerl crashed on $File: $err\n"); return; } else { die('Ogg::Vorbis::Header::PurePerl appears to have crashed for the file "'.$File.'". Please install either ogginfo from vorbis-tools or Audio::File. Error: '.$err); } }; if ($hadInfo) { my %FileInfo; $FileInfo{Title} = getTag(\%Information,'title'); $FileInfo{Band} = getTag(\%Information,'artist'); $FileInfo{Album} = getTag(\%Information,'album'); $FileInfo{Track} = getTag(\%Information,'track'); $FileInfo{SetNo} = getTag(\%Information,'setNo'); $FileInfo{Ext} = 'ogg'; return %FileInfo; } return; } # Purpose: Get information about an audio file using Audio::File # Usage: my %Info = GetInfoFromAudioFile(FILE); sub GetInfoFromAudioFile { my $File = shift; my %FileInfo; if ($File =~ /mp3$/i) { $FileInfo{Ext} = 'mp3'; } elsif($File =~ /ogg$/i) { $FileInfo{Ext} = 'ogg'; } elsif($File =~ /flac$/i) { $FileInfo{Ext} = 'flac'; } else { FatalError("Unknown filetype: $File\n"); } eval { local *STDERR; # Audio::File outputs junk to STDERR we don't want, so temporarily redirect it # to the black hole open(STDERR,'>','/dev/null'); my $af = Audio::File->new($File); eval { $FileInfo{Title} = CleanTag($af->tag->title) }; eval { $FileInfo{Band} = CleanTag($af->tag->artist) }; eval { $FileInfo{Album} = CleanTag($af->tag->album) }; eval { $FileInfo{Track} = CleanTag($af->tag->track) }; 1; } or do { my $err = $@; printv(M_DEBUG,"Audio::File crashed on $File: $err\n"); if ( $FileInfo{Ext} eq 'mp3' and ($Has{'id3info'} or $Has{'id3v2'}) ) { return; } elsif($FileInfo{Ext} eq 'ogg' and ($Has{'ogginfo'} or $Has{'Ogg::Vorbis::Header::PurePerl'})) { return; } else { die('Audio::File appears to have crashed for the file "'.$File.'". See the DEPENDENCIES section of the mussort manpage for a list of other libraries and utilities you can install to avoid this problem. Error: '.$err); } return; }; return %FileInfo; } # Purpose: Check that the tag supplied is valid # Usage: bool = IsValidTagValue(VALUE); # This is simply a reversed version of IsInvalidTagValue() sub IsValidTagValue { return ! IsInvalidTagValue(@_); } # Purpose: Check that the tag supplied is valid # Usage: bool = IsInvalidTagValue(VALUE); # Returns false if it is valid, true if it isn't. sub IsInvalidTagValue { my $value = shift; if(not defined $value or not length $value or $value eq 'Unknown' or $value eq '~') { return true; } return false; } # Purpose: Get information about a file # Usage: $FileInfo = GetInfo(pathtofile); sub GetInfo { my $File = shift; my $usedCached = false; my %FileInfo; my $AudioFilePreferred = $PreferAudioFile; my $used; my $optimalQuality = 5; my $quality = $optimalQuality; # We only use Audio::File for OGGs. id3info appears to be faster # for MP3s if(my $info = getInfoFromCache($File)) { printv(M_DEBUG,'Using cached information for '.$File."\n"); %FileInfo = %{$info}; if(%FileInfo) { $usedCached = true; $used = 'cache'; } else { printv(M_DEBUG,'Cached null information, ignoring'); } } if (not $usedCached) { printv(M_VERYVERBOSE,'Reading information about file: '.$File."\n"); my @try; if ($File =~ /ogg$/i) { if ($Has{'Ogg::Vorbis::Header'}) { push(@try,'Ogg::Vorbis::Header'); } if ($Has{'Ogg::Vorbis::Header::PurePerl'}) { push(@try,'Ogg::Vorbis::Header::PurePerl'); } if ($Has{'ogginfo'}) { push(@try,'ogg'); } } elsif($File =~ /mp3$/i) { if ($Has{'id3v2'}) { push(@try,'id3v2'); } if ($Has{'id3info'}) { push(@try,'id3info'); } } elsif($File =~ /flac$/) { push(@try,'metaflac'); # Audio::File is faster than metaflac, so use it if possible $AudioFilePreferred = 1; } else { FatalError("Unknown filetype: $File\n"); } if ($Has{'Audio::File'}) { if ($AudioFilePreferred) { unshift(@try,'Audio::File'); } else { push(@try,'Audio::File'); } } foreach my $t (@try) { printv(M_DEBUG,'Trying method: '.$t."\n"); $used = $t; $quality = $optimalQuality; if ($t eq 'Audio::File') { %FileInfo = GetInfoFromAudioFile($File); } elsif($t eq 'Ogg::Vorbis::Header') { %FileInfo = GetInfoFromVorbisHeader($File); } elsif($t eq 'Ogg::Vorbis::Header::PurePerl') { %FileInfo = GetInfoFromVorbisHeader($File,'PurePerl'); } elsif($t eq 'id3v2') { %FileInfo = GetMP3Info($File,'id3v2'); } elsif($t eq 'id3info') { %FileInfo = GetMP3Info($File,'id3info'); } elsif($t eq 'mp3') { %FileInfo = GetMP3Info($File); } elsif($t eq 'ogg') { %FileInfo = GetOggVorbisInfo($File); } elsif($t eq 'metaflac') { %FileInfo = GetFLACInfo($File); } my $discard; if (!%FileInfo) { $discard ||= 'No information returned'; $quality = 0; } if(keys %FileInfo < 2) { $discard ||= 'Not enough information returned'; $quality = -1; } if(!IsValidTagValue($FileInfo{Title}) || $FileInfo{Title} !~ /[\w\d]/) { $discard ||= 'Title tag invalid'; $quality--; } if(!IsValidTagValue($FileInfo{Band}) || $FileInfo{Band} !~ /[\w\d]/) { $discard ||= 'Band tag invalid'; $quality--; } if( (defined($FileInfo{Title}) && $FileInfo{Title} eq '1' ) || (defined($FileInfo{Band}) && $FileInfo{Band} eq '1')) { $discard ||= 'Title or Band set to "1" (Ogg::Vorbis::Header workaround)'; $quality--; } if ($quality == $optimalQuality) { printv(M_DEBUG,'Quality of values from '.$t.' was excellent ('.$quality.'/'.$optimalQuality.') - using them'."\n"); last; } elsif($quality < 1) { printv(M_DEBUG,'Quality of values from '.$t.' was rubbish ('.$quality.'/'.$optimalQuality.'): '.$discard.". Will attempt another method if possible.\n"); } else { printv(M_DEBUG,'Quality of values from '.$t.' was poor ('.$quality.'/'.$optimalQuality.'): '.$discard.". Will attempt another method if possible.\n"); } } } printv(M_DEBUG,'Using values from '.$used."\n"); if ($quality == $optimalQuality && $used ne 'cache') { addToCache($File,\%FileInfo); } if ($CompilationDetection and defined $FileInfo{Album} and defined $FileInfo{Band}) { if(not defined $CompilationDetection->{album}->{$FileInfo{Album}}->{$FileInfo{Band}}) { $CompilationDetection->{album}->{$FileInfo{Album}}->{$FileInfo{Band}} = []; } push(@{$CompilationDetection->{album}->{$FileInfo{Album}}->{$FileInfo{Band}}},$File); } # If we couldn't extract a track then try to extract it from the filename instead if(not defined $FileInfo{Track} or not $FileInfo{Track} =~ /^\d+$/ or $FileInfo{Track} eq '0' ) { my $Track = basename($File); if ($Track =~ s/^(\d+)\D+.*$/$1/) { $FileInfo{Track} = $Track; } } return(\%FileInfo); } # Purpose: Fetch tag values from extracted data # Usage: value = getTag(infoHashRef, tagName); sub getTag { my $info = shift; my $tag = shift; my %possibleTags = ( title => [ 'TIT2','TT2','TITLE','Title','title'], artist => [ 'TPE1','TP1','ARTIST','Artist','artist' ], album => [ 'TALB','TAL','ALBUM','Album', 'album' ], track => [ 'TRCK','TRK','TRACKNUMBER', 'TRACK','Track', 'tracknumber' ], setNo => [ 'TPA','DISCNUMBER', 'discnumber','TPOS' ], ); if(not defined $possibleTags{$tag}) { warn("Tried to fetch tag '$tag', but it wasn't found in possibleTags"); return; } my $content = 'Unknown'; foreach my $possible (@{$possibleTags{$tag}}) { if(IsValidTagValue($info->{$possible})) { $content = $info->{$possible}; if ($tag ne 'setNo' && $tag ne 'track') { $content = CleanTag($content); next if not IsValidTagValue($content); } last; } } if ($tag eq 'track') { $content =~ s{/.*$}{}g; } elsif($tag eq 'setNo') { my $valid = false; if ($content =~ m{^\d+/\d+$}) { my $no = $content; my $total = $content; $no =~ s{/\d+$}{}; $total =~ s{^\d+/}{}; if ($no > 1 || $total > 1) { $valid = true; $content = { total => $total, number => $no }; } } if(not $valid) { $content = {}; } } return $content; } # Purpose: Strip stuff we don't want in file/dir names # Usage: my $NewVar = CleanTag(OldVar); sub CleanTag { my $Name = shift; # Make & into and $Name =~ s/\&/and/; # Don't allow whitespace $Name =~ s/\s+/_/g; # Remove these characters - if present $Name =~ s/~//g; $Name =~ s/('|"|\(|\))+//g; $Name =~ s#/##g; $Name =~ s/\?//g; $Name =~ s/#//g; $Name =~ s/\\//g; # Ensure we don't have two identical _ or - following each other. That's ugly. $Name =~ s/_+/_/g; $Name =~ s/-+/-/g; # Don't begin a file with . $Name =~ s/^\.+//; # Don't end or begin a file with _ or - $Name =~ s/(_|-)+$//; $Name =~ s/^(_|-)+//; # If we have more than 3 . after each other, force only three $Name =~ s/\.\.\.\.+/.../g; # Clean up non-ascii characters if(not $AllowSpecialChars) { # These usually doesn't work, but having them here doesn't hurt $Name =~ s/æ/ae/gi; $Name =~ s/ø/oe/gi; $Name =~ s/å/aa/gi; # Now remove everything that doesn't match this regex $Name =~ s/[^\w\s\.,-_]//g; } # Don't let it start with a dot $Name =~ s/^\.+//; # Don't allow _-_ - just use one - $Name =~ s/_-_/-/; # Finally, return the cleaned filename return($Name); } # -- # Main application # -- # Purpose: use() a module if it's installed # Returns true if the use was successful, false otherwise sub tryuse { my $mod = shift; if(eval('use '.$mod.';1;')) { return true; } return; } # Purpose: Set the title of the xterm/screen # Usage: setTermTitle(TITLE); sub setTermTitle { return if not $verbosity > 0; return if not defined $ENV{TERM}; my $title = shift; if ($ENV{TERM} =~ /screen/) { print "\033k$title\033\\"; } else { print "\033]0;$title\007"; } } # Purpose: Returns the mtime of a file # Usage: $mtime = mtime(file); # Note: It returns zero (not undef) if it can't read the mtime sub mtime { my $file = shift; my $mtime; (undef,undef,undef,undef,undef,undef,undef,undef,undef,$mtime,undef,undef,undef) = stat($file); if(not defined $mtime) { printv(M_DEBUG,'Failed to read mtime from file '.$file."\n"); return 0; } return $mtime; } # Purpose: Internal mkpath() that also modifies the directory cache # Usage: intMkpath(/path/to/create); sub intMkpath { my $fullpath = shift; if (-d $fullpath) { return; } my @pathsToCreate; $fullpath=~ s{/+$}{}; while(not -d $fullpath) { unshift(@pathsToCreate,$fullpath); $fullpath = dirname($fullpath); } foreach my $dir (@pathsToCreate) { mkdir($dir) or die('Failed to mkdir('.$dir.'): '.$!); my $parent = dirname($dir); foreach my $type (DIR_TYPE_PRIMARY,DIR_TYPE_SECONDARY) { if(defined $dirInfoCache[$type]->{$parent}) { push(@{$dirInfoCache[$type]->{$parent}},basename($dir)); @{$dirInfoCache[$type]->{$parent}} = sort(@{$dirInfoCache[$type]->{$parent}}); } } } } # Purpose: Check for a dependency # Usage: depError(COMMAND); sub depError { my $format = shift; my $install = shift; my $recommended = shift; my $debPackages = { id3info => 'libid3-dev', id3v2 => 'id3v2', ogginfo => 'vorbis-tools', 'Audio::File' => 'libaudio-file-perl', 'Ogg::Vorbis::Header::PurePerl' => 'libogg-vorbis-header-pureperl-perl', 'Ogg::Vorbis::Header' => 'libogg-vorbis-header-perl', }; # Multi-dimensional hash mapping distro -> command -> package my %DepToPackage = ( '/etc/apt/apt.conf.d/01ubuntu' => $debPackages, '/etc/debian_version' => $debPackages, '/etc/mandriva-release' => { ogginfo => 'vorbis-tools', id3info => 'id3lib', id3v2 => 'id3v2', }, '/etc/fedora-release' => { ogginfo => 'vorbis-tools', id3info => 'id3lib', id3v2 => 'id3v2', }, ); my $out = ''; my $depsMap = {}; foreach my $path (keys(%DepToPackage)) { if (-e $path) { $depsMap = $DepToPackage{$path}; } } $out .= "You are missing a component for $format support.\n"; $out .= "Please install either of the following:\n"; foreach my $e (@{$install}) { my $oe = $e; if ($e eq $recommended) { $oe = '[RECOMMENDED] '.$oe; } if ($depsMap->{$e}) { $out .= "$oe (from the $depsMap->{$e} package)\n"; } else { if ($e =~ /::/) { $oe .= '(perl module)'; } $out .= "$oe\n"; } } FatalError($out); } # Purpose: Output an error message # Usage: Error(MESSAGE); sub Error { warn "Error: $_[0]\n"; } # Purpose: Output a fatal error message (causes die()) # Usage: FatalError(MESSAGE); sub FatalError { die "Error: $_[0]\n"; } # Purpose: Check if a directory is empty # Usage: DirIsEmpty(PATH); # Returns 1 if it is empty, 0 if it isn't. sub DirIsEmpty { my $dir = shift; return 0 if not $dir; opendir(TESTDIR, $dir); my @TestDir = readdir(TESTDIR); closedir(TESTDIR); if(not scalar @TestDir > 2) { return 1; } return 0; } # Purpose: Get information from cache if caching is enabled # Usage: %info = getInfoFromCache(FILE); sub getInfoFromCache { my $file = shift; if(not $readFromCache) { return; } if(defined $cacheFile) { if(defined($cachedInfo{mtime}->{$file})) { if (mtime($file) <= $cachedInfo{mtime}->{$file}) { return $cachedInfo{info}->{$file}; } } } return; } # Purpose: Add information to the cache if caching is enabled # Usage: addToCache($file,\%info); sub addToCache { my $file = shift; my $info = shift; if( defined $cachedInfo{mtime} && defined $cachedInfo{mtime}->{$file} && defined $cachedInfo{info} && defined $cachedInfo{info}->{$file} && (keys %{$cachedInfo{info}->{$file}} > 1) ) { if ($cachedInfo{mtime}->{$file} >= mtime($file)) { return; } else { printv(M_DEBUG,'Re-evaluating cached information for '.$file."\n"); } } if(not (keys %{$info} > 1)) { printv(M_DEBUG,'Refusing to add cached data for '.$file.': too little information'."\n"); return; } if(not defined $cachedInfo{info}) { $cachedInfo{info} = {}; } if(not defined $cachedInfo{mtime}) { $cachedInfo{mtime} = {}; } my $fileinfo = mtime($file); if(not $fileinfo) { printv(M_VERYVERBOSE,'Failed to stat() '.$fileinfo.' - skipping adding it to the cache'."\n"); delete($cachedInfo{info}->{$file}); } else { $cachedInfo{info}->{$file} = $info; $cachedInfo{mtime}->{$file} = $fileinfo; if ($cacheAdditions > 200) { eval { writeCache(); }; $cacheAdditions = 0; } else { $cacheAdditions++; } } } # Purpose: Remove cached information about a file # Usage: removeFromCache($file); sub removeFromCache { my $file = shift; delete($cachedInfo{info}->{$file}); delete($cachedInfo{mtime}->{$file}); } # Purpose: Rename a file in the cache # Usage: cacheRename($oldName,$newName); sub cacheRename { my $oldFile = shift; if(not defined $cachedInfo{info} or not defined $cachedInfo{info}->{$oldFile}) { return; } my $newFile = shift; addToCache($newFile,$cachedInfo{info}->{$oldFile}); removeFromCache($oldFile); } # Purpose: Load cached information # Usage: loadCache(); sub loadCache { my $cleaning = shift; printv(M_DEBUG,'Caching is enabled'."\n"); if(not defined $ENV{HOME}) { die('The environment variable HOME is not set. Unable to continue. Set HOME or use --no-cache'."\n"); } $cacheFile = $ENV{HOME}.'/.mussort-cache'; if (-e $cacheFile) { my $iFile = $cacheFile; $iFile =~ s/^$ENV{HOME}\/*/~/; if ($readFromCache) { printv(M_STANDARD,'Using cache from '.$cacheFile."\n"); } else { printv(M_STANDARD,'Refreshing cache at '.$cacheFile."\n"); } my $info = retrieve($cacheFile) or FatalError('Failed to retrieve() cache from '.$cacheFile.': '.$!); if ($info && ref($info) eq 'HASH') { printv(M_DEBUG,"Read cached information\n"); %cachedInfo = %{$info}; # Data in these older caches are in many cases invalid, so to be on the # safe side we ignore it. if(not defined $cachedInfo{cacheCompat}) { printv(M_STANDARD,'Note: Cache format outdated, ignoring cached data'."\n"); %cachedInfo = (); } else { if ( (not defined($cachedInfo{lastMussortVersion}) or $cachedInfo{lastMussortVersion} ne $VERSION) and (not $cleaning) ) { printv(M_STANDARD,'NOTICE: You appear to have recently upgraded mussort, you may want to run "mussort --cleancache"'."\n"); printv(M_STANDARD,' This message will only be displayed once.'."\n"); } # If the cache file is over 25 MiB, display a warning if(not $cleaning and -s $cacheFile > 26214400) { my $size = -s $cacheFile / 1024 / 1024; printv(M_STANDARD,'NOTICE: Your cache file is unreasonably large ('.$size.' MiB).'."\n"); printv(M_STANDARD,' You may want to run "mussort --cleancache" to reduce the size'."\n"); } $cachedInfo{cacheCompat} ||= 1; if ($cachedInfo{cacheCompat} > 1) { FatalError('The mussort cache file is incompatible with this version of mussort'."\n". 'Upgrade to '.$cachedInfo{lastMussortVersion}.' or use --no-cache (or remove the cache file)'."\n"); } } return true; } elsif(ref($info)) { FatalError('retrieve() returned a useless reference of type: '.ref($info).' - try --no-cache or remove '.$cacheFile."\n"); } return false; } else { printv(M_STANDARD,'Will create cache file at '.$cacheFile."\n"); return false; } } # Purpose: Write the cache if there is data in it # Usage: writeCache(); sub writeCache { my $ignoreError = shift; if(defined($cachedInfo{info}) && keys(%{$cachedInfo{info}})) { my $doneLevel = M_VERBOSE; my $err; if (-e $cacheFile) { printv(M_VERBOSE,'Writing updated cache to '.$cacheFile.'...'); } else { $doneLevel = M_STANDARD; printv(M_STANDARD,'Writing cache file '.$cacheFile.'...'); } $cachedInfo{lastMussortVersion} = $VERSION; $cachedInfo{cacheFormat} = 1; $cachedInfo{cacheCompat} = 1; store(\%cachedInfo,$cacheFile) or $err = 1; if ($err) { if(not $ignoreError) { printv($doneLevel,'failed. '); FatalError('Failed to store() cache in '.$cacheFile.': '.$err); } else { printv($doneLevel,'failed ('.$err.')'."\n"); } } else { printv($doneLevel,'done'."\n"); } } } # Purpose: Retrieve a generated filename or dirname of at most 254 characters # Usage: name = GetNameOfLength(\@names, JOINCHAR,EXT); # \@names is an arrayref containing the name components # JOINCHAR is the character to join the contents of \@names with # EXT is the extension (sans the .) to add, can be left undef for no extension sub GetNameOfLength { # The names arrayref my $names = shift; # The join character my $joiner = shift; # The extension, if any my $extension = shift; # Generate a name my $NewName; if ($extension) { $NewName = join($joiner,@{$names}).'.'.$extension; } else { $NewName = join($joiner,@{$names}); } # Keep track of the number of times through the loop my $loopC = 0; # The maximum length the bare string (sans extension) can be my $maxBareLength; if ($extension) { # 253 because the . in the Ext takes one character (254-1) $maxBareLength = 253-length($extension); } else { $maxBareLength = 254; } # Generate a string of the proper length while(length($NewName) > $maxBareLength) { # Figure out how many characters we need to get my $need = length($NewName)-$maxBareLength; # The largest component of the names-array my $largestI; # The length of the above component string my $largestLen = 0; # Loop through each component to figure out which is the largest for my $i(0..@{$names}) { next if ! defined($names->[$i]); if (length($names->[$i]) > $largestLen) { $largestI = $i; $largestLen = length($names->[$i]); } } # Figure out how many characters we need to remove, the +3 is for the three dots # we add when the component is too long my $reclaim = $need+3; # During the first 10 loops reclaim at most 100 characters from a single string if ($reclaim > 100 && $loopC < 10) { printv(M_DEBUG,'GetNameOfLength: Need '.$need.' characters, setting current value to 100'."\n"); $reclaim = 100; } printv(M_DEBUG,'GetNameOfLength: Need to reclaim '.$reclaim.' characters from string of '.$largestLen." characters\n"); # Find the index to cut at my $index = $largestLen-$reclaim; printv(M_DEBUG,'GetNameOfLength: Reclaiming at index '.$index."\n"); # Cut the string $names->[$largestI] = substr($names->[$largestI],0,$index).'...'; # Generate a new filename if ($extension) { $NewName = join($joiner,@{$names}).'.'.$extension; } else { $NewName = join($joiner,@{$names}); } # Bump the loop counter $loopC++; # Abort if we've tried 50 times if ($loopC > 50) { FatalError('Failed to generate filename. Ended up with "'.$NewName.'", but kept looping to generate a better name.'); } } return $NewName; } # Purpose: Get the new filename for the file # Usage: my $NewFileName = GetNewFileName(InfoHash); sub GetNewFileName { my $Info = shift; my $Compilation = shift; if (IsInvalidTagValue($Info->{Title}) or IsInvalidTagValue($Info->{Band})) { return; } my @NameComponents; push(@NameComponents, $Info->{Band},$Info->{Title}); if(not $Info->{Track} eq 'Unknown' and not $Info->{Track} =~ /\D/) { if(not $Info->{Track} =~ /\d\d/) { $Info->{Track} = "0$Info->{Track}"; } # Disallow 00/0 if($Info->{Track} > 0 ) { unshift(@NameComponents,$Info->{Track}); } } if ( ref($Info->{SetNo}) && defined $Info->{SetNo}->{total} && $Info->{SetNo}->{total} > 1 && $Info->{SetNo}->{number} != 0 ) { unshift(@NameComponents,'CD'.$Info->{SetNo}->{number}); } my $NewName = GetNameOfLength(\@NameComponents,'-',$Info->{Ext}); return($NewName); } # Purpose: Get a list of directories in a directory - possibly cached # Usage: array = getDirectoriesIn(directory,type); sub getDirectoriesIn { my $dir = shift; my $type = shift; if(not defined $dir or not defined $type) { die; } if(not defined $dirInfoCache[$type]) { $dirInfoCache[$type] = {}; } if(defined $dirInfoCache[$type]->{$dir}) { return @{$dirInfoCache[$type]->{$dir}}; } if(not $type eq DIR_TYPE_PRIMARY) { $dirInfoCache[$type] = {}; } opendir(my $dirHandle,$dir); my @dirs; foreach(readdir($dirHandle)) { next if not -d $_; push(@dirs,$_); } @dirs = sort(@dirs); $dirInfoCache[$type]->{$dir} = \@dirs; return @dirs; } # Purpose: Get the new directory path for the file # Usage: my $NewDirName = GetNewDirName(InfoHash); sub GetNewDirName { my $Info = shift; my $BaseDir = shift; my $Compilation = shift; if(IsInvalidTagValue($Info->{Band})) { return; } my $FirstDir; my $SecondDir; if ($Compilation) { if(IsInvalidTagValue($Info->{Album})) { return; } $FirstDir = $Info->{Album}; $SecondDir = ''; } else { $FirstDir = $Info->{Band}; $SecondDir = $Info->{Album}; } if(defined($FirstDir) && length($FirstDir)) { $FirstDir = GetNameOfLength([ $FirstDir ],'',undef); } if(defined($SecondDir) && length($SecondDir)) { $SecondDir = GetNameOfLength([ $SecondDir ],'',undef); } if($DirInsensitive) { ($FirstDir,$SecondDir) = GetNewDirName_insensitive($FirstDir,$SecondDir,$BaseDir); } elsif($DirConsistent) { ($FirstDir,$SecondDir) = GetNewDirName_consistent($FirstDir,$SecondDir); } if(defined $SecondDir and length $SecondDir and not $SecondDir eq 'Unknown') { return("$BaseDir/$FirstDir/$SecondDir/"); } else { return("$BaseDir/$FirstDir/"); } } # Purpose: Retrieves case-insensitive directory names # Usage: ($first,$second) = GetNewDirName_insensitive($first,$second,$base); sub GetNewDirName_insensitive { my($FirstDir,$SecondDir,$BaseDir) = @_; # Get lowercased and fixed name my $lowerFirst = lc($FirstDir); $lowerFirst =~ s/[\.\,\&]//g; my $lowerSecond = lc($SecondDir); $lowerSecond =~ s/[\.\,\&]//g; if($DirPreferance{$lowerFirst}) { $FirstDir = $DirPreferance{$lowerFirst}; if($DirPreferance{$lowerSecond}) { $SecondDir = $DirPreferance{$lowerSecond}; } } else { $FirstDir = getSingleInsensitiveDirName($FirstDir,$BaseDir,DIR_TYPE_PRIMARY); if(defined $SecondDir and length $SecondDir and -d $BaseDir . '/' . $FirstDir) { $SecondDir = getSingleInsensitiveDirName($SecondDir,$BaseDir.'/'.$FirstDir,DIR_TYPE_SECONDARY); } $DirPreferance{$lowerFirst} = $FirstDir; if(defined $lowerSecond and length $lowerSecond) { $DirPreferance{$lowerSecond} = $SecondDir; } } return ($FirstDir,$SecondDir); } # Purpose: Retrieves a single consistent directory name # Usage: ($dir) = getSingleConsistentDirName($dir,$baseDir,$dirType); sub getSingleInsensitiveDirName { my ($dir,$base,$type) = @_; if (-d $base) { my $name; my $alternate; my $lower = lc($dir); my @dirList = getDirectoriesIn($base,$type); foreach my $try (@dirList) { my $lTry = lc($try); if ($lTry eq $lower) { $name = $try; $alternate = undef; last; } elsif(not $alternate) { my $testDir = $lower; $testDir =~ s/(-|_)+//g; my $testTry = $lTry; $testTry =~ s/(-|_)+//g; if ($testDir eq $testTry) { $alternate = $try; } } } if ($name) { return $name; } elsif($alternate) { return $alternate; } } return $dir; } # Purpose: Retrieves consistent directory names # Usage: ($first,$second) = GetNewDirName_consistent($first,$second); sub GetNewDirName_consistent { my($FirstDir,$SecondDir) = @_; $FirstDir = getSingleConsistentDirName($FirstDir); $SecondDir = getSingleConsistentDirName($SecondDir); return($FirstDir,$SecondDir); } # Purpose: Retrieves a single consistent directory name # Usage: ($dir) = getSingleConsistentDirName($dir); sub getSingleConsistentDirName { my $dir = shift; # Don't process undef if(not defined $dir) { return $dir; } $dir = lc($dir); $dir = getSingleConsistentEntity($dir,qr/[\s_]/o,'_',2); if ($dir =~ /\./) { $dir = getSingleConsistentEntity($dir,qr/[\.]/o,'.',0); } no warnings; # If not perl will spew warnings about the below qw() foreach my $thing (qw(- : ,)) { if ($dir =~ /$thing/) { $dir = getSingleConsistentEntity($dir,qr/$thing/,$thing,2); } } # Finally, uppercase the first char and return $dir = ucfirst($dir); return $dir; } # Purpose: Get a single consistently named entity according to supplied rules # Usage: entity = getSingleConsistentEntity(name, regex, joinwith, ucthreshold); sub getSingleConsistentEntity { my $name = shift; my $splitRegex = shift; my $joinWith = shift; my $ucThreshold = shift; my @entries = split($splitRegex,$name); my @final; foreach my $e(@entries) { if (length($e) > $ucThreshold) { # This is far from an exhaustive list, but having these as lowercase # usually makes a lot of sense, and they are very common in names. if ($e ne 'and' && $e ne 'the') { $e = ucfirst($e); } } push(@final,$e); } return join($joinWith,@final); } # Purpose: Do the actual renaming # Usage: RenameFile(Original name, New Name, BaseDir); sub RenameFile { my $OrigFile = shift; my $NewFile = shift; my $BaseDir = shift; # Get some prettier names to display my $OutputOldName = $OrigFile; my $OutputNewName = $NewFile; $OutputOldName =~ s/^\Q$BaseDir\E\/*//; $OutputOldName =~ s#/+#/#g; $OutputNewName =~ s/^\Q$BaseDir\E\/*//; $OutputNewName =~ s#/+#/#g; my $Directory = dirname($NewFile); if(($OutputOldName eq $OutputNewName) or ($NewFile eq $OrigFile)) { return; } # If it exists and isn't a directory then just return if(-e $Directory and not -d $Directory) { return; } # If the length of the filename is less than 7 just return if(length(basename($NewFile)) < 7) { return; } # Create the dir eval { intMkpath(dirname($NewFile)); 1; } or do { FatalError('Failed to create path' . dirname($NewFile) . ": $@\nWas processing $OrigFile"); }; # Check if the file already exists if(-e $NewFile) { if ($dupeAction == DUPE_REPLACE) { # Check which file is the largest if(-s realpath($NewFile) > -s realpath($OrigFile)) { printv(M_STANDARD,"Remove: $OrigFile\n"); unlink($OrigFile); $cleanTree{dirname($OrigFile)} = true; return; } } elsif($dupeAction == DUPE_NOREMOVE) { return; } elsif($dupeAction == DUPE_KEEP) { my $ext = $NewFile; my $name = $NewFile; $ext =~ s/.*\.([^\.]+)$/$1/; $name =~ s/^(.*)\.[^\.]+$/$1/; my $no = 0; my $nextName; while((not defined $nextName) or (-e $nextName)) { $no++; $nextName = $name.'-'.$no.'.'.$ext; } $NewFile = $nextName; } else { die('Unknown dupeAction: '.$dupeAction); } } # Output info and do the actual renaming printv(M_STANDARD,"Rename: $OutputOldName -> $OutputNewName\n"); unless(defined $DryRunMove) { move($OrigFile,$NewFile) or FatalError("Unable to move $OrigFile to $NewFile: $!"); foreach my $fname (qw(folder cover)) { foreach my $fmt (qw(jpg png jpeg)) { if (-e dirname($OrigFile).'/'.$fname.'.'.$fmt && ! -e dirname($NewFile).'/'.$fname.'.'.$fmt) { move(dirname($OrigFile).'/'.$fname.'.'.$fmt,dirname($NewFile).'/'.$fname.'.'.$fmt); } } } cacheRename($OrigFile,$NewFile); $cleanTree{dirname($OrigFile)} = true; } } # Purpose: Queue a file for renaming # Usage: QueueRename(Original name, New Name, BaseDir); sub QueueRename { my $OrigFile = shift; my $NewFile = shift; my $BaseDir = shift; return if ($OrigFile eq $NewFile); $CompilationDetection->{fileMap}{$OrigFile} = { newFile => $NewFile, baseDir => $BaseDir, }; } # Purpose: Remove the supplied directory and up to two directories below it in the tree. # Usage: RemoveIfEmpty(DIR); sub RemoveIfEmpty { return if $dupeAction == DUPE_NOREMOVE; my $Dir = shift; my $SecondDir = dirname($Dir); my $ThirdDir = dirname($SecondDir); my $Removed; foreach($Dir,$SecondDir,$ThirdDir) { if(not -d $_ or not DirIsEmpty($_)) { last; } rmdir($_) or Error "Unable to remove $Dir: $!"; $Removed = $_; } if($Removed) { printv(M_STANDARD,"Removed empty directory: $Removed\n"); } } # Purpose: Process a file # Usage: ProcessFile(FILE); sub ProcessFile { my $File = shift; my $BaseDir = shift; if (-d $File) { printv(M_VERBOSE,'Searching through directory '.$File."\n"); if ($addAllCleanTree) { $cleanTree{$File} = true; } return; } return if not $File =~ /\.(ogg|mp3|flac)$/gi; # It might be a dangling symlink, if it is then just silently skip it return if not -e $File; my($NewName,$NewDir) = getNewFilePath($File,$BaseDir); return if not defined $NewName or not defined $NewDir; if ($CompilationDetection) { QueueRename($File,"$NewDir/$NewName",$BaseDir); } else { RenameFile($File,"$NewDir/$NewName",$BaseDir); } } # Purpose: Get the new dir path and filenames for a file # Usage: my($NewName,$NewDir) = getNewFilePath($File,$BaseDir,Compilation?); sub getNewFilePath { my($File,$BaseDir,$Compilation) = @_; # Get info my $FileInfo = GetInfo($File); # Build a new filename for the music file my $NewName = GetNewFileName($FileInfo,$Compilation); my $NewDir = GetNewDirName($FileInfo,$BaseDir,$Compilation); if(not defined($NewName)) { if(not $SilentSkip) { printv(M_STANDARD,"Skipped: $File\n"); } return; } my $DirInfo = dirname($File); $DirInfo =~ s/^\Q$BaseDir\E//; $NewDir = $NewDir ? $NewDir : dirname($File); return($NewName,$NewDir); } # Purpose: Process pending compilation actions in $CompilationDetection # Usage: ProcessCompilation(); sub ProcessCompilation { my $BaseDir = shift; my $compilationAlbums = []; my @compilationRename; printv(M_VERBOSE,'Detecting compilation albums...'); foreach my $album (keys(%{$CompilationDetection->{album}})) { next if IsInvalidTagValue($album); my $thisAlbum = $CompilationDetection->{album}->{$album}; if (not keys(%{$thisAlbum}) > 2) { next; } foreach my $artist (keys(%{$thisAlbum})) { if(@{$thisAlbum->{$artist}} > 2) { next; } } my @files; foreach my $artist (keys %{$thisAlbum}) { foreach my $file (@{$thisAlbum->{$artist}}) { push(@files,$file); if ($CompilationDetection->{fileMap} and $CompilationDetection->{fileMap}->{$file}) { delete($CompilationDetection->{fileMap}->{$file}); } } } push(@compilationRename,{ files => \@files, album => $album, }); } printv(M_VERBOSE,"done\n"); foreach my $compilationRef (@compilationRename) { my $compilation = $compilationRef->{files}; printv(M_STANDARD,"Detected compilation album: $compilationRef->{album}\n"); foreach my $File (@{$compilation}) { # Build a new filename for the music file my($NewName,$NewDir) = getNewFilePath($File,$BaseDir,true); next if not defined $NewDir or not defined $NewName; RenameFile($File,$NewDir.'/'.$NewName,$BaseDir); } } # Finally, rename those left in fileMap if ($CompilationDetection->{fileMap}) { foreach my $file (sort keys %{$CompilationDetection->{fileMap}}) { RenameFile($file, $CompilationDetection->{fileMap}->{$file}->{newFile}, $CompilationDetection->{fileMap}->{$file}->{baseDir}, ); } } # Reset it for the next dir $CompilationDetection = {}; } # Purpose: Sort files # Usage: sort sortFiles @_ sub sortFiles { if (-d $a and not -d $b) { return 1; } elsif(-d $b and not -d $a) { return -1; } my $sA = lc($a); my $sB = lc($b); return $sA cmp $sB; } # Purpose: Traverse a tree # Usage: ProcessTree(DIR); sub ProcessTree { my $Dir = shift; setTermTitle('mussort ['.$Dir.']'); $Dir = realpath($Dir); if(not -e $Dir) { FatalError($Dir.': does not exist'); } elsif(not -d $Dir or not -r $Dir) { FatalError($Dir.': is not a directory or is not readable'); } printv(M_STANDARD,"Processing: $Dir\n"); find({ wanted => sub { ProcessFile($File::Find::name,$Dir); }, preprocess => sub { my @files; foreach my $f (sort sortFiles @_) { if ($f eq '.git') { next; } push(@files,$f); } return @files; }, }, $Dir ); if ($CompilationDetection) { ProcessCompilation($Dir); } printv(M_VERBOSE,'Looking for empty directories that should be removed...'."\n"); foreach my $cleanDir (sort keys %cleanTree) { RemoveIfEmpty($cleanDir); } return(1); } # Purpose: Output information useful for debugging # Usage: debugInfo(); sub debugInfo { eval('use Digest::MD5; use IPC::Open3;'); my $format = '%-30s: %s'."\n"; printf($format,'mussort version',$VERSION); my $md5 = Digest::MD5->new(); my $loc = realpath($0); open(my $f,'<',$loc); $md5->addfile($f); my $digest = $md5->hexdigest; close($f); printf($format,'MD5:',$digest); print "\nDependencies/library versions:\n"; # Get ogginfo/i3info versions my($id3ver,$id3v2ver,$oggver,$oggPerlVer,$oggPurePerlVer,$audioFileVer,$metaflacver) = ('missing','missing','missing','missing','missing','missing','missing'); if(InPath('id3info')) { open3(my $in, my $out,my $err, 'id3info','-V'); $id3ver = <$out>; $id3ver =~ s/^\D+\d?\D+//; chomp($id3ver); } if(InPath('ogginfo')) { # --meh isn't a valid command-line parameter, but older versions doesn't have -V, # but to an invalid parameter (--meh) it will give us a version number we can regex # out open3(my $in, my $out, my $err, 'ogginfo','--meh'); local $/ = undef; $oggver = <$out>; $oggver =~ s/^\D+//; $oggver =~ s/\n.*//g; chomp($oggver); } if(InPath('id3v2')) { open3(my $in, my $out,my $err, 'id3v2','--version'); $id3v2ver = <$out>; $id3v2ver =~ s/^\s*id3v2\s*//; chomp($id3v2ver); } if(InPath('metaflac')) { open3(my $in, my $out,my $err, 'metaflac','--version'); $metaflacver = <$out>; $metaflacver =~ s/^\s*metaflac\s*//; chomp($metaflacver); } if(tryuse('Ogg::Vorbis::Header::PurePerl')) { $oggPurePerlVer = $Ogg::Vorbis::Header::PurePerl::VERSION; } if(tryuse('Ogg::Vorbis::Header')) { $oggPerlVer = $Ogg::Vorbis::Header::VERSION; # ::Header whines if we don't call Inline::init() eval { Inline::init(); }; } if(tryuse('Audio::File')) { $audioFileVer = $Audio::File::VERSION; } printf($format,'id3info',$id3ver); printf($format,'id3v2',$id3v2ver); printf($format,'ogginfo',$oggver); printf($format,'metaflac',$metaflacver); printf($format,'Ogg::Vorbis::Header',$oggPerlVer); printf($format,'Ogg::Vorbis::Header::PurePerl',$oggPurePerlVer); printf($format,'Audio::File',$audioFileVer); if ($audioFileVer eq 'missing' && $metaflacver eq 'missing') { print "Both Audio::File and metaflac are missing, FLAC support will be unavailable\n"; } print "\nFormat support:\n"; my($mp3,$ogg,$flac) = ('no','no','no'); if ($audioFileVer ne 'missing') { ($mp3,$ogg,$flac) = ('yes','yes','yes'); } if ($id3ver ne 'missing' || $id3v2ver ne 'missing') { $mp3 = 'yes'; } if ($oggver ne 'missing' || $oggPerlVer ne 'missing' || $oggPurePerlVer ne 'missing') { $ogg = 'yes'; } if ($metaflacver ne 'missing') { $flac = 'yes'; } printf($format,'MP3',$mp3); printf($format,'OGG Vorbis',$ogg); printf($format,'FLAC',$flac); if ($mp3 eq 'no' || $ogg eq 'no' || $flac eq 'no') { print "Install missing dependencies to enable additional format support.\n"; } exit(0); } # Purpose: Print formatted --help output # Usage: PrintHelp('-shortoption', '--longoption', 'description'); # Description will be reformatted to fit within a normal terminal sub PrintHelp { # The short option my $short = shift, # The long option my $long = shift; # The description my $desc = shift; # The generated description that will be printed in the end my $GeneratedDesc; # The current line of the description my $currdesc = ''; # The maximum length any line can be my $maxlen = 80; # The length the options take up my $optionlen = 20; # The length the short option take up my $shortlen = 4; if(length($short) > 4) { $shortlen = length($short); } # Check if the short/long are LONGER than optionlen, if so, we need # to do some additional magic to take up only $maxlen. # The +2 here is because we always add some space between them, no matter what if (($shortlen + length($long) + 2) > $optionlen) { $optionlen = $shortlen + length($long) + 2; } # Split the description into lines foreach my $part (split(/ /,$desc)) { if(defined $GeneratedDesc) { if ((length($currdesc) + length($part) + 1 + $optionlen) > $maxlen) { $GeneratedDesc .= "\n"; $currdesc = ''; } else { $currdesc .= ' '; $GeneratedDesc .= ' '; } } $currdesc .= $part; $GeneratedDesc .= $part; } # Something went wrong die('Option mismatch') if not $GeneratedDesc; # Print it all foreach my $description (split(/\n/,$GeneratedDesc)) { printf "%-4s %-15s %s\n", $short,$long,$description; # Set short and long to '' to ensure we don't print the options twice $short = '';$long = ''; } # Succeed return true; } # Purpose: Print a message if verbosity level matches # Usage: printv(VERBOSITY_LEVEL,message); sub printv { my $level = shift; if ($level > $verbosity) { return; } if ($level == M_DEBUG) { print 'Debug: '; } my $string = $_[0]; $string =~ s/\n+/\n/; print $string; # Flush STDOUT $| = true; $| = false; } # Purpose: Check for a file in path # Usage: InPath(FILE) sub InPath { foreach (split /:/, $ENV{PATH}) { if (-x "$_/@_" and not -d "$_/@_" ) { return 1; } } return 0; } # Purpose: Clean up the cache # Usage: cleanCache() sub cleanCache { if(not loadCache(true)) { print "No cached data found - nothing to clean\n"; exit(0); } $| = true; print "Cleaning and validating the cache..."; print "\n" if $verbosity == M_DEBUG; my $removedDangling = 0; my $removedObsolete = 0; my $removedIncomplete = 0; my $existing = 0; my $checked = 0; my $last = 0; foreach my $file (keys %{$cachedInfo{info}}) { $checked++; if ($last + 100 < $checked) { $last = $checked; print '.' if $verbosity < M_DEBUG; } if(not -e $file) { $removedDangling++; removeFromCache($file); printv(M_DEBUG,$file.': was dangling - removed'."\n"); next; } elsif(not defined $cachedInfo{mtime}->{$file}) { $removedDangling++; removeFromCache($file); printv(M_DEBUG,$file.': was semi-dangling (no mtime reference) - removed'."\n"); next; } elsif(not defined $cachedInfo{info}->{$file}) { $removedDangling++; removeFromCache($file); printv(M_DEBUG,$file.': had no actual data - removed'."\n"); next; } elsif(mtime($file) > $cachedInfo{mtime}->{$file}) { $removedObsolete++; removeFromCache($file); printv(M_DEBUG,$file.': has expired from the cache - removed'."\n"); next; } else { my $hadInfo = false; foreach my $ent (qw(Title Band)) { my $t = $cachedInfo{info}->{$file}->{$ent}; if(IsValidTagValue($t) && $t =~ /(\w|\d)/) { $hadInfo++; } } if($hadInfo <= 1) { $removedIncomplete++; removeFromCache($file); printv(M_DEBUG,$file.': had incomplete information - removed'."\n"); next; } elsif(IsValidTagValue($cachedInfo{info}->{$file}->{Track}) and ( ($cachedInfo{info}->{$file}->{Track} =~ /\D/) or ($cachedInfo{info}->{$file}->{Track} > 999) ) ) { $removedIncomplete++; removeFromCache($file); printv(M_DEBUG,$file.': had an invalid track number - removed'."\n"); next; } } $existing++; } print '.' if $verbosity < M_DEBUG; foreach my $file (keys %{$cachedInfo{mtime}}) { if(not defined $cachedInfo{info}->{$file}) { $removedDangling++; $checked++; printv(M_DEBUG,$file.': only had an mtime reference but no data - removed'."\n"); delete($cachedInfo{mtime}->{$file}); } } print "done\n" if $verbosity < M_DEBUG; print "The cache had $checked entries\n"; my $f = "%-25s: %s\n"; printf($f,'Dangling references',$removedDangling); printf($f,'Obsolete references',$removedObsolete); printf($f,'Incomplete references',$removedIncomplete); print "Removed a total of ".($removedDangling+$removedObsolete+$removedIncomplete)." references\n"; print "$existing valid references left\n"; writeCache(); exit(0); } # Purpose: Initialize dependency lists sub initDeps { if(tryuse('Ogg::Vorbis::Header::PurePerl')) { $Has{'Ogg::Vorbis::Header::PurePerl'} = true; } if(tryuse('Ogg::Vorbis::Header')) { $Has{'Ogg::Vorbis::Header'} = true; # ::Header won't work properly if we don't call Inline::init() eval { Inline::init(); }; } if(tryuse('Audio::File')) { $Has{'Audio::File'} = true; } foreach my $cmd (qw(id3v2 id3info ogginfo metaflac)) { if(InPath($cmd)) { $Has{$cmd} = true; } } if(not $Has{'Audio::File'}) { if (not $Has{'id3v2'} and not $Has{'id3info'}) { depError('MP3',[ 'id3v2','id3info','Audio::File'],'id3v2'); } if(not $Has{'ogginfo'} and not $Has{'Ogg::Vorbis::Header::PurePerl'}) { depError('OGG Vorbis',[ 'ogginfo', 'Ogg::Vorbis::Header::PurePerl' ], 'Ogg::Vorbis::Header::PurePerl'); } } } # Purpose: Main application sub main { initDeps(); # This only gets printed if debug output actually IS enabled. printv(M_DEBUG,"Debug output is enabled\n"); if(not (@ARGV)) { FatalError('Requires one option: the directory to process. See --help for more information'); } if($cacheFile) { loadCache(); } else { printv(M_DEBUG,"Cache file did not exist - not loading\n"); } foreach(@ARGV) { ProcessTree($_); } if ($cacheFile) { writeCache(); } exit(0); } Getopt::Long::Configure ('bundling'); GetOptions ( 'help|h' => sub { print "mussort version $VERSION\n\n"; print 'Usage: ' . basename($0) . " [OPTIONS] dir1 dir2 ..\n"; PrintHelp('-h','--help','Display this help screen'); PrintHelp('','--version','Display version information'); PrintHelp('-k','--keepdupes','Keep and sort duplicates (default)'); PrintHelp('-l','--largest','When hitting two files with identical names leave the largest file in place and remove the smallest (overrides --keepdues)'); PrintHelp('-n','--noremove','Never remove any files (overrides --keepdupes)'); PrintHelp('-a','--allowspecial','Allow special letters (accents and other non-ASCII letters)'); PrintHelp('-i','--insensitive','Do case insensitive searches for directory names. This will avoid directory names with different casing but is also slightly slower'); PrintHelp('-s','--consistent','Similarly to -i, this will avoid directory names with different casing by enforcing a consistent casing for all names'); PrintHelp('','--prefer-audiofile','Prefer to use Audio::File for reading tags'); PrintHelp('-c','--compilation','Enable compilation detection (see the manpage)'); PrintHelp('','--silentskip','Supress messages about files skipped'); PrintHelp('-v','--verbose','Increase verbosity. Supply it twice to increase it further'); PrintHelp('','--no-cache','Disable file information caching'); PrintHelp('','--cleancache','Go through the cache and clean up dangling or obsolete data'); PrintHelp('','--refresh-cache','Refresh the cache (use the cache in a write-only mode)'); PrintHelp('','--quiet','Suppress all non-error messages'); PrintHelp('','--dry-run','Output what would be done without doing it'); PrintHelp('','--cleantree','Attempt to clean up the directory tree. This has a significant performance impact. See the manpage for more information'); PrintHelp('','--fileinfo','Display parsed file information for the supplied file.'); PrintHelp('','--debuginfo','Print various technical information related to this installation of mussort'); exit(0); }, 'prefer-audiofile|preferaudiofile' => \$PreferAudioFile, 'n|noremove' => sub { $dupeAction = DUPE_NOREMOVE; }, 'l|largest' => sub { $dupeAction = DUPE_REPLACE; }, 'k|keepdupes' => sub { $dupeAction = DUPE_KEEP; }, 'i|insensitive' => sub { $DirInsensitive = true; die("--insensitive can not be combined with --consistent\n") if $DirConsistent; }, 's|consistent' => sub { $DirConsistent = true; die("--consistent can not be combined with --insensitive\n") if $DirInsensitive; }, 'a|allowspecial' => \$AllowSpecialChars, 'debuginfo' => \&debugInfo, 'c|compilation' => sub { $CompilationDetection = {} }, 'e|cache' => sub { warn('--cache is deprecated, caching is now enabled by default'."\n"); $cacheFile = true; }, 'nocache|no-cache' => sub { $cacheFile = false }, 'refresh-cache' => sub { $readFromCache = false }, 'v|verbose+' => \$verbosity, 'dryrun' => sub { $DryRunMove = true; $cacheFile = false }, 'dryrunmove' => sub { $DryRunMove = true }, 'q|quiet' => sub { $verbosity = 0 }, 'cleantree' => $addAllCleanTree, 'cleancache' => \&cleanCache, 'fileinfo=s' => sub { shift; my $file = shift; $file = realpath(dirname($file)).'/'.basename($file); eval('use Data::Dumper qw(Dumper); $Data::Dumper::Indent = 0;'); initDeps(); if($cacheFile) { loadCache(); } print "File information for $file:\n"; my $info = GetInfo($file); foreach my $entry (keys(%{$info})) { my $c = $info->{$entry}; if(defined($c) and ref($c)) { $c = Dumper($c); $c =~ s/;\n$//; $c =~ s/^\$VAR\d*\s*=\s*//; } if(not defined $c or not length($c)) { $c = '(unknown)'; } print "$entry: $c\n"; } exit(0); }, 'version' => sub { print "mussort version $VERSION\n"; exit(0); }, 'silentskip' => \$SilentSkip, ) or die('See ' . basename($0) . " --help for more information\n"); main(); __END__ =head1 NAME mussort - A simple music file sorting program =head1 SYNOPSIS mussort I<[OPTIONS]> I =head1 DESCRIPTION This is a simple tool that sorts a music collection. It recursively searches a directory for MP3, OGG Vorbis and FLAC files, processing them one by one. It then reads the information from the file and puts them into a newly sorted directory tree, in the form I. The files are renamed to I. TRACKNUMBER is omitted if it isn't found, and CDn is only included if it detects multiple discs. If you use --compilation then the sorting will differ for those albums that are detected to be compilation albums, those will be sorted as I instead. mussort will remove directories that end up empty after sorting. By default mussort will cache file information in ~/.mussort-cache, which speeds up subsequent invocations significantly =head1 OPTIONS =over =item B<-h, --help> Display a short help screen and exit =item B<--version> Display version information and exit =item B<-k, --keepdupes> When mussort reaches two files with identical names, it will keep both, naming the one it finds last with a number at the end (ie. I). This is the default. Use I<--largest> and I<--noremove> to alter this behaviour. =item B<-l, --largest> When mussort reaches two files with identical names, it will remove (delete) the smallest file and leave the largest in place. =item B<-n, --noremove> When mussort reaches two files with identical names it will ignore one of the files (the last one it sees) and not sort it. =item B<-i, --insensitive> Makes mussort do case-insensitive searches for directory names. This is useful when the case in the name of an artist differs and makes mussort place all the music correctly into one directory. This I be a bit slower than normal operation, but not much. When using this option there is a chance that directory names will differ slightly between different collections (see also I<--consistent>). You can combine this option with I<--compilation> if you want to. You can not combine I<--insensitive> with I<--consistent>. =item B<-s, --consistent> Makes mussort generate consistent directory names. This is useful to ensure that two collections on different machines have the exact same directory layout, so that they can be rsynced easily. It avoids directory names that are identical except for the casing, and is also consistent between runs, and accross different machines. Unlike I<-i>, the performance penalty is almost nonexistant. You can combine this option with I<--compilation> if you want to. Note that I<--compilation> changes the directory layout, so a collection sorted without I<--compilation> but with I<--consistent> will differ from a collection sorted with both I<--compilation> B I<--consistent>. You can not combine I<--consistent> with I<--insensitive>. =item B<-a, --allowspecial> This forces mussort to not strip special characters from file and directory names. =item B<-c, --compilation> Enables compilation detection. In this mode mussort will go through all files without moving them first, sorting them in an internal data structure, then it will attempt to detect compilation albums and re-sort members of the compilation albums before finally moving files on-disk. Compilation albums are placed into a directory tree matching I instead of I. Note that this mode is a bit slower than normal mode, and it will take a bit longer before any actual changes are done. This is because it needs to search through all files before it can start to rename them. =item B<--silentskip> Makes mussort not output messages about files that it skips (those that are skipped are generally badly tagged, or not tagged at all). =item B<-v, --verbose> Increases the verbosity of mussort. Supply twice to further increase verbosity. If supplied once, extra information about what mussort is doing, such as which directory is being processed, will be output (this can be useful in --compilation mode, as --compilation won't output anything until after all files have been read). If supplied twice, it will also output information about which file is currently being read. =item B<--quiet> Suppresses all status messages (and the terminal title). Errors will still get printed. =item B<--dry-run> Just output what would be done, without actually doing it. =item B<--no-cache> Disables caching of file information. By default mussort will cache file information (such as tags) between runs as that significantly improves speed in susequent invocations. If you supply this, mussort will neither write nor read any cache. Usually there is very little gain in using this, collections as large as 13 000+ music files only have a cache file of ~3.2MB. If you want to get back a little of the space the cache file takes, see --cleancache. =item B<--refresh-cache> This will enable caching in a 'write-only' mode. That is it will write new information to the cache, but it will not use existing information. This can be used as an alternative to deleting the entire cache when you have different directories that you sort, and only want to re-sort (refresh) one of them. =item B<--cleancache> This cleans up the cache. It will go through all entries in the cache and remove dangling references, expired data and incomplete data. Incomplete data is added when mussort finds a file that has invlalid/empty tags. Those files are still added to the cache so that mussort does not have to re-evaluate them each time, but their entries contain no valid data. This can be useful in a few cases: =over =item - If you have deleted or mvoed a large amount of music files that mussort has previously sorted =item - If you want to save a tiny bit of HD space =item - If you want mussort to re-read information from files that previously contained invalid data =back mussort will automatically re-evaluate any expired cache data during runtime, so you are never B to run I<--cleancache>. =item B<--cleantree> When this parameter is in effect, mussort will attempt to clean up the directory tree by removing all empty directories that it hits (in addition to performing its usual sorting). Note that this has a rather significant performance impact because mussort needs to do a lot of extra readdir() operations, and should only be done if you notice a lot of empty directories in your music tree and want them cleaned up. Normally mussort will automatically clean directories that are empty as a result of sorting, but this option will make it check all directories it finds. =back =head1 DEPENDENCIES mussort can use several libraries and utilities to retrieve tag information. It requires only one for each format, however if multiple methods are available mussort will try each in turn if one of them fails. It needs: =over =item For MP3: id3v2 (best), id3info from id3lib, or Audio::File =item For Vorbis: Ogg::Vorbis::Header::PurePerl (best), ogginfo from vorbis-tools, or Audio::File =item For FLAC: Audio::File (best) or metaflac =back =head1 FILES =over =item ~/.mussort-cache The mussort file information cache. Not created if --no-cache is supplied. You can safely remove this file any time if you want to (see also --cleancache). =back =head1 BUGS AND LIMITATIONS If you find a bug, please report it at L. =head1 INCOMPATIBILITIES None known. =head1 AUTHOR B is written by Eskild Hustvedt I<> =head1 LICENSE AND COPYRIGHT Copyright (C) Eskild Hustvedt 2007, 2008, 2009, 2010, 2011 This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.