Repository: ag91/code-compass Branch: main Commit: 6b741978c83f Files: 26 Total size: 189.5 KB Directory structure: gitextract_29gz1cep/ ├── .gitignore ├── .prettierrc ├── LICENSE ├── README.org ├── code-compass.el ├── pages/ │ ├── age-enclosure-diagram/ │ │ ├── script.js │ │ ├── style.css │ │ └── zoomable.html │ ├── edge-bundling/ │ │ ├── script.js │ │ ├── style.css │ │ └── zoomable.html │ ├── enclosure-diagram/ │ │ ├── script.js │ │ ├── style.css │ │ └── zoomable.html │ └── knowledge-enclosure-diagram/ │ ├── script.js │ ├── style.css │ └── zoomable.html ├── requirements.txt ├── scripts/ │ ├── code_age_csv_as_enclosure_json.py │ ├── communication_csv_as_edge_bundling.py │ ├── coupling_csv_as_edge_bundling.py │ ├── csv-to-pie-graph.py │ ├── csv_as_enclosure_json.py │ ├── knowledge_csv_as_enclosure_diagram.py │ └── refactoring_csv_as_enclosure_diagram.py └── test/ └── code-compass-test.el ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ dependencies/ ================================================ FILE: .prettierrc ================================================ { "tabWidth": 4, } ================================================ FILE: LICENSE ================================================ 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 . ================================================ FILE: README.org ================================================ * Code compass :PROPERTIES: :ID: 1683c6ef-701e-476c-a104-56db5582c785 :END: This package shall guide you in your software development within Emacs. For example, it will point at the code that requires your changes the most and it will suggest you who to ask for help when you are lost. I have presented some of the capabilities of *code-compass* in [[https://emacsconf.org/2020/talks/24/][this talk of EmacsConf2020]]. ** Credits :PROPERTIES: :ID: 3d3fbd8e-ec09-4dbe-91aa-99713b6fac89 :END: A significant part of this project relies on [[https://github.com/adamtornhill/code-maat][code-maat]] and the bright mind of his author Adam Tornhill. His books are inspiring and a [[https://pragprog.com/titles/atcrime/your-code-as-a-crime-scene/][suggested]] [[https://pragprog.com/titles/atevol/software-design-x-rays/][read]]. ** Features :PROPERTIES: :CREATED: [2022-04-30 Sat 21:53] :ID: 9c50d648-8562-497e-93d4-088db1a326a8 :END: Use =code-compass-cheatsheet= to have a quick reference of the available commands and their aim. Check the =Release Checklist= heading for more information about them. ** Installation and Dependencies :PROPERTIES: :CREATED: [2020-12-11 Fri 19:10] :ID: 6d691473-a522-46cf-ae41-09fd5c2c69df :END: *Please run =code-compass-doctor= if you encounter errors in running this tool* Note: I label dependencies as *optional* when the commands needing the dependency warn you they cannot execute because the dependency is missing. This project depends on the following external dependencies: - Git - Python 3 - Java 8 or above - code-maat - cloc - graph-cli (optional - only few commands will not succeed) - gource (optional) And the following Emacs packages: - async.el - dash.el - s.el - simple-httpd If you are on a Linux system, Docker, the Code Maat image, and cloc can be installed by running the following script: #+begin_src sh :noeval # Docker is only necessary if you want to use that instead of the (automatically downloaded) JAR file # see here for how to install in systems different from Linux Debian: https://gist.github.com/rstacruz/297fc799f094f55d062b982f7dac9e41 #sudo apt install docker.io; #sudo systemctl start docker; # after you manage to run docker successfully #git clone https://github.com/adamtornhill/code-maat.git; #cd code-maat; #docker build -t code-maat-app . sudo apt install cloc; #+end_src Python dependencies are stored in a virtual environment managed by code-compass. These are installed by the function =code-compass-install=. *** Installation from Melpa Code-compass can be installed as a package using =use-package=: #+begin_src elisp :noeval (use-package code-compass :ensure t :config (code-compass-install)) #+end_src *** Installation Code-compass can be installed from manually with: #+begin_src elisp :noeval (use-package async) (use-package dash) (use-package s) (use-package simple-httpd) (use-package code-compass :load-path "~/.emacs.d/lisp" :config (code-compass-install)) #+end_src For trying things out in a clean Emacs: #+begin_src elisp :noeval :tangle /tmp/code-compass-minimal-setup.el (require 'package) (eval-and-compile (setq package-archives '(("melpa-stable" . "https://stable.melpa.org/packages/") ("melpa" . "https://melpa.org/packages/") ("marmalade" . "https://marmalade-repo.org/packages/") ("org" . "https://orgmode.org/elpa/") ("gnu" . "https://elpa.gnu.org/packages/")))) (package-initialize) ;;; Bootstrap use-package ;; Install use-package if it's not already installed. (unless (package-installed-p 'use-package) (package-refresh-contents) (package-install 'use-package)) (setq use-package-always-ensure 't) (require 'use-package) (require 'diminish) (require 'bind-key) (use-package async) (use-package dash) (use-package s) (use-package simple-httpd) #+end_src #+begin_src sh :results none emacs -Q -l /tmp/code-compass-minimal-setup.el -l ./code-compass.el #+end_src ** Limitations :PROPERTIES: :CREATED: [2020-12-11 Fri 21:35] :ID: efdeb29f-083a-487c-93d5-48c93fc5b9c8 :END: The limitations I know: 1. only Git support for now, but I am open to PRs (should be easy because code-maat partially support other VCS already) 2. Adam said that code-maat may fail for code bases larger than 5 million lines. Please report if you observe that is the case, we will find a solution. 3. most likely others I will eventually discover from the issues ;) ** Release Checklist :PROPERTIES: :ID: 8450da84-5aa9-46f9-b65c-5055ae907975 :END: Releasing this in the wild is exciting, but it will take some time. Here what you can expect. *** DONE install instructions and dependencies :PROPERTIES: :ID: 27174a0f-186d-4963-a5b3-4704d680476f :END: - https://ag91.github.io/blog/2020/12/11/emacsconf2020-first-steps-towards-emacs-becoming-your-code-compass/ *** DONE hotspots :PROPERTIES: :CREATED: [2020-12-18 Fri 18:01] :ID: 00f4d809-e7e0-4f29-a2af-30fa07a080e7 :END: :LOGBOOK: CLOCK: [2020-12-18 Fri 18:01]--[2020-12-18 Fri 18:01] => 0:00 :END: - hotspots analysis: https://ag91.github.io/blog/2020/12/18/emacs-as-your-code-compass-finding-code-hotspots/ - hotspots evolution: https://ag91.github.io/blog/2020/12/24/emacs-as-your-code-compass-looking-at-hotspots-evolution/ - hotspots analysis for microservices: https://ag91.github.io/blog/2021/04/08/emacs-as-your-code-compass-find-hotspots-in-micro-services/ *** DONE software complexity :PROPERTIES: :ID: 6847956b-75c1-4ad7-b911-1994a21a26ac :CREATED: [2020-12-27 Sun 14:10] :END: - https://ag91.github.io/blog/2020/12/27/emacs-as-your-code-compass-how-complex-is-this-code/ *** DONE code churn :PROPERTIES: :ID: 04b3a73e-60f7-4a6c-87d7-10ff978e24b4 :CREATED: [2021-01-01 Fri 16:54] :END: - https://ag91.github.io/blog/2021/01/01/emacs-as-your-code-compass-how-much-code-we-produced-for-this-repository-lately/ *** DONE change coupling :PROPERTIES: :ID: 59df8e40-e5d3-47dc-b9da-10666301acc8 :END: - https://ag91.github.io/blog/2021/01/07/emacs-as-your-code-compass-how-related-are-these-modules/ *** DONE use case of coupling: find coupled files :PROPERTIES: :CREATED: [2021-01-12 Tue 22:16] :ID: 29de5da7-8ba0-46a7-8afa-397b02d4642d :END: - https://ag91.github.io/blog/2021/01/12/emacs-as-your-code-compass-let-history-show-you-which-files-to-edit-next/ *** DONE code communication :PROPERTIES: :CREATED: [2021-01-22 Fri 20:32] :ID: ceb52892-7b08-4171-8887-670254989b4c :END: :LOGBOOK: CLOCK: [2021-01-12 Tue 22:16] :END: - [[https://ag91.github.io/blog/2021/01/22/emacs-as-your-code-compass-find-collaborators-you-should-(chit)-chat-with/]] *** DONE code knowledge :PROPERTIES: :CREATED: [2021-01-31 Sun 11:48] :ID: 04064490-aaa7-44c3-a31c-a8d223db31a0 :END: :LOGBOOK: CLOCK: [2021-01-22 Fri 20:32] :END: - https://ag91.github.io/blog/2021/01/28/emacs-as-your-code-compass-who-can-i-ask-for-help/ *** DONE code stability :PROPERTIES: :ID: fca4bd0a-8c67-4482-8692-a32f98ea2438 :CREATED: [2021-02-06 Sat 16:42] :END: - https://ag91.github.io/blog/2021/02/06/-emacs-as-your-code-compass-how-stable-is-my-code/ *** DONE fragmentation :PROPERTIES: :ID: b72b368e-7436-4311-a0e6-97b71b8f2260 :CREATED: [2021-02-12 Fri 19:19] :END: :LOGBOOK: CLOCK: [2021-02-06 Sat 16:42] :END: https://ag91.github.io/blog/2021/02/11/emacs-as-your-code-compass-how-fragmented-is-the-knowledge-of-this-file/ *** DONE word analysis :PROPERTIES: :CREATED: [2021-02-20 Sat 19:14] :ID: 46dcf690-2294-47fd-bc33-e1699eba845a :END: - https://ag91.github.io/blog/2021/02/20/emacs-as-your-code-compass-what-is-this-text-about----without-me-reading-it/ *** DONE use case of coupling: generate todos for current file :PROPERTIES: :CREATED: [2021-03-05 Fri 00:17] :ID: a5e1f2f8-3836-4092-bbc7-2943aa2ff186 :END: - https://ag91.github.io/blog/2021/03/04/emacs-as-your-code-compass-what-files-do-i-need-to-change-next/ *** DONE integrate gource :PROPERTIES: :CREATED: [2021-03-04 Thu 10:34] :ID: 63b080a9-859b-4863-af5f-2d6eed8bd215 :END: https://ag91.github.io/blog/2021/03/19/emacs-as-your-code-compass-watch-history-with-gource/ *** DONE file-churn icon :PROPERTIES: :CREATED: [2021-02-24 Wed 21:47] :ID: c4809753-ff55-4726-81d7-e1caa37b60cd :END: - https://ag91.github.io/blog/2021/03/26/emacs-as-your-code-compass-a-gentle-trigger-for-maintenance/ *** DONE main contributors notification :PROPERTIES: :ID: da34e784-028f-4d04-81ec-baa267c9c668 :END: - https://ag91.github.io/blog/2021/04/18/emacs-as-your-code-compass-quietly-show-who-can-help/ *** DONE code refactoring :PROPERTIES: :ID: c0c383ca-c5a1-4c65-be7d-853dce78ac23 :END: https://ag91.github.io/blog/2022/11/23/emacs-as-your-code-compass-who-is-the-person-who-refactored-most-in-this-project/ :PROPERTIES: :CREATED: [2022-11-23 Wed 23:42] :END: *** DONE functions complexity :PROPERTIES: :CREATED: [2022-11-23 Wed 23:42] :END: oh well I needed tree-sitter for this, see here: https://github.com/ag91/moldable-emacs/blob/master/molds/contrib.el#L242 ** License [[https://www.gnu.org/licenses/gpl-3.0.html][GPLv3]] *** Dependencies [[https://github.com/d3/d3/][d3]]: License: [[https://opensource.org/licenses/BSD-3-Clause][BSD-3]] Copyright 2010-2020 Mike Bostock ** Contributing :PROPERTIES: :CREATED: [2020-12-11 Fri 21:40] :ID: f1b0881f-1c66-49d6-ac46-aecd8dbe9e64 :END: If you have ideas or wishes, just open an issue and I will look into it! Thanks for caring. *** Testing :PROPERTIES: :CREATED: [2023-03-09 Thu 16:26] :ID: 7d1a7149-8ef2-41c0-9b6b-36b3000ce561 :END: Functions without side effects have tests in their documentation. To run those install https://github.com/ag91/doctest (at the time of writing my fork as enhancements over the original) and run =doctest=. ** Alternatives :PROPERTIES: :CREATED: [2020-12-18 Fri 16:00] :ID: 77dac754-8a76-4234-bb1c-0f4e0ea6cb46 :END: - [[https://codescene.com/][CodeScene]]: this is the code analysis tool of Adam Tornhill which organizations can use to manage their software and organizational complexity. Code-compass learns from CodeScene and adapts to empower you. - [[https://github.com/textarcana/code-risk/tree/master/bin][code-risk]]: this is a set of scripts Noah Sussman's uses to find quality issues in repositories. Code-compass includes these and make them easily accessible to you. - [[https://github.com/smontanari/code-forensics][code-forensics]]: this makes available code-maat analyses in a node application. Code-compass offers a subset of these for now and focuses more on supporting you while you edit your project. (Thanks @BlankSpruce to share this repository!) - [[https://github.com/aspiers/git-deps/][git-deps]]: this shows you dependencies between git commits. Hopefully code-compass will integrate this project to help you when, for example, you are struggling to identify the commit that broke your release. - ??? ================================================ FILE: code-compass.el ================================================ ;;; code-compass.el --- Navigate software aided by metrics and visualization -*- lexical-binding: t; -*- ;; Copyright (C) 2023 Andrea ;; Author: Andrea ;; Version: 0.1.4 ;; Package-Requires: ((emacs "26.1") (s "1.12.0") (dash "2.13") (async "1.9.7") (simple-httpd "1.5.1")) ;; Keywords: tools, extensions, help ;; Homepage: https://github.com/ag91/code-compass ;; 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 ;;; Commentary: ;; Make Emacs your compass in a sea of software complexity. ;; ;; This tool puts the power and knowledge of your repository history in your hands. ;; You can find what analyses are supported with `code-compass-cheatsheet'. ;; A good way to start is: ;; - `code-compass-show-hotspots': ;; show hotspots in code repository as a circle diagram. ;; Circles are packages or modules. ;; The redder the circle, the more it has been modified lately. The bigger the more code it contains. ;; ;; If you are having trouble with dependencies, try `code-compass-doctor' to get some clarity. ;; ;; See documentation at https://github.com/ag91/code-compass ;;; Code: (require 'dash) (require 's) (require 'simple-httpd) (require 'async) (require 'url) (require 'vc) (defun code-compass--python-script (script) "Return the command to run a script with code-compass' python. " (concat code-compass-download-directory "/venv/bin/python3 " script)) (defgroup code-compass nil "Options specific to code-compass." :tag "code-compass" :group 'code-compass) (defcustom code-compass-default-port 8888 "Default port on which to serve analyses files." :type 'int :group 'code-compass) (defcustom code-compass-default-periods '("beginning" "1d" "2d" "3d" "6d" "12d" "18d" "24d" "1m" "2m" "6m") "Starting date to reduce the Git log for analysis. 'beginning' is a keyword to say to not reduce. 'Nd' means to start after N days, where N is a positive number. 'Nm' means to start after N months, where N is a positive number." :group 'code-compass :type 'string) (defcustom code-compass-snapshot-periods '("1d" "3m" "6m" "9m" "12m" "15m") "A list of snapshots periods to show evolution of analyses over time." :group 'code-compass :type 'string) (defconst code-compass-path-to-code-compass (file-name-directory (or load-file-name (buffer-file-name))) "The directory from where code compass was loaded.") (defun code-compass--expand-file-name (file-name) "Expand FILE-NAME with `code-compass-path-to-code-compass'." (expand-file-name file-name code-compass-path-to-code-compass)) (defcustom code-compass-tmp-directory "/tmp" "Directory to store temporary files generated by code-compass." :group 'code-compass :type 'string) (defcustom code-compass-docker-data-directory "/data" "Directory to store temporary docker files generated by code-compass." :group 'code-compass :type 'string) (defcustom code-compass-download-directory (code-compass--expand-file-name "dependencies") "Directory to store downloaded dependencies." :group 'code-compass :type 'string) (defcustom code-compass-code-maat-command (format "java -jar %s/code-maat-1.0.1-standalone.jar" (code-compass--expand-file-name "dependencies")) "Command to run Code-maat (https://github.com/adamtornhill/code-maat). Currently defaults to use docker because easier to setup." :group 'code-compass :type 'string :options `(,(format "java -jar %s/code-maat-1.0.1-standalone.jar" code-compass-download-directory) ,(format "docker run -v %s/:%s code-maat-app" code-compass-tmp-directory code-compass-docker-data-directory))) (defcustom code-compass-preferred-browser "chromium" "Browser to use to open graphs served by webserver." :group 'code-compass :type 'string) (defcustom code-compass-exclude-directories '("node_modules" "bower_components" "vendor" "tmp") "A list of directory patterns to exclude from reports. Contents are passed to the cloc executable via its --exclude-dir argument." :group 'code-compass :type 'list) (defcustom code-compass-calculate-coupling-project-key-fn (lambda (repository) (concat repository "-" (s-trim (shell-command-to-string (format "cd %s; git rev-parse --short HEAD" repository))))) "Function taking a REPOSITORY path and returning a string." :group 'code-compass :type 'function) (defcustom code-compass-authors-colors (list "red" "blue" "orange" "gray" "green" "violet" "pink" "brown" "aquamarine" "blueviolet" "burlywood" "cadetblue" "chartreuse" "chocolate" "coral" "cornflowerblue" "cyan" "darkblue" "darkcyan" "darkgoldenrod" "darkgray" "darkgreen" "darkkhaki" "darkmagenta" "darkolivegreen" "darkorange" "darkorchid" "darkred" "darksalmon" "darkseagreen" "darkslateblue" "darkslategray" "darkturquoise" "darkviolet" "deeppink" "deepskyblue" "dimgray" "dodgerblue" "firebrick" "forestgreen" "fuchsia" "gold" "goldenrod" "greenyellow" "hotpink" "indianred" "indigo" "lawngreen" "lightcoral" "lightgray" "lightgreen" "lightpink" "lightsalmon" "lightseagreen" "lightskyblue" "lightslategray" "lightsteelblue" "lime" "limegreen" "linen" "magenta" "maroon" "mediumaquamarine" "mediumblue" "mediumorchid" "mediumpurple" "mediumseagreen" "mediumslateblue" "mediumspringgreen" "mediumturquoise" "mediumvioletred" "midnightblue" "mintcream" "mistyrose" "moccasin" "navajowhite" "navy" "oldlace" "olive" "olivedrab" "orangered" "orchid" "palegoldenrod" "palegreen" "paleturquoise" "palevioletred" "papayawhip" "peachpuff" "peru" "plum" "powderblue" "purple" "rosybrown" "royalblue" "saddlebrown" "salmon" "sandybrown" "seagreen" "seashell" "sienna" "silver" "skyblue" "slateblue" "slategray" "snow" "springgreen" "steelblue" "tan" "teal" "thistle" "tomato" "turquoise" "wheat" "whitesmoke" "yellow" "yellowgreen") "Colors to use for authors." :group 'code-compass :type 'list) (defcustom code-compass-pie-or-bar-chart-command (code-compass--python-script "csv-to-pie-graph.py %s") "Command to visualize chart." :group 'code-compass :type 'string :options '((code-compass--python-script "csv-to-pie-graph.py %s") "graph %s --bar --width 0.4 --offset='-0.2,0.2'")) (defcustom code-compass-gource-command "gource" "Command to the gource utility. See https://gource.io/ for more information on how to install." :group 'code-compass :type 'string) (defcustom code-compass-gource-seconds-per-day 0.5 "How long each Git history day should take." :type 'float :group 'code-compass) (defcustom code-compass-display-icon 't "Display an icon in modeline showing growth trend of code. A pointing up icon means the code has been growing, a pointing down arrow has been decreasing." :group 'code-compass :type 'bool) (defcustom code-compass-icon-trends '( :period "3" :always-additions (propertize "⬆" 'face `(:background "DarkOrange")) :always-deletions (propertize "⬇" 'face `(:background "SpringGreen")) :more-additions (propertize "↗" 'face `(:background "Gold")) :more-deletions (propertize "↘" 'face `(:background "GreenYellow"))) "Icon and period of evaluation for trend." :group 'code-compass :type 'plist) (defcustom code-compass-display-file-contributors 't "Enable the listing of contributors for a file in the *Messages* buffer." :group 'code-compass :type 'bool) (defcustom code-compass-cache-file (concat user-emacs-directory ".code-compass/cache") "Directory to store a cache of coupling files." :group 'code-compass :type 'string) ;; these definitions are just to satisfy the linting tools (defvar browse-url-generic-program) (defvar slack-current-team) (declare-function slack-team-users "ext:slack.el") (declare-function slack-create-user-profile-buffer "ext:slack.el") (declare-function slack-buffer-display-im "ext:slack.el") ;;;###autoload (defun code-compass-install (&optional no-query-p) (interactive) (let ((venv-dir (file-name-concat code-compass-download-directory "/venv/"))) (when (and (not (file-exists-p venv-dir)) (or no-query-p (y-or-n-p "Need to install code-compass python dependencies, do it now ?"))) (code-compass--in-directory code-compass-download-directory (mkdir code-compass-download-directory t) (let ((compilation-buffer (compilation-start (format "cd %s; python3 -m venv venv && ./venv/bin/pip3 install -r ../requirements.txt" code-compass-download-directory)))) (if (get-buffer-window compilation-buffer) (select-window (get-buffer-window compilation-buffer)) (pop-to-buffer compilation-buffer)) ))))) ;;;###autoload (defun code-compass-doctor () "Report if and what dependencies are missing." (interactive) (let ((git-p (executable-find "git")) (python-p (executable-find "python3")) (python-venv-p (file-exists-p (file-name-concat code-compass-download-directory "/venv/"))) (java-p (executable-find "java")) (graph-cli-p (file-exists-p (file-name-concat code-compass-download-directory "/venv/bin/graph"))) (cloc-p (executable-find "cloc")) (gource-p (executable-find "gource")) (docker-p (executable-find "docker")) (doctor-buffer (get-buffer-create "code-compass dependencies check"))) (with-current-buffer doctor-buffer (read-only-mode -1) (erase-buffer) (insert "Welcome to Code Compass doctor!\n\n") (insert "Required dependencies for minimal functionality:\n") (insert (format "- Git: %s\n" (if git-p "OK" "MISSING"))) (insert (format "- Python: %s\n" (if python-p "OK" "MISSING"))) (insert (format "- Python venv: %s\n" (if python-venv-p "OK" "MISSING"))) (insert (format "- Java: %s\n" (if java-p "OK" "MISSING"))) (insert (format "- Cloc: %s\n" (if cloc-p "OK" "MISSING"))) (insert "\n\nOptional dependencies:\n") (insert (format "- Graph-cli: %s\n" (if graph-cli-p "OK" "MISSING"))) (insert (format "- Gource: %s\n" (if gource-p "OK" "MISSING"))) (insert (format "- Docker: %s\n" (if docker-p "OK" "MISSING"))) (read-only-mode)) (switch-to-buffer-other-window doctor-buffer))) (define-obsolete-function-alias 'c/doctor #'code-compass-doctor "0.1.2") (defun code-compass--subtract-to-now (n month|day &optional time) "Subtract N * MONTH|DAY to current time. Optionally give TIME from which to start." (time-subtract (or time (current-time)) (seconds-to-time (* 60 60 month|day n)))) (defun code-compass-request-date (days|months &optional time) "Request date in days or months by asking how many DAYS|MONTHS ago. Optionally give TIME from which to start. >> (code-compass-request-date \"1d\" '(25610 2072 776840 400000)) => \"2023-03-08\" >> (code-compass-request-date \"1m\" '(25610 2072 776840 400000)) => \"2023-02-06\"" (interactive (list (completing-read "From how long ago? " code-compass-default-periods))) (when (not (string= days|months "beginning")) (format-time-string "%F" (apply #'code-compass--subtract-to-now (-concat (if (s-contains-p "m" days|months) (list (string-to-number (s-replace "m" "" days|months)) (* 24 31)) (list (string-to-number (s-replace "d" "" days|months)) 24)) (list time)))))) (define-obsolete-function-alias 'c/request-date #'code-compass-request-date "0.1.2") (defun code-compass--first (l) "Get first element of L." (car l)) (defun code-compass--second (l) "Get second element of L." (nth 1 l)) (defun code-compass--third (l) "Get third element of L." (nth 2 l)) (defun code-compass--filename (file) "Get filename of FILE. >> (code-compass--filename \"some/file.txt\") => \"file.txt\"" (file-name-nondirectory (directory-file-name file))) (defun code-compass--temp-dir (repository) "Format temporary directory in which store analyses assets for REPOSITORY. >> (code-compass--temp-dir \"~/some-repo/\") => \"/tmp/code-compass-some-repo/\"" (format "%s/code-compass-%s/" code-compass-tmp-directory (code-compass--filename repository))) (defmacro code-compass--in-directory (directory &rest body) "Execute BODY in DIRECTORY. Temporarily changes current buffer's default directory to DIRECTORY." (declare (indent defun)) `(let ((default-directory ,directory)) (unwind-protect ,@body))) (defmacro code-compass--in-temp-directory (repository &rest body) "Execute BODY in temporary directory created for analysed REPOSITORY." (declare (indent defun)) `(progn (mkdir (code-compass--temp-dir ,repository) t) (code-compass--in-directory (code-compass--temp-dir ,repository) ,@body))) (defun code-compass--shell-command-error-handler (command buffer-name) "Run COMMAND with `shell-command' but check if errors are output in BUFFER-NAME." (ignore-errors (kill-buffer buffer-name)) (shell-command command nil (get-buffer-create buffer-name)) (let ((contents (with-current-buffer buffer-name (buffer-string)))) (when (> (length contents) 1) (error (concat buffer-name "\n\n" contents))))) (defun code-compass-produce-git-report (repository date &optional before-date authors) "Create git report for REPOSITORY with a Git log starting at DATE. Define optionally a BEFORE-DATE. The knowledge analysis allow to filter by AUTHORS when set." (interactive (list (call-interactively #'code-compass-request-date))) (message "Producing git report...") (let ((git-command (s-concat (format "git -C %s" repository) " log --all --numstat --date=short --pretty=format:'--%h--%ad--%aN' --no-renames " (when authors (format "--perl-regexp --author='%s' " authors)) (when date (format "--after=%s " date)) (when before-date (format "--before=%s " before-date)) (when code-compass-exclude-directories (s-join " " (--map (format "':(exclude)%s'" it) code-compass-exclude-directories))) " > gitreport.log"))) (message "Running %s" git-command) (code-compass--shell-command-error-handler git-command "*code-compass-produce-git-report-errors*")) repository) (define-obsolete-function-alias 'c/produce-git-report #'code-compass-produce-git-report "0.1.2") (defun code-compass--run-code-maat (command repository) "Run code-maat's COMMAND on REPOSITORY." (message "Producing code-maat %s report for %s..." command repository) (let ((source-file (format "%s/code-maat-1.0.1-standalone.jar" code-compass-download-directory)) (maat-jar-p (s-contains-p "jar" code-compass-code-maat-command))) (when (and maat-jar-p (not (file-exists-p (code-compass--expand-file-name source-file)))) (mkdir code-compass-download-directory t) (url-copy-file "https://github.com/smontanari/code-forensics/raw/v3.0.0/lib/analysers/code_maat/code-maat-1.0.1-standalone.jar" (code-compass--expand-file-name source-file) t)) (code-compass--shell-command-error-handler (format "%1$s -l %4$s/code-compass-%2$s/gitreport.log -c git2 -a %3$s > %3$s.csv" code-compass-code-maat-command (code-compass--filename repository) command (if maat-jar-p code-compass-tmp-directory code-compass-docker-data-directory)) "*code-compass--run-code-maat-errors*"))) (defun code-compass--produce-code-maat-revisions-report (repository) "Create code-maat revisions report for REPOSITORY." (code-compass--run-code-maat "revisions" repository) repository) (defun code-compass--produce-cloc-report (repository) "Create cloc report for REPOSITORY. To filter specific subdirectories out of this report, edit the variable `code-compass-exclude-directories'." (let ((cloc-command (format "(cd %s; PERL_BADLANG=0 cloc ./ --timeout 0 --by-file --csv --quiet --exclude-dir=%s) > cloc.csv" repository (string-join code-compass-exclude-directories ",")))) (message (concat "Producing cloc report with " cloc-command "...")) (code-compass--shell-command-error-handler cloc-command "*code-compass--produce-cloc-report-errors*")) repository) (defun code-compass--copy-file (file-name directory) "Copy FILE-NAME to DIRECTORY." (copy-file (code-compass--expand-file-name file-name) directory t) (set-file-modes (concat directory "/" (file-name-nondirectory file-name)) (file-modes-symbolic-to-number "u=rw,go=r"))) (defun code-compass--generate-merger-script (repository) "Generate a Python script to give weights to the circle diagram of REPOSITORY." (code-compass--copy-file "./scripts/csv_as_enclosure_json.py" (code-compass--temp-dir repository)) repository) (defun code-compass--generate-d3-v3-lib (repository) "Make available the D3 library for REPOSITORY. This is just to not depend on a network connection." (mkdir "d3" t) (let ((source-file (format "%s/d3.v3.min.js" code-compass-download-directory))) (unless (file-exists-p (code-compass--expand-file-name source-file)) (mkdir code-compass-download-directory t) (url-copy-file "http://d3js.org/d3.v3.min.js" (code-compass--expand-file-name source-file) t)) (code-compass--copy-file source-file "d3/")) repository) (defun code-compass--generate-d3-v4-lib (repository) "Make available the D3 v4 library for REPOSITORY. This is just to not depend on a network connection." (mkdir "d3" t) (let ((source-file (format "%s/d3.v4.min.js" code-compass-download-directory))) (unless (file-exists-p (code-compass--expand-file-name source-file)) (mkdir code-compass-download-directory t) (url-copy-file "http://d3js.org/d3.v4.min.js" (code-compass--expand-file-name source-file) t)) (code-compass--copy-file source-file "d3/")) repository) (defun code-compass--produce-json (repository) "Produce json for REPOSITORY." (message "Produce json...") (code-compass--shell-command-error-handler (code-compass--python-script "csv_as_enclosure_json.py --structure cloc.csv --weights revisions.csv > hotspot_proto.json") "*code-compass--produce-json-errors*") repository) (defun code-compass--generate-host-enclosure-diagram-html (repository) "Generate host html from REPOSITORY." (code-compass--copy-file "./pages/enclosure-diagram/style.css" (code-compass--temp-dir repository)) (code-compass--copy-file "./pages/enclosure-diagram/script.js" (code-compass--temp-dir repository)) (code-compass--copy-file "./pages/enclosure-diagram/zoomable.html" (code-compass--temp-dir repository)) repository) (defun code-compass--navigate-to-localhost (repository &optional port) "Navigate to served directory for REPOSITORY, optionally at specified PORT." (let ((port (or port code-compass-default-port)) (browse-url-browser-function #'browse-url-generic) (browse-url-generic-program code-compass-preferred-browser)) (browse-url (format "http://localhost:%s/zoomable.html" port))) repository) (defun code-compass--run-server (repository &optional port) "Serve directory for REPOSITORY, optionally at PORT." (let ((httpd-host 'local) (httpd-port (or port code-compass-default-port))) (httpd-stop) (ignore-errors (httpd-serve-directory (code-compass--temp-dir repository)))) repository) (defun code-compass--run-server-and-navigate (repository &optional port) "Serve and navigate to REPOSITORY, optionally at PORT." (when port (code-compass--run-server repository port) (code-compass--navigate-to-localhost repository port))) (defun code-compass--async-run (command repository date &optional port do-not-serve authors) "Run asynchronously COMMAND taking a REPOSITORY and a DATE, optionally at PORT. Optional argument DO-NOT-SERVE skips serving contents on localhost. Optional argument AUTHORS to filter AUTHORS for knowledge analysis." (async-start `(lambda () (setq load-path ',load-path) (load-file ,(symbol-file command)) (setq code-compass-code-maat-command ,code-compass-code-maat-command) (setq code-compass-pie-or-bar-chart-command ,code-compass-pie-or-bar-chart-command) (setq code-compass-calculate-coupling-project-key-fn ',code-compass-calculate-coupling-project-key-fn) (setq code-compass-authors-colors ',code-compass-authors-colors) (setq code-compass-exclude-directories ',code-compass-exclude-directories) (setq code-compass-preferred-browser ,code-compass-preferred-browser) (setq code-compass-snapshot-periods ',code-compass-snapshot-periods) (setq code-compass-default-periods ',code-compass-default-periods) (setq code-compass-tmp-directory ',code-compass-tmp-directory) (setq code-compass-docker-data-directory ',code-compass-docker-data-directory) (setq code-compass-download-directory ',code-compass-download-directory) (setq code-compass-default-port ',code-compass-default-port) (let ((browse-url-browser-function #'browse-url-generic) (browse-url-generic-program ,code-compass-preferred-browser)) (condition-case err (funcall ',command ,repository ,date ',authors) (error (funcall ',command ,repository ,date))))) `(lambda (result) (when (not ,do-not-serve) (code-compass--run-server-and-navigate ,(expand-file-name repository) (or ,port code-compass-default-port)))))) ;;;###autoload (defun code-compass-show-hotspots-sync (repository date &optional port) "Show REPOSITORY enclosure diagram for hotspots starting at DATE. Optionally served at PORT." (interactive (list (read-directory-name "Choose git repository directory:" (vc-root-dir)) (call-interactively #'code-compass-request-date) code-compass-default-port)) (code-compass--in-temp-directory repository (--> repository (code-compass-produce-git-report it date) code-compass--produce-code-maat-revisions-report code-compass--produce-cloc-report code-compass--generate-merger-script code-compass--generate-d3-v3-lib code-compass--produce-json code-compass--generate-host-enclosure-diagram-html (code-compass--run-server-and-navigate it port)))) (define-obsolete-function-alias 'c/show-hotspots-sync #'code-compass-show-hotspots-sync "0.1.2") ;;;###autoload (defun code-compass-show-hotspots (repository date &optional port) "Show REPOSITORY enclosure diagram for hotspots. Starting DATE reduces scope of Git log and PORT define where the html is served." (interactive (list (read-directory-name "Choose git repository directory:" (vc-root-dir)) (call-interactively #'code-compass-request-date))) (code-compass--async-run #'code-compass-show-hotspots-sync repository date port)) (define-obsolete-function-alias 'c/show-hotspots #'code-compass-show-hotspots "0.1.2") (defun code-compass-show-hotspot-snapshot-sync (repository) "Snapshot COMMAND over REPOSITORY over the last year every three months." (interactive (list (read-directory-name "Choose git repository directory:" (vc-root-dir)))) (--each code-compass-snapshot-periods (code-compass-show-hotspots-sync repository (code-compass-request-date it) code-compass-default-port))) (define-obsolete-function-alias 'c/show-hotspot-snapshot-sync #'code-compass-show-hotspot-snapshot-sync "0.1.2") ;; BEGIN indentation (defun code-compass--split-on-newlines (code) "Split CODE over newlines." (s-split "\n" code)) (defun code-compass--remove-empty-lines (lines) "Remove empty LINES. >> (code-compass--remove-empty-lines '(\"line\" \" \" \" \" \"\")) => (\"line\")\"" (--remove (eq (length (s-trim it)) 0) lines)) (defun code-compass--remove-text-after-indentation (lines) "Remove text in LINES that is not indentation characters.. >> (code-compass--remove-text-after-indentation '(\" one indent\")) => (\" \")" (--map (apply #'string (--take-while (or (eq ?\s it) (eq ?\t it)) (string-to-list it))) lines)) (defun code-compass--find-indentation (lines-without-text) "Infer indentation level in LINES-WITHOUT-TEXT. If no indentation present in file, defaults to 2. >> (code-compass--find-indentation '(\" \" \" \" \" \")) => 3 >> (code-compass--find-indentation '(\" \")) => 1" (or (--> lines-without-text (--map (list (s-count-matches "\s" it) (s-count-matches "\t" it)) it) (let ((spaces-ind (-sort #'< (--remove (eq 0 it) (-map 'code-compass--first it)))) (tabs-ind (-sort #'< (--remove (eq 0 it) (-map 'code-compass--second it))))) (if (> (length spaces-ind) (length tabs-ind)) (code-compass--first spaces-ind) (code-compass--first tabs-ind)))) 2)) (defun code-compass--convert-tabs-to-spaces (line-without-text n) "Replace tabs in LINE-WITHOUT-TEXT with N spaces." (s-replace "\t" (make-string n ?\s) line-without-text)) (defun code-compass--calculate-complexity (line-without-text indentation) "Calculate indentation complexity. This divides length of LINE-WITHOUT-TEXT by INDENTATION. >> (code-compass--calculate-complexity \" \" 2) => 2.0" (/ (+ 0.0 (length line-without-text)) indentation)) (defun code-compass--as-logical-indents (lines &optional opts) "Calculate logical indentations of LINES. Try to infer how many space is an indent unless OPTS provides it." (let ((indentation (or opts (code-compass--find-indentation lines)))) (list (--map (--> it (code-compass--convert-tabs-to-spaces it indentation) (code-compass--calculate-complexity it indentation)) lines) indentation))) (defun code-compass--stats-from (complexities-indentation) "Return stats from COMPLEXITIES-INDENTATION." (let* ((complexities (code-compass--first complexities-indentation)) (mean (/ (-sum complexities) (length complexities))) (sd (sqrt (/ (-sum (--map (expt (- it mean) 2) complexities)) (length complexities))))) `((total . ,(-sum complexities)) (n-lines . ,(length complexities)) (max . ,(-max complexities)) (mean . ,mean) (standard-deviation . ,sd) (used-indentation . ,(code-compass--second complexities-indentation))))) (defun code-compass-calculate-complexity-stats (code &optional opts) "Return complexity of CODE based on indentation. If OPTS is provided, use these settings to define what is the indentation. Return nil for empty CODE. >> (-take 3 (code-compass-calculate-complexity-stats \"1\")) => ((total . 0.0) (n-lines . 1) (max . 0.0))" (ignore-errors (--> code ;; TODO maybe add line numbers, so that I can also open the most troublesome (max-c) line automatically? code-compass--split-on-newlines code-compass--remove-empty-lines code-compass--remove-text-after-indentation (code-compass--as-logical-indents it opts) code-compass--stats-from))) (define-obsolete-function-alias 'c/calculate-complexity-stats #'code-compass-calculate-complexity-stats "0.1.2") ;;;###autoload (defun code-compass-calculate-complexity-current-buffer (&optional indentation) "Calculate complexity of the current buffer contents. Optionally you can provide the INDENTATION level of the file. The code can infer it automatically." (interactive) (code-compass-calculate-complexity-stats (buffer-substring-no-properties (point-min) (point-max)) indentation)) (define-obsolete-function-alias 'c/calculate-complexity-current-buffer #'code-compass-calculate-complexity-current-buffer "0.1.2") ;; END indentation ;; BEGIN complexity over commits (defun code-compass--retrieve-commits-up-to-date-touching-file (file &optional date) "Retrieve list of commits touching FILE from DATE." (s-split "\n" (shell-command-to-string (s-concat "git log --format=format:%H --reverse " (if date (s-concat "--after=" date " ") "") file)))) (defun code-compass--retrieve-file-at-commit-with-git (file commit) "Retrieve FILE contents at COMMIT." (let* ((git-dir (with-current-buffer (find-file-noselect file) (expand-file-name (vc-root-dir)))) (git-file (string-remove-prefix git-dir (expand-file-name file)))) (shell-command-to-string (format "git show %s:\"%s\"" commit git-file)))) (defun code-compass--git-hash-to-date (commit) "Return the date of the COMMIT. Note this is the date of merging in, not of the code change." (s-replace "\n" "" (shell-command-to-string (s-concat "git show --no-patch --no-notes --pretty='%cd' --date=short " commit)))) (defun code-compass--calculate-complexity-over-commits (file &optional opts) "Calculate complexity of FILE over commits. Optional argument OPTS defines things like the indentation to use." (--> (call-interactively #'code-compass-request-date) (code-compass--retrieve-commits-up-to-date-touching-file file it) (--map (--> it (list it (code-compass--retrieve-file-at-commit-with-git file it)) (list (code-compass--first it) (code-compass-calculate-complexity-stats (code-compass--second it) opts))) it))) (define-obsolete-function-alias 'c/calculate-complexity-over-commits #'code-compass--calculate-complexity-over-commits "0.1.2") (defun code-compass--plot-csv-file-with-graph-cli (file) "Plot CSV FILE with graph-cli." (async-shell-command (format "%s/venv/bin/graph --xtick-angle 90 %s" code-compass-download-directory file))) (defun code-compass--plot-lines-with-graph-cli (data) "Plot DATA from lists as a graph." (let ((tmp-file (format "%s/data-file-graph-cli.csv" code-compass-tmp-directory))) (with-temp-file tmp-file (insert "commit-date,total-complexity,loc\n") (insert (s-join "\n" (--map (s-replace-all '((" " . ",") ("(" . "") (")" . "")) (format "%s" it)) data)))) (code-compass--plot-csv-file-with-graph-cli tmp-file))) ;;;###autoload (defun code-compass-show-complexity-over-commits (file &optional opts) "Make a graph plotting complexity out of a FILE. Optionally give file indentation in OPTS." (interactive (list (read-file-name "Select file:" nil nil nil (buffer-file-name)))) (code-compass--plot-lines-with-graph-cli (--map (list (code-compass--git-hash-to-date (code-compass--first it)) (alist-get 'total (code-compass--second it)) (alist-get 'n-lines (code-compass--second it))) (code-compass--calculate-complexity-over-commits file opts)))) (define-obsolete-function-alias 'c/show-complexity-over-commits #'code-compass-show-complexity-over-commits "0.1.2") ;; END complexity over commits ;; BEGIN code churn (defun code-compass--produce-code-maat-abs-churn-report (repository) "Create code-maat abs-churn report for REPOSITORY." (code-compass--run-code-maat "abs-churn" repository) repository) (defun code-compass-show-code-churn-sync (repository date) "Show how much code was added and removed from REPOSITORY from a DATE." (interactive (list (read-directory-name "Choose git repository directory:" (vc-root-dir)) (call-interactively #'code-compass-request-date))) (code-compass--in-temp-directory repository (progn (--> repository (code-compass-produce-git-report it date) code-compass--produce-code-maat-abs-churn-report) (code-compass--plot-csv-file-with-graph-cli "abs-churn.csv")))) (define-obsolete-function-alias 'c/show-code-churn-sync #'code-compass-show-code-churn-sync "0.1.2") ;;;###autoload (defun code-compass-show-code-churn (repository date) "Show how much code was added and removed from REPOSITORY from a DATE." (interactive (list (read-directory-name "Choose git repository directory:" (vc-root-dir)) (call-interactively #'code-compass-request-date))) (code-compass--async-run #'code-compass-show-code-churn-sync repository date nil 't)) (define-obsolete-function-alias 'c/show-code-churn #'code-compass-show-code-churn "0.1.2") ;; END complexity over commits ;; BEGIN change coupling (defun code-compass--produce-code-maat-coupling-report (repository) "Create code-maat coupling report for REPOSITORY." (code-compass--run-code-maat "coupling" repository) repository) (defun code-compass--generate-coupling-json-script (repository) "Generate script to produce a weighted graph for REPOSITORY." (code-compass--copy-file "./scripts/coupling_csv_as_edge_bundling.py" (code-compass--temp-dir repository)) repository) (defun code-compass--produce-coupling-json (repository) "Produce coupling json needed by d3 for REPOSITORY." (message "Produce coupling json...") (code-compass--shell-command-error-handler (code-compass--python-script "coupling_csv_as_edge_bundling.py --coupling coupling.csv > edgebundling.json") "*code-compass--produce-coupling-json-errors*") repository) (defun code-compass--generate-host-edge-bundling-html (repository) "Generate host html from REPOSITORY." (code-compass--copy-file "./pages/edge-bundling/script.js" (code-compass--temp-dir repository)) (code-compass--copy-file "./pages/edge-bundling/style.css" (code-compass--temp-dir repository)) (code-compass--copy-file "./pages/edge-bundling/zoomable.html" (code-compass--temp-dir repository)) repository) (defun code-compass-show-coupling-graph-sync (repository date &optional port) "Show REPOSITORY edge bundling synchronously for code coupling up to DATE. Serve graph on PORT." (interactive (list (read-directory-name "Choose git repository directory:" (vc-root-dir)) (call-interactively #'code-compass-request-date) 8888)) (code-compass--in-temp-directory repository (--> repository (code-compass-produce-git-report it nil date) code-compass--produce-code-maat-coupling-report code-compass--generate-coupling-json-script code-compass--generate-d3-v4-lib code-compass--produce-coupling-json code-compass--generate-host-edge-bundling-html (code-compass--run-server-and-navigate it port)))) (define-obsolete-function-alias 'c/show-coupling-graph-sync #'code-compass-show-coupling-graph-sync "0.1.2") ;;;###autoload (defun code-compass-show-coupling-graph (repository date &optional port) "Show REPOSITORY edge bundling for code coupling up to DATE. Serve graph on PORT." (interactive (list (read-directory-name "Choose git repository directory:" (vc-root-dir)) (call-interactively #'code-compass-request-date))) (code-compass--async-run #'code-compass-show-coupling-graph-sync repository date port)) (define-obsolete-function-alias 'c/show-coupling-graph #'code-compass-show-coupling-graph "0.1.2") ;; END change coupling ;; BEGIN find coupled files (defun code-compass--add-filename-to-analysis-columns (repository analysis) "Add filepath from REPOSITORY to ANALYSIS columns." (--> analysis (s-split "\n" it 't) ;(--remove (s-blank? (s-trim it)) it) (-concat (list (car it)) (--map (--> (s-split "," it) (-concat (list (s-concat repository "/" (code-compass--first it))) (list (if (or (null (code-compass--second it)) (not (s-contains-p "/" (code-compass--second it)))) (code-compass--second it) (s-concat repository "/" (code-compass--second it)))) (cdr (cdr it))) (s-join "," it)) (cdr it))))) (defun code-compass--get-coupling-alist-sync (repository) "Get list of coupled files in REPOSITORY async." (code-compass--in-temp-directory repository (--> repository (code-compass-produce-git-report it nil) code-compass--produce-code-maat-coupling-report) (--> (code-compass--get-analysis-as-string-from-csv "coupling") (code-compass--add-filename-to-analysis-columns repository it) (--map (s-split "," it) (cdr it))))) (defun code-compass--get-coupling-alist (repository fun) "FUN takes a list of coupled files in REPOSITORY." (async-start `(lambda () (setq load-path ',load-path) (load-file ,(symbol-file 'code-compass--get-coupling-alist)) (code-compass--get-coupling-alist-sync ,repository)) fun)) (defvar code-compass-coupling-project-map (make-hash-table :test 'equal) "Hash table to contain coupling files list.") (defun code-compass--get-coupled-files-alist (repository fun) "Run FUN on the coupled files for REPOSITORY." (let* ((key (funcall code-compass-calculate-coupling-project-key-fn repository)) (code-compass-files (gethash key code-compass-coupling-project-map))) (if code-compass-files (funcall fun code-compass-files) (message "Building coupling cache asynchronously...") (code-compass--get-coupling-alist repository `(lambda (result-files) (message "Coupling Cache Built") (puthash ,key result-files code-compass-coupling-project-map) (funcall ,fun result-files) ;; Save cache to local storage to access it faster next time if nothing has changed (with-temp-file ,code-compass-cache-file (prin1 code-compass-coupling-project-map (current-buffer)))))))) (defun code-compass-clear-coupling-project-map () "Clear `code-compass-coupling-project-map' and deletes cache file." (interactive) (clrhash code-compass-coupling-project-map) (delete-file code-compass-cache-file)) (define-obsolete-function-alias 'c/clear-coupling-project-map #'code-compass-clear-coupling-project-map "0.1.2") (defun code-compass-get-coupled-files-alist-hook-fn () "Calculate coupled files asynchronously." (let ((git-root (ignore-errors (vc-root-dir)))) (when git-root (code-compass--get-coupled-files-alist git-root `(lambda (x) (message "Finished to update coupled files for %s and found %s coupled files." ,git-root (length x))))))) (define-obsolete-function-alias 'c/get-coupled-files-alist-hook-fn #'code-compass-get-coupled-files-alist-hook-fn "0.1.2") (defun code-compass--coupling-completions (file-name coupled-files root) "Get a list of files coupled to FILE-NAME. The coupling information is provided by COUPLED-FILES. ROOT is the VCS project path. >> (code-compass--coupling-completions \"\" nil \"\") => nil >> (code-compass--coupling-completions (concat code-compass-path-to-code-compass \"code-compass.el\") (list (list (concat code-compass-path-to-code-compass \"/README.org\") \"code-compass.el\" 31 65)) code-compass-path-to-code-compass) => (\"README.org\")" (let ((default-directory root) (root (s-chop-suffixes '("/" "/" "/") root))) (--> coupled-files (--sort (> (string-to-number (nth 3 it)) (string-to-number (nth 3 other))) it) ;; sort by number of commits (--sort (> (string-to-number (nth 2 it)) (string-to-number (nth 2 other))) it) ;; sort then by how often this file has changed (-keep (lambda (file) (let ((src-coupled-file-name (expand-file-name (car file))) (target-coupled-file-name-src (expand-file-name (nth 1 file))) (file-name (expand-file-name file-name))) (when (and (file-exists-p src-coupled-file-name) (file-exists-p target-coupled-file-name-src) (or (string= file-name src-coupled-file-name) (string= file-name target-coupled-file-name-src))) (s-replace ; this replace is just removing the root prefix, so the completions are human readable (concat root "/") "" (expand-file-name (car ;; this picks only the coupled files, ignoring the file we are matching against (file-name) (--remove (string= (expand-file-name file-name) (expand-file-name it)) (-take 2 file)))))))) it)))) (defun code-compass--show-coupled-files (files file-name) "Gather coupled files to FILE-NAME from all FILES." (let* ((root (ignore-errors (car (s-split "//" (caar files))))) (completions (ignore-errors (-non-nil (code-compass--coupling-completions file-name files (expand-file-name root)))))) (if completions (let ((open-file (completing-read "Find coupled file: " completions nil 't))) (find-file (concat root "/" open-file))) (error "No coupled file found!")))) ;;;###autoload (defun code-compass-find-coupled-files () "Allow user to choose files coupled according to previous modifications." (interactive) (when (file-exists-p code-compass-cache-file) (with-temp-buffer (insert-file-contents code-compass-cache-file) (goto-char (point-min)) (set 'code-compass-coupling-project-map (read (current-buffer))))) (code-compass--get-coupled-files-alist (vc-root-dir) `(lambda (files) (code-compass--show-coupled-files files ,(buffer-file-name))))) (define-obsolete-function-alias 'c/find-coupled-files #'code-compass-find-coupled-files "0.1.2") ;; END find coupled files ;; BEGIN code communication (defun code-compass--produce-code-maat-communication-report (repository) "Create code-maat communication report for REPOSITORY." (code-compass--run-code-maat "communication" repository) repository) (defun code-compass--generate-communication-json-script (repository) "Generate script to produce a weighted graph for REPOSITORY." (code-compass--copy-file "./scripts/communication_csv_as_edge_bundling.py" (code-compass--temp-dir repository)) repository) (defun code-compass--produce-communication-json (repository) "Generate REPOSITORY age json." (message "Produce age json...") (code-compass--shell-command-error-handler (code-compass--python-script "communication_csv_as_edge_bundling.py --communication communication.csv > edgebundling.json") "*code-compass--produce-communication-json-errors*") repository) (defun code-compass-show-code-communication-sync (repository date &optional port) "Show REPOSITORY edge bundling for code communication from DATE. Green edges is incoming (dependant) and red outgoing (dependencies). Optionally set the PORT on which to serve the graph." (interactive (list (read-directory-name "Choose git repository directory:" (vc-root-dir)) (call-interactively #'code-compass-request-date) 8888)) (code-compass--in-temp-directory repository (--> repository (code-compass-produce-git-report it date) code-compass--produce-code-maat-communication-report code-compass--generate-communication-json-script code-compass--generate-d3-v4-lib code-compass--produce-communication-json code-compass--generate-host-edge-bundling-html (code-compass--run-server-and-navigate it port)))) (define-obsolete-function-alias 'c/show-code-communication-sync #'code-compass-show-code-communication-sync "0.1.2") ;;;###autoload (defun code-compass-show-code-communication (repository date &optional port) "Show REPOSITORY edge bundling for code communication from DATE. Optionally define PORT on which to serve graph." (interactive (list (read-directory-name "Choose git repository directory:" (vc-root-dir)) (call-interactively #'code-compass-request-date))) (code-compass--async-run #'code-compass-show-code-communication-sync repository date port)) (define-obsolete-function-alias 'c/show-code-communication #'code-compass-show-code-communication "0.1.2") ;; END code communication ;; BEGIN code knowledge (defun code-compass--produce-code-maat-main-dev-report (repository) "Create code-maat main-dev report for REPOSITORY." (code-compass--run-code-maat "main-dev" repository) repository) (defun code-compass--generate-knowledge-json-script (repository) "Generate python script. Argument REPOSITORY defines for which repo to run this." (code-compass--copy-file "./scripts/knowledge_csv_as_enclosure_diagram.py" (code-compass--temp-dir repository)) repository) (defun code-compass--produce-knowledge-json (repository) "Generate REPOSITORY age json." (message "Produce knowledge json...") (code-compass--shell-command-error-handler (code-compass--python-script "knowledge_csv_as_enclosure_diagram.py --structure cloc.csv --owners main-dev.csv --authors authors.csv > knowledge.json") "*code-compass--produce-knowledge-json-errors*") repository) (defun code-compass--insert-authors-colors-in-file (authors-colors) "Insert a csv of AUTHORS-COLORS in the temporary asset directory for REPOSITORY." (with-temp-file "authors.csv" (insert "author,color\n") (apply #'insert (--map (s-concat (car it) "," (cdr it) "\n") authors-colors)))) (defun code-compass--get-authors (repository) "Retrieve authors in REPOSITORY." (--> (s-concat "cd " repository "; git shortlog HEAD -s -n | uniq | cut -f 2") shell-command-to-string (s-split "\n" it) (--remove (s-blank? (s-trim it)) it))) (defun code-compass--generate-list-authors-colors (repository) "Generate list of authors of REPOSITORY." (--> (code-compass--get-authors repository) (-zip-pair it code-compass-authors-colors) (code-compass--insert-authors-colors-in-file it)) repository) (defun code-compass--generate-host-knowledge-enclosure-diagram-html (repository) "Generate host html from REPOSITORY." (code-compass--copy-file "./pages/knowledge-enclosure-diagram/script.js" (code-compass--temp-dir repository)) (code-compass--copy-file "./pages/knowledge-enclosure-diagram/style.css" (code-compass--temp-dir repository)) (code-compass--copy-file "./pages/knowledge-enclosure-diagram/zoomable.html" (code-compass--temp-dir repository)) repository) (defun code-compass-show-knowledge-graph-sync (repository date authors &optional port) "Show REPOSITORY enclosure diagram for code knowledge. Filter by DATE and AUTHORS. Optionally define PORT on which to serve graph." (interactive (let ((repository (read-directory-name "Choose git repository directory:" (vc-root-dir)))) (list repository (call-interactively #'code-compass-request-date) (completing-read-multiple "Filter by authors (TAB-completion) or leave empty for all: " (code-compass--get-authors repository)) 8888))) (code-compass--in-temp-directory repository (--> repository (code-compass-produce-git-report it date nil (if (> (length authors) 1) (s-concat "(" (s-join "|" authors) ")") authors)) code-compass--produce-code-maat-main-dev-report code-compass--produce-cloc-report code-compass--generate-knowledge-json-script code-compass--generate-d3-v3-lib code-compass--generate-list-authors-colors code-compass--produce-knowledge-json code-compass--generate-host-knowledge-enclosure-diagram-html (code-compass--run-server-and-navigate it port)))) (define-obsolete-function-alias 'c/show-knowledge-graph-sync #'code-compass-show-knowledge-graph-sync "0.1.2") ;;;###autoload (defun code-compass-show-knowledge-graph (repository date &optional authors port) "Show REPOSITORY enclosure diagram for code knowledge. Filter by DATE and AUTHORS. Optionally define PORT on which to serve graph." (interactive (let ((repository (read-directory-name "Choose git repository directory:" (vc-root-dir)))) (list repository (call-interactively #'code-compass-request-date) (completing-read-multiple "Filter by authors (TAB-completion) or leave empty for all: " (code-compass--get-authors repository)) 8888))) (code-compass--async-run #'code-compass-show-knowledge-graph-sync repository date port nil authors)) (define-obsolete-function-alias 'c/show-knowledge-graph #'code-compass-show-knowledge-graph "0.1.2") ;; END code knowledge ;; BEGIN code refactoring (defun code-compass--produce-code-maat-refactoring-main-dev-report (repository) "Create code-maat refactoring-main-dev report for REPOSITORY." (code-compass--run-code-maat "refactoring-main-dev" repository) repository) (defun code-compass--generate-refactoring-json-script (repository) "Generate python script for REPOSITORY." (code-compass--copy-file "./scripts/refactoring_csv_as_enclosure_diagram.py" (code-compass--temp-dir repository)) repository) (defun code-compass--produce-refactoring-json (repository) "Generate REPOSITORY age json." (message "Produce refactoring json...") (code-compass--shell-command-error-handler (code-compass--python-script "refactoring_csv_as_enclosure_diagram.py --structure cloc.csv --owners refactoring-main-dev.csv --authors authors.csv > knowledge.json") ; TODO should be refactoring.json, but leaving knowledge.json for code reuse "*code-compass--produce-refactoring-json-errors*") repository) (defun code-compass-show-refactoring-graph-sync (repository date &optional port) "Show REPOSITORY enclosure diagram for code knowledge up to DATE. Optionally define PORT on which to serve graph." (interactive (list (read-directory-name "Choose git repository directory:" (vc-root-dir)) (call-interactively #'code-compass-request-date) 8888)) (code-compass--in-temp-directory repository (--> repository (code-compass-produce-git-report it date) code-compass--produce-code-maat-refactoring-main-dev-report code-compass--produce-cloc-report code-compass--generate-refactoring-json-script ;; added,total-added, vs removed,total-removed code-compass--generate-d3-v3-lib code-compass--generate-list-authors-colors code-compass--produce-refactoring-json code-compass--generate-host-knowledge-enclosure-diagram-html (code-compass--run-server-and-navigate it port)))) (define-obsolete-function-alias 'c/show-refactoring-graph-sync #'code-compass-show-refactoring-graph-sync "0.1.2") ;;;###autoload (defun code-compass-show-refactoring-graph (repository date &optional port) "Show REPOSITORY enclosure diagram for code refactoring. Filter by DATE. Optionally define PORT on which to serve graph." (interactive (list (read-directory-name "Choose git repository directory:" (vc-root-dir)) (call-interactively #'code-compass-request-date))) (code-compass--async-run #'code-compass-show-refactoring-graph-sync repository date port)) (define-obsolete-function-alias 'c/show-refactoring-graph #'code-compass-show-refactoring-graph "0.1.2") ;; END code refactoring ;; BEGIN code stability (defun code-compass-produce-code-maat-age-report (repository) "Create code-maat age report for REPOSITORY." (code-compass--run-code-maat "age" repository) repository) (defun code-compass--generate-age-json-script (repository) "Generate python script for REPOSITORY." (code-compass--copy-file "./scripts/code_age_csv_as_enclosure_json.py" (code-compass--temp-dir repository)) repository) (defun code-compass--produce-age-json (repository) "Generate REPOSITORY age json." (message "Produce age json...") (code-compass--shell-command-error-handler (code-compass--python-script "code_age_csv_as_enclosure_json.py --structure cloc.csv --weights age.csv > age.json") "*code-compass--produce-age-json-errors*") repository) (defun code-compass--generate-host-age-enclosure-diagram-html (repository) "Generate host html from REPOSITORY." (code-compass--copy-file "./pages/age-enclosure-diagram/script.js" (code-compass--temp-dir repository)) (code-compass--copy-file "./pages/age-enclosure-diagram/style.css" (code-compass--temp-dir repository)) (code-compass--copy-file "./pages/age-enclosure-diagram/zoomable.html" (code-compass--temp-dir repository)) repository) (defun code-compass-show-code-age-sync (repository date &optional port) "Show REPOSITORY enclosure diagram for code stability/age. Filter by DATE. Optionally define PORT on which to serve graph." (interactive (list (read-directory-name "Choose git repository directory:" (vc-root-dir)) (call-interactively #'code-compass-request-date) 8888)) (code-compass--in-temp-directory repository (--> repository (code-compass-produce-git-report it date) code-compass-produce-code-maat-age-report code-compass--produce-cloc-report code-compass--generate-age-json-script code-compass--generate-d3-v3-lib code-compass--produce-age-json code-compass--generate-host-age-enclosure-diagram-html (code-compass--run-server-and-navigate it port)))) (define-obsolete-function-alias 'c/show-code-age-sync #'code-compass-show-code-age-sync "0.1.2") ;;;###autoload (defun code-compass-show-stability-graph (repository date &optional port) "Show REPOSITORY enclosure diagram for code stability. Filter by DATE. Optionally define PORT on which to serve graph." (interactive (list (read-directory-name "Choose git repository directory:" (vc-root-dir)) (call-interactively #'code-compass-request-date))) (code-compass--async-run #'code-compass-show-code-age-sync repository date port)) (define-obsolete-function-alias 'c/show-stability-graph #'code-compass-show-stability-graph "0.1.2") ;; END code stability ;; BEGIN code fragmentation (defun code-compass--produce-code-maat-entity-ownership-report (repository) "Create code-maat entity-ownership report for REPOSITORY." (code-compass--run-code-maat "entity-ownership" repository) repository) (defun code-compass--slurp (file) "Get string from FILE contents." (with-temp-buffer (insert-file-contents-literally file) (buffer-substring-no-properties (point-min) (point-max)))) (defun code-compass--get-analysis-as-string-from-csv (analysis) "Get ANALYSIS in csv as text." (code-compass--slurp (s-concat analysis ".csv"))) (defun code-compass--generate-pie-script (repository) "Generate python script for REPOSITORY." (code-compass--copy-file "./scripts/csv-to-pie-graph.py" (code-compass--temp-dir repository)) repository) (defun code-compass--show-pie-chart-command (file) "Show pie chart of CSV FILE." (format code-compass-pie-or-bar-chart-command file)) (defun code-compass--sum-by-first-column (rows) "Utility to sum ROWS by first column. >> (code-compass--sum-by-first-column '((a . 1) (a . 2))) => ((a . 3))" (let (result) (dolist (row rows) (let* ((key (car row)) (value (cdr row)) (mapping (assoc key result))) (if mapping (setcdr mapping (+ (cdr mapping) value)) (push (cons key value) result)))) result)) (defun code-compass-show-fragmentation-sync (path &optional date) "Show knowledge fragmentation for PATH. Optional argument DATE to reduce time window." (interactive "fShow fragmentation for:") (let* ((path (file-truename path)) (repository (s-trim (shell-command-to-string (format "cd %s; git rev-parse --show-toplevel" (file-name-directory path)))))) (code-compass--in-temp-directory repository (--> repository (code-compass-produce-git-report it date) code-compass--produce-code-maat-entity-ownership-report code-compass--generate-pie-script) (--> (code-compass--get-analysis-as-string-from-csv "entity-ownership") (code-compass--add-filename-to-analysis-columns repository it) (--filter (s-starts-with-p path it) it) (--map (--> (s-split "," it) (cons (nth 1 it) (+ (string-to-number (nth 2 it)) (string-to-number (nth 3 it))))) it) (code-compass--sum-by-first-column it) (--map (--> it (format "%s,%s\n" (car it) (cdr it))) it) (cons "author,+&-lines\n" it) (with-temp-file "fragmentation.csv" (apply #'insert it))) (code-compass--shell-command-error-handler (code-compass--show-pie-chart-command "fragmentation.csv") "*code-compass-show-fragmentation-sync-errors*")))) (define-obsolete-function-alias 'c/show-fragmentation-sync #'code-compass-show-fragmentation-sync "0.1.2") ;;;###autoload (defun code-compass-show-fragmentation (path) "Show knowledge fragmentation for PATH." (interactive "fShow fragmentation for:") (code-compass--async-run #'code-compass-show-fragmentation-sync path nil nil 't)) (define-obsolete-function-alias 'c/show-fragmentation #'code-compass-show-fragmentation "0.1.2") ;; END code fragmentation ;; BEGIN word analysis ;; taken from: https://emacs.stackexchange.com/questions/13514/how-to-obtain-the-statistic-of-the-the-frequency-of-words-in-a-buffer (defvar code-compass-punctuation-marks '("," "." "'" "&" "\"") "List of Punctuation Marks that you want to count.") (defun code-compass--count-raw-word-list (raw-word-list) "Produce a dictionary of RAW-WORD-LIST. This contains the number of occurrences for each word." (--> raw-word-list (--reduce-from (progn (cl-incf (cdr (or (assoc it acc) (code-compass--first (push (cons it 0) acc))))) acc) nil it) (sort it (lambda (a b) (string< (car a) (car b)))))) (defun code-compass--word-stats (string) "Return word (as a token between spaces) frequency in STRING." (let* ((words (split-string (downcase string) (format "[ %s\f\t\n\r\v]+" (mapconcat #'identity code-compass-punctuation-marks "")) t)) (punctuation-marks (--filter (member it code-compass-punctuation-marks) (split-string string "" t))) (raw-word-list (append punctuation-marks words)) (word-list (code-compass--count-raw-word-list raw-word-list))) (sort word-list (lambda (a b) (> (cdr a) (cdr b)))))) (defun code-compass--word-stats-to-csv-string (string &optional order-fn) "Produce occurrences csv table for words in STRING. Optionally sorting the table according to ORDER-FN." (--> string code-compass--word-stats (--filter (> (length (car it)) 2) it) (sort it (or order-fn (lambda (a b) (> (cdr a) (cdr b))))) (--map (format "'%s',%d\n" (car it) (cdr it)) it) (apply #'s-concat it) (s-concat "word,occurences\n\n" it))) ;;;###autoload (defun code-compass-word-statistics (string &optional order-fn) "Produce a buffer with word statistics from STRING. Optionally define ORDER-FN \(for example to see the ones appearing less first\)." (interactive (list (buffer-substring-no-properties (point-min) (point-max)))) (with-current-buffer (get-buffer-create "*word-statistics*") (erase-buffer) (insert (code-compass--word-stats-to-csv-string string order-fn))) (pop-to-buffer "*word-statistics*") (goto-char (point-min))) (define-obsolete-function-alias 'c/word-statistics #'code-compass-word-statistics "0.1.2") ;;;###autoload (defun code-compass-word-semantics (string) "Produce a buffer with the words least used. This could contain the most semantically relevant from STRING." (interactive (list (buffer-substring-no-properties (point-min) (point-max)))) (code-compass-word-statistics string (lambda (a b) (< (cdr a) (cdr b))))) (define-obsolete-function-alias 'c/word-semantics #'code-compass-word-semantics "0.1.2") ;;;###autoload (defun code-compass-word-analysis-commits (arg) "Show the frequency of words used in commits messages. When ARG is set show only history for given file." (interactive "P") (--> (shell-command-to-string (s-concat "git log --pretty=format:\"%s\"" (when arg (format " %s" (read-file-name "Analyze history of:"))))) code-compass-word-statistics)) (define-obsolete-function-alias 'c/word-analysis-commits #'code-compass-word-analysis-commits "0.1.2") ;;;###autoload (defun code-compass-word-analysis-region () "Show the frequency of words in a region." (interactive) (when (region-active-p) (--> (buffer-substring-no-properties (region-beginning) (region-end)) code-compass-word-statistics))) (define-obsolete-function-alias 'c/word-analysis-region #'code-compass-word-analysis-region "0.1.2") ;;;###autoload (defun code-compass-word-analysis-region-graph () "Show the frequency graph for words in region." (interactive) (when (region-active-p) (--> (buffer-substring-no-properties (region-beginning) (region-end)) code-compass--word-stats-to-csv-string (with-temp-file (format "%s/word-stats.csv" code-compass-tmp-directory) (insert it))) (shell-command (format "graph --bar --xtick-angle 90 %s/word-stats.csv" code-compass-tmp-directory)))) (define-obsolete-function-alias 'c/word-analysis-region-graph #'code-compass-word-analysis-region-graph "0.1.2") ;; END word analysis ;; BEGIN churn icon (defun code-compass--calculate-added-delete-lines (file n-weeks-ago) "Calculate added and deleted lines for FILE from N-WEEKS-AGO." (--> "git log --since \"%s weeks ago\" --numstat --oneline %s " (format it n-weeks-ago file) (shell-command-to-string it) (s-split "\n" it) (--map (s-split "\t" it) it) (--filter (> (length it) 2) it) (--reduce-from (list :additions (+ (string-to-number (nth 0 it)) (plist-get acc :additions)) :deletions (+ (string-to-number (nth 1 it)) (plist-get acc :deletions))) (list :additions 0 :deletions 0) it))) (defun code-compass--async-start (start-func &optional finish-func) "Call `async-start' with START-FUNC and FINISH-FUNC." (async-start `(lambda () (setq load-path ',load-path) (load-file ,(symbol-file 'code-compass--async-start)) (funcall ,start-func)) finish-func)) (defun code-compass--display-icon () "Display icon for buffer according to the previous history." (when (and code-compass-display-icon (vc-root-dir)) (let ((current-buffer (current-buffer)) (current-file (buffer-file-name))) (code-compass--async-start `(lambda () (let* ((additions-deletions (code-compass--calculate-added-delete-lines ,current-file (plist-get ',code-compass-icon-trends :period))) (additions (plist-get additions-deletions :additions)) (deletions (plist-get additions-deletions :deletions)) (icon-key (cond ((eq additions 0) :always-deletions) ((eq deletions 0) :always-additions) ((> additions deletions) :more-additions) ('otherwise :more-deletions)))) (plist-get ',code-compass-icon-trends icon-key))) `(lambda (icon) (with-current-buffer ,current-buffer (code-compass--remove-icon) (setq-local mode-line-format (cons `(:eval ,icon) mode-line-format)))))))) (defun code-compass--remove-icon () "Remove icon." (setq-local mode-line-format (--remove (-contains-p (--remove (symbolp it) code-compass-icon-trends) (plist-get it :eval)) mode-line-format))) (defun code-compass--display-icon-delayed () "Display icon function for `prog-mode-hook'." (run-with-timer 0.1 nil 'code-compass--display-icon)) (defun code-compass-toggle-churn-status-icon () "Enable churn status icon." (interactive) (if (-contains-p prog-mode-hook #'code-compass--display-icon-delayed) (remove-hook 'prog-mode-hook #'code-compass--display-icon-delayed) (add-hook 'prog-mode-hook #'code-compass--display-icon-delayed))) ;; END churn icon ;; BEGIN wrapper gource ;;;###autoload (defun code-compass-show-gource (repository date) "Open gource for REPOSITORY from DATE." (interactive (list (read-directory-name "Choose git repository directory:" (vc-root-dir)) (call-interactively #'code-compass-request-date))) (if (executable-find code-compass-gource-command) (async-shell-command (s-concat (format "cd %s; %s -seconds-per-day %s" repository code-compass-gource-command code-compass-gource-seconds-per-day) (when date (format " --start-date %s" date)))) (message "Sorry, cannot find executable (%s). Try change the value of `code-compass-gource-command'" code-compass-gource-command))) (define-obsolete-function-alias 'c/show-gource #'code-compass-show-gource "0.1.2") ;; END wrapper gource ;; BEGIN create todos for a coupled files (defun code-compass--get-matching-coupled-files (files &optional file) "Get coupled FILES that match FILE or current buffer's file." (let ((coupled-file (file-truename (or file (buffer-file-name))))) (--> files (--sort (> (string-to-number (nth 3 it)) (string-to-number (nth 3 other))) it) ;; sort by number of commits (--sort (> (string-to-number (nth 2 it)) (string-to-number (nth 2 other))) it) ;; sort then by how often this file has changed (-map (lambda (file) (when (or (string= coupled-file (file-truename (car file))) (string= coupled-file (file-truename (nth 1 file)))) (car (--remove (string= (buffer-file-name) it) (-take 2 file))))) it) (-remove 'null it)))) (defun code-compass--show-todo-buffer (files file) "Show a `org-mode' buffer for FILE with the left FILES to modify." (let ((buffer (get-buffer-create (concat (file-name-base file) "-todos")))) (switch-to-buffer buffer) (erase-buffer) (org-mode) (insert "* Files you need to modify after " (file-name-base file) ":\n") (let* ((modified-files (--filter (-contains-p (s-split "\n" (shell-command-to-string "git diff --name-only HEAD")) (file-name-nondirectory it)) files)) (files-to-modify (-difference files modified-files))) (--each files-to-modify (insert (format "** TODO [[%s][%s]]\n" it (file-name-base it)))) (--each modified-files (insert (format "** DONE [[%s][%s]]\n" it (file-name-base it))))) buffer)) ;;;###autoload (defun code-compass-create-todos-from-coupled-files (&optional file) "Allow user to choose a coupled file to FILE or the current buffer's file." (interactive) (let ((create-todos (lambda (files file) (--> (code-compass--get-matching-coupled-files files file) (if (null it) (message "Nothing left todo for this file in this commit!") (code-compass--show-todo-buffer it file)))))) (code-compass--get-coupled-files-alist (vc-root-dir) `(lambda (files) (funcall ,create-todos files ,(or file (file-truename (or file (buffer-file-name))))))))) (define-obsolete-function-alias 'c/create-todos-from-coupled-files #'code-compass-create-todos-from-coupled-files "0.1.2") ;; END create todos for a coupled files ;; BEGIN EXPERIMENTAL slack support (defun code-compass--get-main-contributor-email (&optional file) "Find email of main contributor of buffer, or FILE." (--> (or file (buffer-file-name)) (file-name-nondirectory it) (s-concat "./" it) (format "git shortlog HEAD -n -sne -- %s" it) (shell-command-to-string it) (s-split "\n" it) car ;; only the first contributor (s-split "<" it) (nth 1 it) (s-split ">" it) (nth 0 it))) (defun code-compass--open-slack-from-email (email) "Open slack chat from EMAIL." (when (and (fboundp 'slack) slack-current-team) (slack-buffer-display-im (slack-create-user-profile-buffer slack-current-team (plist-get ;; TODO fall back to manual choice if the mail cannot be found? (--find (string= email (plist-get (plist-get it :profile) :email)) (slack-team-users slack-current-team)) :id))))) ;;;###autoload (defun code-compass-slack-main-contributor () "Open slack chat with main contributor of file." (interactive) ;; Allow slack only if user has it installed, and has set a current team (if (and (fboundp 'slack) slack-current-team) (code-compass--open-slack-from-email (code-compass--get-main-contributor-email)) (message "Sorry, setup your emacs-slack to use this function. See https://github.com/yuya373/emacs-slack."))) (define-obsolete-function-alias 'c/slack-main-contributor #'code-compass-slack-main-contributor "0.1.2") ;; END EXPERIMENTAL slack support ;; BEGIN Hotspots for microservices (defun code-compass--get-repositories-from-file (file) "Extract the list the cluster list of directories. We run `code-compass-show-hotspot-cluster-sync' from FILE." (when (file-exists-p file) (with-temp-buffer (insert-file-contents-literally file) (--> (buffer-substring-no-properties (point-min) (point-max)) (s-split "\n" it) (--map (s-concat (file-name-directory file) "/" it) it) (--filter (and (file-directory-p it) (file-directory-p (concat it "/.git"))) it))))) (defun code-compass--directory-git-p (directory) "Check if DIRECTORY is a Git repository." (and (file-directory-p directory) (file-directory-p (concat directory "/.git")))) (defun code-compass--add-prepended-reports (directory) "Prepend DIRECTORY to gitreport and revisions." (copy-file "gitreport.log" (format "%s-gitreport.log" (code-compass--filename directory)) 't) (copy-file "revisions.csv" (format "%s-revisions.csv" (code-compass--filename directory)) 't) directory) (defun code-compass-show-hotspot-cluster-sync (repository date &optional port) "Show hotspot analysis for repositories in DIRECTORY. Filter by DATE. If a file `repos-cluster.txt' exists with a list of repositories in the current REPOSITORY, this has priority over DIRECTORY." (interactive (list (read-directory-name "Choose repositories directory:" ".") (call-interactively #'code-compass-request-date) 8888)) (let* ((filepath (s-concat repository "/repos-cluster.txt")) (directories (or (code-compass--get-repositories-from-file filepath) (-filter #'code-compass--directory-git-p (--remove (or (s-ends-with? "/." it) (s-ends-with? "/.." it)) (directory-files repository 't))))) (no-prefix-revisions-fn (lambda (repo) (code-compass--produce-code-maat-revisions-report repository) repo))) (message "Used directories: %s" directories) (code-compass--in-temp-directory repository (code-compass--produce-cloc-report repository) (--each directories (--> it (code-compass-produce-git-report it date) (funcall no-prefix-revisions-fn it) code-compass--add-prepended-reports ;; codemaat: prepend "repo-name/" to all entries apart first and last (empty line) (let* ((filename (code-compass--filename it)) (rev-file (s-concat filename "-revisions.csv"))) (--> rev-file (with-temp-buffer (insert-file-contents-literally it) (buffer-substring-no-properties (point-min) (point-max))) (s-split "\n" it 'omit-nulls) cdr (--map (concat filename "/" it) it) (s-join "\n" it) (format "%s\n" it) (write-region it nil rev-file))))) (code-compass--in-temp-directory repository ;; at this point I need to merge all *-revisions.csv and cloc-*.csv in something like "system" (shell-command "cat *-revisions.csv | sed '/^[[:space:]]*$/d' > revisions.csv;") (write-region (concat "entity,n-revs\n" (with-temp-buffer (insert-file-contents-literally "revisions.csv") (buffer-substring-no-properties (point-min) (point-max)))) nil "revisions.csv") (--> repository code-compass--generate-merger-script code-compass--generate-d3-v3-lib code-compass--produce-json code-compass--generate-host-enclosure-diagram-html (code-compass--run-server-and-navigate it port)))))) (define-obsolete-function-alias 'c/show-hotspot-cluster-sync #'code-compass-show-hotspot-cluster-sync "0.1.2") ;;;###autoload (defun code-compass-show-hotspot-cluster (directory date &optional port) "Show DIRECTORY enclosure diagram for hotspots. Starting DATE reduces scope of Git log. PORT defines where the html is served." (interactive (list (read-directory-name "Choose repositories directory:" ".") (call-interactively #'code-compass-request-date))) (code-compass--async-run #'code-compass-show-hotspot-cluster-sync directory date port)) (define-obsolete-function-alias 'c/show-hotspot-cluster #'code-compass-show-hotspot-cluster "0.1.2") ;; END Hotspots for microservices ;; BEGIN display contributors (defun code-compass--contributors-list-for-current-buffer () "Return contributors of this file if it is in a git repository." (if (vc-root-dir) (shell-command-to-string (concat "git shortlog HEAD -n -s -- " (buffer-file-name))) " No history yet")) (defun code-compass-file-name-parent-directory (filename) "Get parent of FILENAME. This comes in Emacs 29." (let* ((expanded-filename (expand-file-name filename)) (parent (file-name-directory (directory-file-name expanded-filename)))) (cond ;; filename is at top-level, therefore no parent ((or (null parent) ;; `equal' is enough, we don't need to resolve symlinks here ;; with `file-equal-p', also for performance (equal parent expanded-filename)) nil) ;; filename is relative, return relative parent ((not (file-name-absolute-p filename)) (file-relative-name parent)) (t parent)))) ;;;###autoload (defun code-compass-display-contributors () "Show in minibuffer the main contributors of this file." (interactive) (when (and code-compass-display-file-contributors (buffer-file-name)) (let ((file-path buffer-file-name)) ;; When we have the ability to infer the project root, we will use that to display the relative file path ;; Otherwise, we will display the entire full path. ;; We can infer project root when file in question, is in VCS. If its a new file, the function won't ;; be able to pick it up, so it will display the full file path. (when (vc-root-dir) (setq file-path (file-relative-name (buffer-file-name) (code-compass-file-name-parent-directory (vc-root-dir))))) (message "Contributors of %s:\n%s" file-path (code-compass--contributors-list-for-current-buffer))))) (define-obsolete-function-alias 'c/display-contributors #'code-compass-display-contributors "0.1.2") (defun code-compass-display-contributors-delayed () "Delayed version of `code-compass--display-contributors' for use in hooks. For example `prog-mode-hook'." (run-with-timer 0.1 nil 'code-compass-display-contributors)) (define-obsolete-function-alias 'c/display-contributors-delayed #'code-compass-display-contributors-delayed "0.1.2") (defun code-compass-toggle-display-contributors () "Show the contributors when opening files." (interactive) (if (-contains-p prog-mode-hook #'code-compass-display-contributors-delayed) (remove-hook 'prog-mode-hook #'code-compass-display-contributors-delayed) (add-hook 'prog-mode-hook #'code-compass-display-contributors-delayed))) ;; END display contributors (defun code-compass-cheatsheet () "Show cheatsheet for code compass." (interactive) (switch-to-buffer (get-buffer-create "*Code Compass Help*")) (org-mode) (insert " | Command | Description | |--------------------------------------------------+-----------------------------------------------------------------| | code-compass-doctor | Check dependencies are satisfied. | |--------------------------------------------------+-----------------------------------------------------------------| | Graphs | | |--------------------------------------------------+-----------------------------------------------------------------| | code-compass-show-hotspots | Show code that changed more frequently in the last period. | | code-compass-show-hotspot-snapshot-sync | Show hotspots over many intervals of times. | | code-compass-show-hotspot-cluster | Show hotspots graph for a directory containing many projects. | | code-compass-show-code-churn | Show code throughput/churn in the last period. | | code-compass-show-coupling-graph | Show which file is coupled to which in the last period. | | code-compass-show-code-communication | Show which contributors are/should likely chat with each other. | | code-compass-show-knowledge-graph | Show who knows most about what code. | | code-compass-show-refactoring-graph | Show who refactored most what code. | | code-compass-show-stability-graph | Show the code that is most stable in last period. | | code-compass-show-fragmentation | Show pie chart with how much people contributed to file. | | code-compass-show-gource | Show gource video of repository contributions. | |--------------------------------------------------+-----------------------------------------------------------------| | Complexity | | |--------------------------------------------------+-----------------------------------------------------------------| | code-compass-calculate-complexity-current-buffer | Prints complexity stats of current buffer. | | code-compass-show-complexity-over-commits | Show line graph of complexity for current file from the start. | |--------------------------------------------------+-----------------------------------------------------------------| | Word analysis | | |--------------------------------------------------+-----------------------------------------------------------------| | code-compass-word-statistics | Show stats about words in buffer. | | code-compass-word-semantics | Show words least used in buffer. | | code-compass-word-analysis-commits | Show frequency of words in commit messages. | | code-compass-word-analysis-region | Show frequency of words in region (useful on functions) | | code-compass-word-analysis-region-graph | Show graph for words frequency in region. | |--------------------------------------------------+-----------------------------------------------------------------| | Coupling extras | | |--------------------------------------------------+-----------------------------------------------------------------| | code-compass-create-todos-from-coupled-files | Make TODO list from coupled files. | | code-compass-find-coupled-files | Jump to a file coupled to the current one, if available. | |--------------------------------------------------+-----------------------------------------------------------------| | Contributors extras | | |--------------------------------------------------+-----------------------------------------------------------------| | code-compass-slack-main-contributor | Chat with main contributor of file via emacs-slack. | | code-compass-display-contributors | Show contributors for current file in minibuffer. | | code-compass-show-raw-csv | Show the raw csv file for code-maat analyses. | |--------------------------------------------------+-----------------------------------------------------------------| ")) (define-obsolete-function-alias 'c/cheatsheet #'code-compass-cheatsheet "0.1.2") ;;;###autoload (defun code-compass-show-raw-csv (analysis repository date) "Show REPOSITORY edge bundling synchronously for code coupling up to DATE. Serve graph on PORT. Argument ANALYSIS sets the anylysis command to run." (interactive (list (completing-read "Analysis:" '("authors" "revisions" "coupling" "soc" "summary" "identity" "abs-churn" "author-churn" "entity-churn" "entity-ownership" "main-dev" "refactoring-main-dev" "entity-effort" "main-dev-by-revs" "fragmentation" "communication" "messages" "age")) (read-directory-name "Choose git repository directory:" (vc-root-dir)) (call-interactively #'code-compass-request-date))) (code-compass--in-temp-directory repository (--> repository (code-compass-produce-git-report it nil date) (code-compass--run-code-maat analysis it)) (find-file (concat "./" analysis ".csv")) (when (progn (goto-char (point-min)) (search-forward "entity," nil t)) (while (search-forward-regexp "\\\n." nil t) (goto-char (- (point) 1)) (insert repository)) (goto-char (point-min))))) (define-obsolete-function-alias 'c/show-raw-csv #'code-compass-show-raw-csv "0.1.2") (provide 'code-compass) ;;; code-compass.el ends here ================================================ FILE: pages/age-enclosure-diagram/script.js ================================================ var margin = 10, outerDiameter = 960, innerDiameter = outerDiameter - margin - margin; var x = d3.scale.linear() .range([0, innerDiameter]); var y = d3.scale.linear() .range([0, innerDiameter]); var color = d3.scale.linear() .domain([-1, 5]) .range(["hsl(185,60%,99%)", "hsl(187,40%,70%)"]) .interpolate(d3.interpolateHcl); var pack = d3.layout.pack() .padding(2) .size([innerDiameter, innerDiameter]) .value(function(d) { return d.size; }) var svg = d3.select("body").append("svg") .attr("width", outerDiameter) .attr("height", outerDiameter) .append("g") .attr("transform", "translate(" + margin + "," + margin + ")"); d3.json("age.json", function(error, root) { var focus = root, nodes = pack.nodes(root); svg.append("g").selectAll("circle") .data(nodes) .enter().append("circle") .attr("class", function(d) { return d.parent ? d.children ? "node" : "node node--leaf" : "node node--root"; }) .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }) .attr("r", function(d) { return d.r; }) .style("fill", function(d) { return d.weight > 0.0 ? "whitesmoke" : d.children ? color(d.depth) : "black"; }) .style("fill-opacity", function(d) { return !!d.weight ? 1.0 - Math.min(1.0, d.weight) : d.weight;}) .on("click", function(d) { return zoom(focus == d ? root : d); }); svg.append("g").selectAll("text") .data(nodes) .enter().append("text") .attr("class", "label") .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }) .style("fill-opacity", function(d) { return d.parent === root ? 1 : 0; }) .style("display", function(d) { return d.parent === root ? null : "none"; }) .text(function(d) { return d.name; }); d3.select(window) .on("click", function() { zoom(root); }); function zoom(d, i) { var focus0 = focus; focus = d; var k = innerDiameter / d.r / 2; x.domain([d.x - d.r, d.x + d.r]); y.domain([d.y - d.r, d.y + d.r]); d3.event.stopPropagation(); var transition = d3.selectAll("text,circle").transition() .duration(d3.event.altKey ? 7500 : 750) .attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; }); transition.filter("circle") .attr("r", function(d) { return k * d.r; }); transition.filter("text") .filter(function(d) { return d.parent === focus || d.parent === focus0; }) .style("fill-opacity", function(d) { return d.parent === focus ? 1 : 0; }) .each("start", function(d) { if (d.parent === focus) this.style.display = "inline"; }) .each("end", function(d) { if (d.parent !== focus) this.style.display = "none"; }); }} ); d3.select(self.frameElement).style("height", outerDiameter + "px"); ================================================ FILE: pages/age-enclosure-diagram/style.css ================================================ .node { cursor: pointer; } .node:hover { stroke: #000; stroke-width: 1.5px; } .node--root { stroke: #777; stroke-width: 2px; } .node--leaf { fill: white; stroke: #777; stroke-width: 1px; } .label { font: 14px "Helvetica Neue", Helvetica, Arial, sans-serif; text-anchor: middle; fill: black; //text-shadow: 0 1px 0 #fff, 1px 0 0 #fff, -1px 0 0 #fff, 0 -1px 0 #fff; } .label, .node--root, .node--leaf { pointer-events: none; } ================================================ FILE: pages/age-enclosure-diagram/zoomable.html ================================================ ================================================ FILE: pages/edge-bundling/script.js ================================================ var diameter = 960, radius = diameter / 2, innerRadius = radius - 120; var cluster = d3.cluster().size([360, innerRadius]); var line = d3 .radialLine() .curve(d3.curveBundle.beta(0.85)) .radius(function (d) { return d.y; }) .angle(function (d) { return (d.x / 180) * Math.PI; }); var svg = d3 .select("body") .append("svg") .attr("width", diameter) .attr("height", diameter) .append("g") .attr("transform", "translate(" + radius + "," + radius + ")"); var link = svg.append("g").selectAll(".link"), node = svg.append("g").selectAll(".node"); d3.json("edgebundling.json", function (error, classes) { if (error) throw error; var root = packageHierarchy(classes).sum(function (d) { return d.size; }); cluster(root); link = link .data(packageImports(root.leaves())) .enter() .append("path") .each(function (d) { (d.source = d[0]), (d.target = d[d.length - 1]); }) .attr("class", "link") .attr("d", line); node = node .data(root.leaves()) .enter() .append("text") .attr("class", "node") .attr("dy", "0.31em") .attr("transform", function (d) { return ( "rotate(" + (d.x - 90) + ")translate(" + (d.y + 8) + ",0)" + (d.x < 180 ? "" : "rotate(180)") ); }) .attr("text-anchor", function (d) { return d.x < 180 ? "start" : "end"; }) .text(function (d) { return d.data.key; }) .on("mouseover", mouseovered) .on("mouseout", mouseouted); }); function mouseovered(d) { node.each(function (n) { n.target = n.source = false; }); link.classed("link--target", function (l) { if (l.target === d) return (l.source.source = true); }) .classed("link--source", function (l) { if (l.source === d) return (l.target.target = true); }) .filter(function (l) { return l.target === d || l.source === d; }) .raise(); node.classed("node--target", function (n) { return n.target; }).classed("node--source", function (n) { return n.source; }); } function mouseouted(d) { link.classed("link--target", false).classed("link--source", false); node.classed("node--target", false).classed("node--source", false); } // Lazily construct the package hierarchy from class names. function packageHierarchy(classes) { var map = {}; function find(name, data) { var node = map[name], i; if (!node) { node = map[name] = data || { name: name, children: [] }; if (name.length) { node.parent = find( name.substring(0, (i = name.lastIndexOf("/"))) ); node.parent.children.push(node); node.key = name.substring(i + 1); } } return node; } classes.forEach(function (d) { find(d.name, d); }); return d3.hierarchy(map[""]); } // Return a list of imports for the given array of nodes. function packageImports(nodes) { var map = {}, imports = []; // Compute a map from name to node. nodes.forEach(function (d) { map[d.data.name] = d; }); // For each import, construct a link from the source to target node. nodes.forEach(function (d) { if (d.data.imports) d.data.imports.forEach(function (i) { if (map[i]) { // skip nodes that do not have a pair imports.push(map[d.data.name].path(map[i])); } }); }); return imports; } ================================================ FILE: pages/edge-bundling/style.css ================================================ .node { font: 300 11px "Helvetica Neue", Helvetica, Arial, sans-serif; fill: #bbb; } .node:hover { fill: #000; } .link { stroke: steelblue; stroke-opacity: 0.4; fill: none; pointer-events: none; } .node:hover, .node--source, .node--target { font-weight: 700; } .node--source { fill: #2ca02c; } .node--target { fill: #d62728; } .link--source, .link--target { stroke-opacity: 1; stroke-width: 2px; } .link--source { stroke: #d62728; } .link--target { stroke: #2ca02c; } ================================================ FILE: pages/edge-bundling/zoomable.html ================================================ ================================================ FILE: pages/enclosure-diagram/script.js ================================================ var margin = 10, outerDiameter = 960, innerDiameter = outerDiameter - margin - margin; var x = d3.scale.linear().range([0, innerDiameter]); var y = d3.scale.linear().range([0, innerDiameter]); var color = d3.scale .linear() .domain([-1, 5]) .range(["hsl(185,60%,99%)", "hsl(187,40%,70%)"]) .interpolate(d3.interpolateHcl); var pack = d3.layout .pack() .padding(2) .size([innerDiameter, innerDiameter]) .value(function (d) { return d.size; }); var svg = d3 .select("body") .append("svg") .attr("width", outerDiameter) .attr("height", outerDiameter) .append("g") .attr("transform", "translate(" + margin + "," + margin + ")"); d3.json("hotspot_proto.json", function (error, root) { var focus = root, nodes = pack.nodes(root); svg.append("g") .selectAll("circle") .data(nodes) .enter() .append("circle") .attr("class", function (d) { return d.parent ? d.children ? "node" : "node node--leaf" : "node node--root"; }) .attr("transform", function (d) { return "translate(" + d.x + "," + d.y + ")"; }) .attr("r", function (d) { return d.r; }) .style("fill", function (d) { return d.weight > 0.0 ? "darkred" : d.children ? color(d.depth) : "black"; }) .style("fill-opacity", function (d) { return d.weight; }) .on("click", function (d) { return zoom(focus == d ? root : d); }); svg.append("g") .selectAll("text") .data(nodes) .enter() .append("text") .attr("class", "label") .attr("transform", function (d) { return "translate(" + d.x + "," + d.y + ")"; }) .style("fill-opacity", function (d) { return d.parent === root ? 1 : 0; }) .style("display", function (d) { return d.parent === root ? null : "none"; }) .text(function (d) { return d.name; }); d3.select(window).on("click", function () { zoom(root); }); function zoom(d, i) { var focus0 = focus; focus = d; var k = innerDiameter / d.r / 2; x.domain([d.x - d.r, d.x + d.r]); y.domain([d.y - d.r, d.y + d.r]); d3.event.stopPropagation(); var transition = d3 .selectAll("text,circle") .transition() .duration(d3.event.altKey ? 7500 : 750) .attr("transform", function (d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; }); transition.filter("circle").attr("r", function (d) { return k * d.r; }); transition .filter("text") .filter(function (d) { return d.parent === focus || d.parent === focus0; }) .style("fill-opacity", function (d) { return d.parent === focus ? 1 : 0; }) .each("start", function (d) { if (d.parent === focus) this.style.display = "inline"; }) .each("end", function (d) { if (d.parent !== focus) this.style.display = "none"; }); } }); d3.select(self.frameElement).style("height", outerDiameter + "px"); ================================================ FILE: pages/enclosure-diagram/style.css ================================================ .node { cursor: pointer; } .node:hover { stroke: #000; stroke-width: 1.5px; } .node--root { stroke: #777; stroke-width: 2px; } .node--leaf { fill: white; stroke: #777; stroke-width: 1px; } .label { font: 14px "Helvetica Neue", Helvetica, Arial, sans-serif; text-anchor: middle; fill: white; //text-shadow: 0 1px 0 #fff, 1px 0 0 #fff, -1px 0 0 #fff, 0 -1px 0 #fff; } .label, .node--root, .node--leaf { pointer-events: none; } ================================================ FILE: pages/enclosure-diagram/zoomable.html ================================================ ================================================ FILE: pages/knowledge-enclosure-diagram/script.js ================================================ var margin = 10, outerDiameter = 960, innerDiameter = outerDiameter - margin - margin; var x = d3.scale.linear() .range([0, innerDiameter]); var y = d3.scale.linear() .range([0, innerDiameter]); var color = d3.scale.linear() .domain([-1, 5]) .range(["hsl(185,60%,99%)", "hsl(187,40%,70%)"]) .interpolate(d3.interpolateHcl); var pack = d3.layout.pack() .padding(2) .size([innerDiameter, innerDiameter]) .value(function(d) { return d.size; }) var mainDiv = d3 .select("body") .append("div") .attr("id", "maindiv") .style("width", "100%") .style("float", "left") var graphDiv = d3 .select("#maindiv") .append("div") .attr("id", "graphdiv") .style("width", "600px") .style("float", "left") var svg = d3 .select("#graphdiv") .append("svg") .attr("width", outerDiameter) .attr("height", outerDiameter) .append("g") .attr("transform", "translate(" + margin + "," + margin + ")"); d3.json("knowledge.json", function(error, root) { var focus = root, nodes = pack.nodes(root); svg.append("g").selectAll("circle") .data(nodes) .enter().append("circle") .attr("class", function(d) { return d.parent ? d.children ? "node" : "node node--leaf" : "node node--root"; }) .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }) .attr("r", function(d) { return d.r; }) .style("fill", function(d) { return d.weight > 0.0 ? d.author_color : d.children ? color(d.depth) : "black"; }) .style("fill-opacity", function(d) { return d.effort; }) .on("click", function(d) { return d.children ? zoom(focus == d ? root : d) : undefined; }); svg.append("g").selectAll("text") .data(nodes) .enter().append("text") .attr("class", "label") .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }) .style("fill-opacity", function(d) { return d.parent === root ? 1 : 0; }) .style("display", function(d) { return d.parent === root ? null : "none"; }) .text(function(d) { return d.name; }) .on("mouseover", function(d){this.innerHTML = d.author || d.name;}) .on("mouseout", function(d){this.innerHTML = d.name;}); d3.select(window) .on("click", function() { zoom(root); }); function zoom(d, i) { var focus0 = focus; focus = d; var k = innerDiameter / d.r / 2; x.domain([d.x - d.r, d.x + d.r]); y.domain([d.y - d.r, d.y + d.r]); d3.event.stopPropagation(); var transition = d3.selectAll("text,circle").transition() .duration(d3.event.altKey ? 7500 : 750) .attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; }); transition.filter("circle") .attr("r", function(d) { return k * d.r; }); transition.filter("text") .filter(function(d) { return d.parent === focus || d.parent === focus0; }) .style("fill-opacity", function(d) { return d.parent === focus ? 1 : 0; }) .each("start", function(d) { if (d.parent === focus) this.style.display = "inline"; }) .each("end", function(d) { if (d.parent !== focus) this.style.display = "none"; }); }} ); d3.select(self.frameElement).style("height", outerDiameter + "px"); var div = d3 .select("#maindiv") .append("div") .attr("id", "legendiv") .attr("width", outerDiameter) .attr("height", outerDiameter) .style("margin-left", "1020px") .style("height", "800px") .style("overflow-y", "scroll"); var legendSVG = d3 .select("#legendiv") .append("svg") .style("height", "3000") .style("width", "450"); var size = 20 d3.csv("authors.csv", function(authorsColors){ // Add dots legendSVG.selectAll("mydots") .data(authorsColors) .enter() .append("rect") .attr("x", 100) .attr("y", function(d,i){ return 100 + i*(size+5)}) // 100 is where the first dot appears. 25 is the distance between dots .attr("width", size) .attr("height", size) .style("fill", function(d){ return d.color}) // Add names. legendSVG.selectAll("mylabels") .data(authorsColors) .enter() .append("text") .attr("x", 100 + size*1.2) .attr("y", function(d,i){ return 100 + i*(size+5) + (size/2)}) .style("fill", function(d){ return d.color}) .text(function(d){ return d.author}) .attr("text-anchor", "left") .style("alignment-baseline", "middle") }) ================================================ FILE: pages/knowledge-enclosure-diagram/style.css ================================================ .node { cursor: pointer; } .node:hover { stroke: #000; stroke-width: 1.5px; } .node--root { stroke: #777; stroke-width: 2px; } .node--leaf { fill: white; stroke: #777; stroke-width: 1px; } .label { font: 14px "Helvetica Neue", Helvetica, Arial, sans-serif; text-anchor: middle; fill: white; //text-shadow: 0 1px 0 #fff, 1px 0 0 #fff, -1px 0 0 #fff, 0 -1px 0 #fff; } .label, .node--root, .node--leaf { } ================================================ FILE: pages/knowledge-enclosure-diagram/zoomable.html ================================================ ================================================ FILE: requirements.txt ================================================ graph-cli PyQT5 ================================================ FILE: scripts/code_age_csv_as_enclosure_json.py ================================================ #!/bin/env python ####################################################################### ## This program generates a JSON document suitable for a D3.js ## enclosure diagram visualization. This script is used together with ## a Code Maat age analysis in order to calculate the exponential ## decay and stabilization of code. ## ## The input data is read from two CSV files: ## 1) The complete system structure, including size metrics. ## 2) A code age analysis result used to assign weights to the modules. ####################################################################### import argparse import csv import json import sys class MergeError(Exception): def __init__(self, message): Exception.__init__(self, message) class Merged(object): def __init__(self): self._all_modules_with_complexity = {} self._merged = {} def sorted_result(self): # Sort on descending order: ordered = sorted(list(self._merged.items()), key=lambda item: item[1][0], reverse=True) return ordered def extend_with(self, name, freqs): if name in self._all_modules_with_complexity: complexity = self._all_modules_with_complexity[name] self._merged[name] = freqs, complexity def record_detected(self, name, complexity): self._all_modules_with_complexity[name] = complexity def write_csv(stats): print('module,revisions,code') for s in stats: name, (f,c) = s print(name + ',' + f + ',' + c) def parse_complexity(merged, row): name = row[1][2:] complexity = row[4] merged.record_detected(name, complexity) def parse_freqs(merged, row): name = row[0] freqs = row[1] merged.extend_with(name, freqs) def merge(revs_file, comp_file): merged = Merged() parse_csv(merged, comp_file, parse_complexity, expected_format='language,filename,blank,comment,code') parse_csv(merged, revs_file, parse_freqs, expected_format='entity,n-revs') write_csv(merged.sorted_result()) ###################################################################### ## Parse input ###################################################################### def validate_content_by(heading, expected): if not expected: return # no validation comparison = expected.split(',') stripped = heading[0:len(comparison)] # allow extra fields if stripped != comparison: raise MergeError('Erroneous content. Expected = ' + expected + ', got = ' + ','.join(heading)) def parse_csv(filename, parse_action, expected_format=None): def read_heading_from(r): p = next(r) while p == []: p = next(r) return p with open(filename, 'r', encoding="utf8") as csvfile: r = csv.reader(csvfile, delimiter=',') heading = read_heading_from(r) validate_content_by(heading, expected_format) return [parse_action(row) for row in r] class StructuralElement(object): def __init__(self, name, complexity): self.name = name self.complexity = complexity def parts(self): return self.name.split('/') def parse_structural_element(csv_row): name = csv_row[1][2:] complexity = csv_row[4] return StructuralElement(name, complexity) def make_element_weight_parser(weight_column): """ Parameterize with the column - this allows us to generate data from different analysis result types. """ def parse_element_weight(csv_row): name = csv_row[0] weight = float(csv_row[weight_column]) # Assert not zero? return name, weight return parse_element_weight ###################################################################### ## Calculating weights from the given CSV analysis file ###################################################################### class WeightCalculator(object): """ Calculates code age using exponential decay. """ def __init__(self, half_life, analysis_results): self._half_life_months = float(half_life) def as_half_life(age): return 1 / 2**(float(age)/self._half_life_months) def as_color(age): if age < self._half_life_months: return "darkred" return "DodgerBlue" def as_colored_weight(age): return as_half_life(age), as_color(age) self._colored_weights = dict([(name, as_colored_weight(n)) for name,n in analysis_results]) def weight_for(self, module_name): if module_name in self._colored_weights: weight, _ = self._colored_weights[module_name] return weight return 0.0 def color_of(self, module_name): if module_name in self._colored_weights: _, color = self._colored_weights[module_name] return color return "gray" ###################################################################### ## Building the structure of the system ###################################################################### def _matching_part_in(hierarchy, part): return next((x for x in hierarchy if x['name']==part), None) def _ensure_branch_exists(hierarchy, branch): existing = _matching_part_in(hierarchy, branch) if not existing: new_branch = {'name':branch, 'children':[]} hierarchy.append(new_branch) existing = new_branch return existing def _add_leaf(hierarchy, module, weight_calculator, name): new_leaf = {'name':name, 'children':[], 'size':module.complexity, 'weight':weight_calculator.weight_for(module.name), 'color':weight_calculator.color_of(module.name)} hierarchy.append(new_leaf) return hierarchy def _insert_parts_into(hierarchy, module, weight_calculator, parts): """ Recursively traverse the hierarchy and insert the individual parts of the module, one by one. The parts specify branches. If any branch is missing, it's created during the traversal. The final part specifies a module name (sans its path, of course). This is where we add size and weight to the leaf. """ if len(parts) == 1: return _add_leaf(hierarchy, module, weight_calculator, name=parts[0]) next_branch = parts[0] existing_branch = _ensure_branch_exists(hierarchy, next_branch) return _insert_parts_into(existing_branch['children'], module, weight_calculator, parts=parts[1:]) def generate_structure_from(modules, weight_calculator): hierarchy = [] for module in modules: parts = module.parts() _insert_parts_into(hierarchy, module, weight_calculator, parts) structure = {'name':'root', 'children':hierarchy} return structure ###################################################################### ## Output ###################################################################### def write_json(result): print(json.dumps(result)) ###################################################################### ## Main ###################################################################### def run(args): raw_weights = parse_csv(args.weights, parse_action=make_element_weight_parser(args.weightcolumn)) weight_calculator = WeightCalculator(args.halflife, raw_weights) structure_input = parse_csv(args.structure, expected_format='language,filename,blank,comment,code', parse_action=parse_structural_element) weighted_system_structure = generate_structure_from(structure_input, weight_calculator) write_json(weighted_system_structure) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Generates a JSON document suitable for enclosure diagrams.') parser.add_argument('--structure', required=True, help='A CSV file generated by cloc') parser.add_argument('--weights', required=True, help='A CSV file with code age results from Code Maat') parser.add_argument('--weightcolumn', type=int, default=1, help="The index specifying the column to use in the weight table") parser.add_argument('--halflife', type=int, default=1, help="Specifies the half life for a module in months") args = parser.parse_args() run(args) ================================================ FILE: scripts/communication_csv_as_edge_bundling.py ================================================ #!/bin/env python ####################################################################### ## This program generates a JSON document suitable for a D3.js ## Hierarchical Edge Bundling visualization (see https://gist.github.com/mbostock/7607999) ## ## The input data is read from a Code Maat CSV file containing the result ## of a analysis. ####################################################################### import argparse import csv import json import sys ###################################################################### ## Parse input ###################################################################### def validate_content_by(heading, expected): if not expected: return # no validation comparison = expected.split(',') stripped = heading[0:len(comparison)] # allow extra fields if stripped != comparison: raise MergeError('Erroneous content. Expected = ' + expected + ', got = ' + ','.join(heading)) def parse_csv(filename, parse_action, expected_format=None): def read_heading_from(r): p = next(r) while p == []: p = next(r) return p with open(filename, 'rt', encoding="utf8") as csvfile: r = csv.reader(csvfile, delimiter=',') heading = read_heading_from(r) validate_content_by(heading, expected_format) return [parse_action(row) for row in r] class LinkBetweenPeer(object): def __init__(self, author, peer, strength): self.author = author self.peer = peer self.strength = int(strength) def parse_peers(csv_row): return LinkBetweenPeer(csv_row[0], csv_row[1], csv_row[4]) ###################################################################### ## Assemble the individual entries into an aggregated structure ###################################################################### def link_to(existing_authors, new_link): if not new_link.author in existing_authors: return {'name':new_link.author, 'size':new_link.strength, 'imports':[new_link.peer]} existing_author = existing_authors[new_link.author] existing_author['imports'].append(new_link.peer) existing_author['size'] = existing_author['size'] + new_link.strength return existing_author def aggregate_links_per_author_in(peer_links): links_per_author = {} for peer in peer_links: links_per_author[peer.author] = link_to(links_per_author, peer) return links_per_author ###################################################################### ## Output ###################################################################### def write_json(result): print(json.dumps(result)) ###################################################################### ## Main ###################################################################### def run(args): peer_links = parse_csv(args.communication, expected_format='author,peer,shared,average,strength', parse_action=parse_peers) links_by_author = aggregate_links_per_author_in(peer_links) write_json(list(links_by_author.values())) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Generates a JSON document suitable for communication diagrams.') parser.add_argument('--communication', required=True, help='A CSV file containing the result of a communication analysis') args = parser.parse_args() run(args) ================================================ FILE: scripts/coupling_csv_as_edge_bundling.py ================================================ #!/bin/env python """ The input data is read from a Code Maat CSV file containing the result of a analysis. """ import argparse import csv import json import sys def validate_content_by(heading, expected): if not expected: return # no validation comparison = expected.split(",") stripped = heading[0 : len(comparison)] # allow extra fields if stripped != comparison: raise MergeError( "Erroneous content. Expected = " + expected + ", got = " + ",".join(heading) ) def parse_csv(filename, parse_action, expected_format=None): def read_heading_from(r): p = next(r) while p == []: p = next(r) return p with open(filename, "rt", encoding="utf8") as csvfile: r = csv.reader(csvfile, delimiter=",") heading = read_heading_from(r) validate_content_by(heading, expected_format) return [parse_action(row) for row in r] class LinkBetweenCoupled(object): def __init__(self, entity, coupled, degree): self.entity = entity self.coupled = coupled self.degree = int(degree) def parse_coupleds(csv_row): return LinkBetweenCoupled( csv_row[0], csv_row[1], csv_row[2] ) # 2020-07-05 AG: editing this to make it work with software dependencies, TODO rename all entity based naming to coupled stuff def link_to(existing_entitys, new_link): if not new_link.entity in existing_entitys: return { "name": new_link.entity, "size": new_link.degree, "imports": [new_link.coupled], } existing_entity = existing_entitys[new_link.entity] existing_entity["imports"].append(new_link.coupled) existing_entity["size"] = existing_entity["size"] + new_link.degree return existing_entity def aggregate_links_per_entity_in(coupled_links): links_per_entity = {} for coupled in coupled_links: links_per_entity[coupled.entity] = link_to(links_per_entity, coupled) return links_per_entity def write_json(result): print(json.dumps(result)) def run(args): coupled_links = parse_csv( args.coupling, expected_format="entity,coupled,degree,average-revs", parse_action=parse_coupleds, ) links_by_entity = aggregate_links_per_entity_in(coupled_links) write_json(list(links_by_entity.values())) if __name__ == "__main__": parser = argparse.ArgumentParser( description="Generates a JSON document suitable for coupling diagrams." ) parser.add_argument( "--coupling", required=True, help="A CSV file containing the result of a coupling analysis", ) args = parser.parse_args() run(args) ================================================ FILE: scripts/csv-to-pie-graph.py ================================================ #!/bin/env python import pandas as pd import matplotlib.pyplot as plt import argparse parser = argparse.ArgumentParser("simple_example") parser.add_argument("csv", help="The csv file containing 2 columns.") args = parser.parse_args() csv_file=args.csv data = pd.read_csv(csv_file) Authors = data["author"] Lines = data["+&-lines"] x=[] y=[] x=list(Lines) y=list(Authors) plt.title('Ownership Fragmentation') plt.pie(x,labels=y,autopct='%.2f%%') plt.show() ================================================ FILE: scripts/csv_as_enclosure_json.py ================================================ #!/bin/env python """ This program generates a JSON document suitable for a D3.js enclosure diagram visualization. The input data is read from two CSV files: 1) The complete system structure, including size metrics. 2) A hotspot analysis result used to assign weights to the modules. """ import argparse import csv import json class MergeError(Exception): pass class Merged(object): def __init__(self): self._all_modules_with_complexity = {} self._merged = {} def sorted_result(self): # Sort on descending order: return sorted( list(self._merged.items()), key=lambda item: item[1][0], reverse=True ) def extend_with(self, name, freqs): if name in self._all_modules_with_complexity: complexity = self._all_modules_with_complexity[name] self._merged[name] = freqs, complexity def record_detected(self, name, complexity): self._all_modules_with_complexity[name] = complexity def write_csv(stats): print("module,revisions,code") for name, (f, c) in stats: print(f"{name},{f},{c}") def parse_complexity(merged, row): _, name, _, _, complexity, *_ = row merged.record_detected(name[2:], complexity) def parse_freqs(merged, row): name, freqs, *_ = row merged.extend_with(name, freqs) def merge(revs_file, comp_file): merged = Merged() parse_csv( merged, comp_file, parse_complexity, expected_format="language,filename,blank,comment,code", ) parse_csv(merged, revs_file, parse_freqs, expected_format="entity,n-revs") write_csv(merged.sorted_result()) def validate_content_by(heading, expected): if not expected: return # no validation comparison = expected.split(",") stripped = heading[0 : len(comparison)] # allow extra fields if stripped != comparison: raise MergeError( f"Erroneous content. Expected = {expected}, got = {','.join(heading)}" ) def parse_csv(filename, parse_action, expected_format=None): def read_heading_from(r): p = next(r) while p == []: p = next(r) return p with open(filename, "r") as csvfile: r = csv.reader(csvfile, delimiter=",") heading = read_heading_from(r) validate_content_by(heading, expected_format) return [parse_action(row) for row in r] class StructuralElement(object): def __init__(self, name, complexity): self.name = name self.complexity = complexity def parts(self): return self.name.split("/") def parse_structural_element(csv_row): _, name, _, _, complexity, *_ = csv_row return StructuralElement(name[2:], complexity) def make_element_weight_parser(weight_column): """Parameterize with the column - this allows us to generate data from different analysis result types. """ def parse_element_weight(csv_row): name = csv_row[0] weight = float(csv_row[weight_column]) # Assert not zero? return name, weight return parse_element_weight def module_weight_calculator_from(analysis_results): max_raw_weight = max(analysis_results, key=lambda e: e[1]) max_value = max_raw_weight[1] normalized_weights = dict( [(name, (1.0 / max_value) * n) for name, n in analysis_results] ) def normalized_weight_for(module_name): if module_name in normalized_weights: return normalized_weights[module_name] return 0.0 return normalized_weight_for def _matching_part_in(hierarchy, part): return next((x for x in hierarchy if x["name"] == part), None) def _ensure_branch_exists(hierarchy, branch): existing = _matching_part_in(hierarchy, branch) if not existing: new_branch = {"name": branch, "children": []} hierarchy.append(new_branch) existing = new_branch return existing def _add_leaf(hierarchy, module, weight_calculator, name): # TODO: augment with weight here! new_leaf = { "name": name, "children": [], "size": module.complexity, "weight": weight_calculator(module.name), } hierarchy.append(new_leaf) return hierarchy def _insert_parts_into(hierarchy, module, weight_calculator, parts): """Recursively traverse the hierarchy and insert the individual parts of the module, one by one. The parts specify branches. If any branch is missing, it's created during the traversal. The final part specifies a module name (sans its path, of course). This is where we add size and weight to the leaf. """ if len(parts) == 1: return _add_leaf(hierarchy, module, weight_calculator, name=parts[0]) next_branch, *rest = parts existing_branch = _ensure_branch_exists(hierarchy, next_branch) return _insert_parts_into( existing_branch["children"], module, weight_calculator, parts=rest ) def generate_structure_from(modules, weight_calculator): hierarchy = [] for module in modules: parts = module.parts() _insert_parts_into(hierarchy, module, weight_calculator, parts) return {"name": "root", "children": hierarchy} def write_json(result): print(json.dumps(result)) # TODO: turn it around: parse the weights first and add them to individual elements # as the raw structure list is built! def run(args): raw_weights = parse_csv( args.weights, parse_action=make_element_weight_parser(args.weightcolumn) ) weight_calculator = module_weight_calculator_from(raw_weights) structure_input = parse_csv( args.structure, expected_format="language,filename,blank,comment,code", parse_action=parse_structural_element, ) weighted_system_structure = generate_structure_from( structure_input, weight_calculator ) write_json(weighted_system_structure) if __name__ == "__main__": parser = argparse.ArgumentParser( description="Generates a JSON document suitable for enclosure diagrams." ) parser.add_argument( "--structure", required=True, help="A CSV file generated by cloc" ) parser.add_argument( "--weights", required=True, help="A CSV file with hotspot results from Code Maat", ) parser.add_argument( "--weightcolumn", type=int, default=1, help="The index specifying the columnt to use in the weight table", ) # TODO: add arguments to specify which CSV columns to use! args = parser.parse_args() run(args) ================================================ FILE: scripts/knowledge_csv_as_enclosure_diagram.py ================================================ #!/bin/env python ####################################################################### ## This program generates a JSON document suitable for a D3.js ## enclosure diagram visualization. ## The input data is read from three CSV files: ## 1) A cloc output file specifying the static structure of the system. ## 2) A file containing Code Maat main developer results. ## 3) A file specifying the color to use for a certain author. If that ## information is absent, this script will treat that code as a ## dead spot. ## This CSV file must have two columns: author, color ####################################################################### import argparse import csv import json import sys ###################################################################### ## Parse input ###################################################################### def validate_content_by(heading, expected): if not expected: return # no validation comparison = expected.split(',') stripped = heading[0:len(comparison)] # allow extra fields if stripped != comparison: raise MergeError('Erroneous content. Expected = ' + expected + ', got = ' + ','.join(heading)) def parse_csv(filename, parse_action, expected_format=None): def read_heading_from(r): p = next(r) while p == []: p = next(r) return p with open(filename, 'r') as csvfile: r = csv.reader(csvfile, delimiter=',') heading = read_heading_from(r) validate_content_by(heading, expected_format) return [parse_action(row) for row in r] class StructuralElement(object): def __init__(self, name, complexity): self.name = name self.complexity = complexity def parts(self): return self.name.split('/') def parse_structural_element(csv_row): name = csv_row[1][2:] complexity = csv_row[4] return StructuralElement(name, complexity) def parse_author_color(csv_row): author = csv_row[0] color = csv_row[1] return author,color class Ownership(object): def __init__(self, module, main_author, ownership): self.module = module self.main_author = main_author self.ownership = ownership def parse_ownership(csv_row): module = csv_row[0] main_author = csv_row[1] ownership = csv_row[4] return Ownership(module, main_author,ownership) ###################################################################### ## Organizational information to augment the structure ###################################################################### class Knowledge(object): DEFAULT_COLOR = "black" def __init__(self, authors_colors, ownerships): self._authors_colors = authors_colors self._ownership = dict([(o.module, o) for o in ownerships]) def color_of(self, author): if author in self._authors_colors: return self._authors_colors[author] return self.DEFAULT_COLOR def owner_of(self, module_name): if module_name in self._ownership: o = self._ownership[module_name] return o.main_author return None def degree_of_ownership_for(self, module_name): if module_name in self._ownership: o = self._ownership[module_name] return o.ownership return 0.0 ###################################################################### ## Building the structure of the system ###################################################################### def _matching_part_in(hierarchy, part): return next((x for x in hierarchy if x['name']==part), None) def _ensure_branch_exists(hierarchy, branch): existing = _matching_part_in(hierarchy, branch) if not existing: new_branch = {'name':branch, 'children':[]} hierarchy.append(new_branch) existing = new_branch return existing def _add_leaf(hierarchy, module, knowledge, name): owner = knowledge.owner_of(module.name) new_leaf = {'name':name, 'children':[], 'size':module.complexity, 'weight':knowledge.degree_of_ownership_for(module.name), 'author': owner, 'author_color':knowledge.color_of(owner)} hierarchy.append(new_leaf) return hierarchy def _insert_parts_into(hierarchy, module, knowledge, parts): """ Recursively traverse the hierarchy and insert the individual parts of the module, one by one. The parts specify branches. If any branch is missing, it's created during the traversal. The final part specifies a module name (sans its path, of course). This is where we add size and weight to the leaf. """ if len(parts) == 1: return _add_leaf(hierarchy, module, knowledge, name=parts[0]) next_branch = parts[0] existing_branch = _ensure_branch_exists(hierarchy, next_branch) return _insert_parts_into(existing_branch['children'], module, knowledge, parts=parts[1:]) def generate_structure_from(modules, knowledge): hierarchy = [] for module in modules: parts = module.parts() _insert_parts_into(hierarchy, module, knowledge, parts) structure = {'name':'root', 'children':hierarchy} return structure ###################################################################### ## Output ###################################################################### def write_json(result): print(json.dumps(result)) ###################################################################### ## Main ###################################################################### def run(args): authors_colors = dict(parse_csv(args.authors, expected_format='author,color', parse_action=parse_author_color)) module_ownership = parse_csv(args.owners, expected_format='entity,main-dev,added,total-added,ownership', parse_action=parse_ownership) structure_input = parse_csv(args.structure, expected_format='language,filename,blank,comment,code', parse_action=parse_structural_element) knowledge = Knowledge(authors_colors, module_ownership) knowledge_structure = generate_structure_from(structure_input, knowledge) write_json(knowledge_structure) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Generates a JSON document suitable for knowledge diagrams.') parser.add_argument('--structure', required=True, help='A CSV file generated by cloc') parser.add_argument('--owners', required=True, help='A CSV file generated by a Code Maat main-dev analysis') parser.add_argument('--authors', required=True, help='A CSV file specifying the color to use for each author') args = parser.parse_args() run(args) ================================================ FILE: scripts/refactoring_csv_as_enclosure_diagram.py ================================================ #!/bin/env python ####################################################################### ## This program generates a JSON document suitable for a D3.js ## enclosure diagram visualization. ## The input data is read from three CSV files: ## 1) A cloc output file specifying the static structure of the system. ## 2) A file containing Code Maat main developer results. ## 3) A file specifying the color to use for a certain author. If that ## information is absent, this script will treat that code as a ## dead spot. ## This CSV file must have two columns: author, color ####################################################################### import argparse import csv import json import sys ###################################################################### ## Parse input ###################################################################### def validate_content_by(heading, expected): if not expected: return # no validation comparison = expected.split(',') stripped = heading[0:len(comparison)] # allow extra fields if stripped != comparison: raise MergeError('Erroneous content. Expected = ' + expected + ', got = ' + ','.join(heading)) def parse_csv(filename, parse_action, expected_format=None): def read_heading_from(r): p = next(r) while p == []: p = next(r) return p with open(filename, 'r') as csvfile: r = csv.reader(csvfile, delimiter=',') heading = read_heading_from(r) validate_content_by(heading, expected_format) return [parse_action(row) for row in r] class StructuralElement(object): def __init__(self, name, complexity): self.name = name self.complexity = complexity def parts(self): return self.name.split('/') def parse_structural_element(csv_row): name = csv_row[1][2:] complexity = csv_row[4] return StructuralElement(name, complexity) def parse_author_color(csv_row): author = csv_row[0] color = csv_row[1] return author,color class Ownership(object): def __init__(self, module, main_author, ownership): self.module = module self.main_author = main_author self.ownership = ownership def parse_ownership(csv_row): module = csv_row[0] main_author = csv_row[1] ownership = csv_row[4] return Ownership(module, main_author,ownership) ###################################################################### ## Organizational information to augment the structure ###################################################################### class Knowledge(object): DEFAULT_COLOR = "black" def __init__(self, authors_colors, ownerships): self._authors_colors = authors_colors self._ownership = dict([(o.module, o) for o in ownerships]) def color_of(self, author): if author in self._authors_colors: return self._authors_colors[author] return self.DEFAULT_COLOR def owner_of(self, module_name): if module_name in self._ownership: o = self._ownership[module_name] return o.main_author return None def degree_of_ownership_for(self, module_name): if module_name in self._ownership: o = self._ownership[module_name] return o.ownership return 0.0 ###################################################################### ## Building the structure of the system ###################################################################### def _matching_part_in(hierarchy, part): return next((x for x in hierarchy if x['name']==part), None) def _ensure_branch_exists(hierarchy, branch): existing = _matching_part_in(hierarchy, branch) if not existing: new_branch = {'name':branch, 'children':[]} hierarchy.append(new_branch) existing = new_branch return existing def _add_leaf(hierarchy, module, knowledge, name): owner = knowledge.owner_of(module.name) new_leaf = {'name':name, 'children':[], 'size':module.complexity, 'weight':knowledge.degree_of_ownership_for(module.name), 'author': owner, 'author_color':knowledge.color_of(owner)} hierarchy.append(new_leaf) return hierarchy def _insert_parts_into(hierarchy, module, knowledge, parts): """ Recursively traverse the hierarchy and insert the individual parts of the module, one by one. The parts specify branches. If any branch is missing, it's created during the traversal. The final part specifies a module name (sans its path, of course). This is where we add size and weight to the leaf. """ if len(parts) == 1: return _add_leaf(hierarchy, module, knowledge, name=parts[0]) next_branch = parts[0] existing_branch = _ensure_branch_exists(hierarchy, next_branch) return _insert_parts_into(existing_branch['children'], module, knowledge, parts=parts[1:]) def generate_structure_from(modules, knowledge): hierarchy = [] for module in modules: parts = module.parts() _insert_parts_into(hierarchy, module, knowledge, parts) structure = {'name':'root', 'children':hierarchy} return structure ###################################################################### ## Output ###################################################################### def write_json(result): print(json.dumps(result)) ###################################################################### ## Main ###################################################################### def run(args): authors_colors = dict(parse_csv(args.authors, expected_format='author,color', parse_action=parse_author_color)) module_ownership = parse_csv(args.owners, expected_format='entity,main-dev,removed,total-removed,ownership', parse_action=parse_ownership) structure_input = parse_csv(args.structure, expected_format='language,filename,blank,comment,code', parse_action=parse_structural_element) knowledge = Knowledge(authors_colors, module_ownership) knowledge_structure = generate_structure_from(structure_input, knowledge) write_json(knowledge_structure) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Generates a JSON document suitable for knowledge diagrams.') parser.add_argument('--structure', required=True, help='A CSV file generated by cloc') parser.add_argument('--owners', required=True, help='A CSV file generated by a Code Maat main-dev analysis') parser.add_argument('--authors', required=True, help='A CSV file specifying the color to use for each author') args = parser.parse_args() run(args) ================================================ FILE: test/code-compass-test.el ================================================ ;;; code-compass.el --- Tests for code-compass. ;; Copyright (C) 2020 Andrea Giugliano ;; Author: Andrea Giugliano ;; 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 . ;;; Commentary: ;; Tests for code-compass ;; ;;; Code: (ert-deftest c/expand-file-name_expanded-file-name () (let ((default-directory "/tmp") (code-compass-path-to-code-compass "somePath")) (should (string= (code-compass--expand-file-name "someFile") "/tmp/somePath/someFile")))) (defun utils/parse-string-as-time (date-string) "Parse DATE-STRING as time." (let ((l (parse-time-string date-string))) (encode-time 0 0 0 (nth 3 l) (nth 4 l) (nth 5 l))) ) (ert-deftest c/subtract-to-now_return-the-day-before () (should (string= (format-time-string "%Y-%m-%d" (code-compass--subtract-to-now 1 24 (utils/parse-string-as-time "2021-01-02"))) "2021-01-01"))) (ert-deftest c/request-date_git-date () (should (string= (code-compass-request-date "1d" (utils/parse-string-as-time "2021-01-02")) "2021-01-01"))) (ert-deftest c/temp-dir_give-temp-dir-for-analyses () (should (string= (code-compass--temp-dir "someRepo") "/tmp/code-compass-someRepo/"))) (ert-deftest c/in-temp-directory_run-in-directory () (should (string= (code-compass--in-temp-directory "someDir" default-directory) "/tmp/code-compass-someDir/"))) (ert-deftest c/calculate-complexity-stats_empty-stats () (should (string= (code-compass--calculate-complexity-stats "") nil))) (ert-deftest c/calculate-complexity-stats_return-stats () (should (equal (code-compass--calculate-complexity-stats " (let ((x 1)) (let ((y 2)) (let ((z 3))) (+ x y z)))") '((total . 6.0) (n-lines . 4) (max . 3.0) (mean . 1.5) (standard-deviation . 1.118033988749895) (used-indentation . 2))))) (ert-deftest c/add-filename-to-analysis-columns_prefix-lines () (should (equal (code-compass--add-filename-to-analysis-columns "someRepo" "some,analysis\nsomeEntry,someData\n\n") '("some,analysis" "someRepo/someEntry,someData")))) (ert-deftest c/sum-by-first-column_sums-rows-first-column () (should (equal (code-compass--sum-by-first-column '(("a" . 1) ("b" . 1) ("a" . 1) ("c" . 1) ("c" . 1) ("c" . 1))) '(("c" . 3) ("b" . 1) ("a" . 2))))) (ert-deftest c/word-stats_distribution-of-words () (should (equal (code-compass--word-stats "hi, hi, hi, hello, hello\nbla") '(("," . 4) ("hi" . 3) ("hello" . 2) ("bla" . 1))))) ;; Just evaluate buffer to run tests. (ert--stats-passed-expected (ert-run-tests 't (lambda (&rest args)))) ;;; code-compass ends here