pax_global_header00006660000000000000000000000064146427317630014527gustar00rootroot0000000000000052 comment=ab88ff4e08abcf8ede609bcf19ceac86484e5fca gophian/000077500000000000000000000000001464273176300125205ustar00rootroot00000000000000gophian/.gitignore000066400000000000000000000060251464273176300145130ustar00rootroot00000000000000man/*.1 /.pc/ # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ share/python-wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .nox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover *.py,cover .hypothesis/ .pytest_cache/ cover/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 db.sqlite3-journal # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder .pybuilder/ target/ # Jupyter Notebook .ipynb_checkpoints # IPython profile_default/ ipython_config.py # pyenv # For a library or package, you might want to ignore these files since the code is # intended to run in multiple environments; otherwise, check them in: # .python-version # pipenv # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. # However, in case of collaboration, if having platform-specific dependencies or dependencies # having no cross-platform support, pipenv may install dependencies that don't work, or not # install all needed dependencies. #Pipfile.lock # poetry # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. # This is especially recommended for binary packages to ensure reproducibility, and is more # commonly ignored for libraries. # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control #poetry.lock # pdm # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. #pdm.lock # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it # in version control. # https://pdm.fming.dev/#use-with-ide .pdm.toml # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm __pypackages__/ # Celery stuff celerybeat-schedule celerybeat.pid # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ .dmypy.json dmypy.json # Pyre type checker .pyre/ # pytype static type analyzer .pytype/ # Cython debug symbols cython_debug/ # PyCharm # JetBrains specific template is maintained in a separate JetBrains.gitignore that can # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore # and can be added to the global gitignore or merged into this file. For a more nuclear # option (not recommended) you can uncomment the following to ignore the entire idea folder. #.idea/ gophian/.pre-commit-config.yaml000066400000000000000000000006261464273176300170050ustar00rootroot00000000000000repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v3.2.0 hooks: - id: trailing-whitespace - id: end-of-file-fixer - repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.1.11 hooks: - id: ruff args: [ --fix ] - id: ruff-format # - repo: https://github.com/pre-commit/mirrors-mypy # rev: v1.8.0 # hooks: # - id: mypy gophian/CONTRIBUTING.md000066400000000000000000000047611464273176300147610ustar00rootroot00000000000000# Contributing All contributions are welcome, and they don't have to be code contributions! - [Issues](#issues) - [Hacking](#hacking) - [Documentation](#documentation) ## Issues Finding problems or missing features and reporting them to https://codeberg.org/Maytha8/gophian is greatly appreciated! If you don't have a Codeberg account and are not interested in creating one, then you can email me instead at `maytha8thedev@gmail.com` ## Hacking **Please see the NOTES below these instructions!** First of all, make sure to run `pre-commit install` Then: ```sh # with a venv sudo apt install python3-venv python3 -m venv .venv source .venv/bin/activate # or .venv/bin/activate.(fish|csh) pip install -e .[dev,graphviz] # or with pipx pipx install -e .[dev,graphviz] ``` All files in the gophian/ directory **MUST** have the copyright and license header (templates and license text files are exempt). So make sure to add it to any new files. You can copy it from the end of this document. ### NOTES The Session clones repos into `self.gopath`, but this **is not representative of nor usable as an actual GOPATH**. This is because packages are cloned according to **their repository root** and not the 'package' statement in go.mod. This means that packages such as `github.com/go-git/go-git/v5` will not be cloned in the correct location, but rather `GOPATH/src/github.com/go-git/go-git`. Do **NOT** rely on Session.gopath for running `go get`, `go build`, or `go install`. (You shouldn't need to run these commands anyway.) If there's a new feature that requires a correctly-structured GOPATH, please let me know so I can refactor the code accordingly. ## Documentation Manual pages are located in `man/` directory, and written in the scdoc format. ## Header ```txt # gophian -- tools to help with Debianizing Go software # Copyright (C) 2024 Maytham Alsudany # # 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 . ``` gophian/COPYING000066400000000000000000001045151464273176300135610ustar00rootroot00000000000000 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 . gophian/COPYING.md000066400000000000000000001041151464273176300141540ustar00rootroot00000000000000# 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 . gophian/MANIFEST.in000066400000000000000000000000571464273176300142600ustar00rootroot00000000000000graft gophian/licenses graft gophian/templates gophian/README.md000066400000000000000000000072621464273176300140060ustar00rootroot00000000000000# gophian **Tools to help with Debianizing Go software** > ⚠️ **Experimental software**, please report any issues to > https://codeberg.org/Maytha8/gophian/issues. Alternatively, you can email me > at `maytha8thedev@gmail.com`. In my experience, dh-make-golang is a little underfeatured and isn't very reliable. `dh-make-golang make` doesn't work half the time, it doesn't automatically fill in (Build-)Depends, and `dh-make-golang estimate` doesn't work at all ([Debian#1050523](https://bugs.debian.org/1050523), [Debian#1058936](https://bugs.debian.org/1058936)). This is because dh-make-golang still relies on the deprecated and removed golang.org/x/tools/go/vcs package to work out the root repo of import paths ([Debian#1043070](https://bugs.debian.org/1043070), [dh-make-golang#200](https://github.com/Debian/dh-make-golang/issues/200)). gophian seeks to change that, by avoiding the use of `go get` completely (and replicating it with the session module), and providing something that *just works*, as well as adding on more features and more intelligence. This CLI aims to be a full alternative to dh-make-golang. **Hey Go team,** what do you think of this tool? ## Features - `gophian make` - Check if the software has already been packaged for Debian, and whether it's on the Package Tracker or in the NEW queue. - Check for an ITP/RFP, tell you about it, and fill in debian/changelog - Check for a Salsa repo with the name of the source package - Uses Jinja templates for d/control, d/changelog, d/watch, and d/copyright instead of creating them inside the program. - Prompts you for package type. - Prompts you for source package name (if your package is binary-only or binary-and-library) - Asks you which binaries you'd like to include, ensuring that you can exclude testing binaries. - Extra short hostnames for websites like codeberg.org. - Check for unpackaged dependencies and warn about them, and optionally write them to a debian/TODO file. - `gophian estimate` - Reliable alternative to `dh-make-golang` - Can exclude packaged dependencies, giving you a TODO list of unpackaged Go libraries. - `gophian estimate-graphviz` (graphviz feature only) - Visualise the dependency tree using graphviz. ## Install gophian is available in [Debian unstable](https://tracker.debian.org/pkg/gophian). From git: ```sh pipx install git+https://codeberg.org/Maytha8/gophian.git # or with graphviz support pipx install git+https://codeberg.org/Maytha8/gophian.git[graphviz] ``` ## Runtime Dependencies This program requires `git`, `go`, and `git-buildpackage` in order to run. ## Optional Features - `graphviz` - enables the estimate-graphviz command ## Contributing See [CONTRIBUTING](./CONTRIBUTING.md). ## Contact Report any bugs or issues to https://codeberg.org/Maytha8/gophian/issues Alternatively, you can email me at `maytha8thedev@gmail.com`, or ping me via IRC on #debian-golang on irc.oftc.net, with nickname "maytham". ## License ``` gophian -- tools to help with Debianizing Go software Copyright (C) 2024 Maytham Alsudany 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 . ``` gophian/gophian/000077500000000000000000000000001464273176300141455ustar00rootroot00000000000000gophian/gophian/__about__.py000066400000000000000000000033471464273176300164340ustar00rootroot00000000000000# gophian -- tools to help with Debianizing Go software # Copyright (C) 2024 Maytham Alsudany # # 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 . VERSION = "0.3.0" COPYRIGHT_NOTICE = """gophian -- tools to help with Debianizing Go software Copyright (C) 2024 Maytham Alsudany 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 . On Debian systems, the full text of the GNU General Public License version 3 can be found at /usr/share/common-licenses/GPL-3""" REPO_URL = "https://codeberg.org/Maytha8/gophian" BUGS_URL = "https://codeberg.org/Maytha8/gophian/issues" gophian/gophian/__init__.py000066400000000000000000000013651464273176300162630ustar00rootroot00000000000000# gophian -- tools to help with Debianizing Go software # Copyright (C) 2024 Maytham Alsudany # # 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 . gophian/gophian/cli/000077500000000000000000000000001464273176300147145ustar00rootroot00000000000000gophian/gophian/cli/__init__.py000066400000000000000000000053231464273176300170300ustar00rootroot00000000000000# gophian -- tools to help with Debianizing Go software # Copyright (C) 2024 Maytham Alsudany # # 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 . from importlib.util import find_spec import click from requests.adapters import HTTPAdapter from requests_cache import CachedSession from urllib3.util.retry import Retry from gophian.__about__ import VERSION, COPYRIGHT_NOTICE from gophian.cli.create_salsa_repo import create_salsa_repo from gophian.cli.estimate import estimate from gophian.cli.make import make from gophian.cli.search import search from gophian.cli.show import show from gophian.cli.license_text import license_text def print_version(ctx: click.Context, _, value: bool) -> None: if not value or ctx.resilient_parsing: return click.echo(VERSION) ctx.exit() def print_copyright(ctx: click.Context, _, value: bool) -> None: if not value or ctx.resilient_parsing: return click.echo(COPYRIGHT_NOTICE) ctx.exit() @click.group() @click.option( "--version", is_flag=True, callback=print_version, expose_value=False, is_eager=True, help="Print version and exit.", ) @click.option( "--copyright", is_flag=True, callback=print_copyright, expose_value=False, is_eager=True, help="Print copyright notice and exit.", ) @click.pass_context def cli(ctx: click.Context) -> None: """ Tools to help with Debianizing Go software. """ session = CachedSession( "gophian", backend="sqlite", expire_after=60 * 60, use_cache_dir=True, allowable_methods=["HEAD", "GET"], ) retries = Retry( total=5, backoff_factor=0.1, status_forcelist=[502, 503, 504], allowed_methods={"GET", "HEAD", "POST"}, ) session.mount("https://", HTTPAdapter(max_retries=retries)) ctx.obj = session cli.add_command(estimate) cli.add_command(make) cli.add_command(create_salsa_repo) cli.add_command(search) cli.add_command(show) cli.add_command(license_text) if find_spec("graphviz"): from gophian.cli.estimate_graphviz import estimate_graphviz cli.add_command(estimate_graphviz) gophian/gophian/cli/create_salsa_repo.py000066400000000000000000000052151464273176300207440ustar00rootroot00000000000000# gophian -- tools to help with Debianizing Go software # Copyright (C) 2024 Maytham Alsudany # # 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 . from pathlib import Path from typing import Optional import click import requests @click.command() @click.argument("project", required=False) @click.pass_context def create_salsa_repo(context: click.Context, project: Optional[str]) -> None: """ Create a Salsa repo within the Debian Go Package Team. If no project name is passed, this checks if the 'Source' field has been defined in a debian/control file, and uses that instead. """ session: requests.Session = context.obj if project is not None: repo = project elif name := package_name_from_control(): repo = name else: click.secho( "No project argument passed, and no debian/control file found with source package defined.", fg="red", ) context.exit(1) if "/" in repo: click.secho("Repo name must not contain slashes.", fg="red") context.exit(1) res = session.post( "https://pgt-api-server.debian.net/v1/createrepo", params={"repo": repo} ) if res.status_code == 200: click.secho( "Repo created successfully at https://salsa.debian.org/go-team/packages/" + repo, fg="green", bold=True, ) elif res.status_code == 403: click.secho( "Repository creation has been disabled; please see the mailing list (debian-go@lists.debian.org)", fg="red", ) else: click.secho( f"An unknown problem occurred; status code {res.status_code} recieved.", fg="red", ) def package_name_from_control() -> Optional[str]: control = Path("debian/control") if control.exists(): with control.open("r") as file: line = next(file) if line.startswith("Source:"): return line[7:].strip() else: return None else: return None gophian/gophian/cli/estimate.py000066400000000000000000000147501464273176300171100ustar00rootroot00000000000000# gophian -- tools to help with Debianizing Go software # Copyright (C) 2024 Maytham Alsudany # # 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 . from typing import List, Optional import click import requests from treelib import Tree from gophian.__about__ import BUGS_URL from gophian.error import ExecutionError from gophian.packages import DebianGolangPackages from gophian.session import Session from gophian.vcs import package_from_import_path @click.command() @click.argument("importpath") @click.option("--quiet/--no-quiet", default=False, help="Don't print warnings.") @click.option( "--warn-packaged/--no-warn-packaged", default=True, help="Warn if the given Go package has already been packaged for Debian.", ) @click.option( "--include-packaged-deps/--no-include-packaged-deps", default=True, help="Include packaged dependencies in the estimate.", ) @click.option( "--include-version-conflicts/--no-include-version-conflicts", default=False, help=( "Include any version conflicts between the package's go.mod and the" "version in Debian unstable. Ignored if --no-include-packaged-deps is" "passed." ), ) @click.option( "--max-depth", required=False, help="Maximum recursion depth of unpackaged dependencies.", ) @click.pass_context def estimate( context: click.Context, importpath: str, quiet: bool, warn_packaged: bool, include_packaged_deps: bool, include_version_conflicts: bool, max_depth: Optional[int], ) -> None: """ Estimate work required to Debianize a given Go package. """ requests_session: requests.Session = context.obj if not quiet: click.secho("gophian is experimental software!", bold=True, fg="yellow") click.secho("Please report any problems to:", fg="yellow") click.secho(BUGS_URL, fg="yellow") try: package, _ = package_from_import_path(requests_session, importpath) except Exception as error: click.echo(error) click.secho("Did you specify a Go package import path?", fg="yellow") context.exit(1) if package != importpath: click.echo(f"Continuing with repo root {package} instead of {importpath}") debian_packages = DebianGolangPackages(requests_session) if debian_packages._check_for_package(package, quiet) and warn_packaged: if not quiet: click.secho("To ignore, pass the --no-warn-packaged flag.", fg="cyan") return with Session(requests_session) as session: seen: List[str] = [] errors: List[ExecutionError] = [] tree = Tree() tree.create_node(package, package) dependency_tree( session, seen, errors, package, include_packaged_deps, include_version_conflicts, debian_packages, tree, max_depth, ) click.echo(tree.show(stdout=False)) for error in errors: click.echo(error) def dependency_tree( session: Session, seen: List[str], errors: List[ExecutionError], package: str, include_packaged_deps: bool, include_version_conflicts: bool, debian_packages: DebianGolangPackages, tree: Tree, max_depth: Optional[int], level: int = 1, ): try: go_package = session.go_get(package) dep_packages = go_package.find_dependencies() except ExecutionError as error: errors.append(error) tree.create_node( click.style("Error getting dependencies", fg="red"), f"{package}_error", parent=package, ) return for dep_package, _ in dep_packages: if ( (result := debian_packages.library_is_packaged(dep_package)) and (debian_package := result[0]) and (debian_package_version := result[1]) ): if include_packaged_deps: node_text = click.style( f"{dep_package} ({debian_package})", fg="green", ) if include_version_conflicts: [go_mod_major, go_mod_minor] = go_package.deps[ dep_package ].vstring.split(".")[:2] [debian_major, debian_minor] = debian_package_version.vstring.split( "." )[:2] if ( ( go_package.deps[dep_package].commit and go_package.deps[dep_package].vstring != debian_package_version.vstring ) or (go_mod_major != debian_major) or (go_mod_major == 0 and go_mod_minor != debian_minor) ): node_text += click.style( f" [{debian_package_version} ≠ {go_package.deps[dep_package]}]", fg="yellow", ) tree.create_node( node_text, f"{package}_{dep_package}", parent=package, ) elif dep_package in seen: tree.create_node( f"{dep_package}", f"{package}_{dep_package}", parent=package, ) elif max_depth is None or (level + 1) > max_depth: tree.create_node( dep_package, dep_package, parent=package, ) seen.append(dep_package) dependency_tree( session, seen, errors, dep_package, include_packaged_deps, include_version_conflicts, debian_packages, tree, max_depth, level + 1, ) gophian/gophian/cli/estimate_graphviz.py000066400000000000000000000174711464273176300210250ustar00rootroot00000000000000# gophian -- tools to help with Debianizing Go software # Copyright (C) 2024 Maytham Alsudany # # 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 . from pathlib import Path from typing import List, Optional import click import graphviz import requests from graphviz.dot import Dot from gophian.__about__ import BUGS_URL from gophian.error import ExecutionError from gophian.hosts import KNOWN_HOSTS from gophian.name import debianize_name, shorten_host from gophian.packages import DebianGolangPackages from gophian.session import Session from gophian.vcs import package_from_import_path @click.command() @click.argument("importpath") @click.argument( "source_output", type=click.Path(exists=False, writable=True), required=False ) @click.option("--quiet/--no-quiet", default=False, help="Don't print warnings.") @click.option( "--open/--no-open", "should_open", default=True, help=( "View the rendered output in the most suitable application. Ignore if" "--no-render is passed." ), ) @click.option( "--render/--no-render", default=True, help="Render the graph using graphviz.", ) @click.option( "--warn-packaged/--no-warn-packaged", default=True, help="Warn if the given Go package has already been packaged for Debian.", ) @click.option( "--include-packaged-deps/--no-include-packaged-deps", default=True, help="Include packaged dependencies in the estimate.", ) @click.option( "--include-version-conflicts/--no-include-version-conflicts", default=False, help=( "Include any version conflicts between the package's go.mod and the" "version in Debian unstable. Ignored if --no-include-packaged-deps is" "passed." ), ) @click.option( "--max-depth", required=False, help="Maximum recursion depth of unpackaged dependencies.", ) @click.pass_context def estimate_graphviz( context: click.Context, importpath: str, source_output: Optional[Path], quiet: bool, should_open: bool, render: bool, warn_packaged: bool, include_packaged_deps: bool, include_version_conflicts: bool, max_depth: Optional[int], ) -> None: """ Visualize the dependency tree of a given Go package. """ requests_session: requests.Session = context.obj if not quiet: click.secho("gophian is experimental software!", bold=True, fg="yellow") click.secho("Please report any problems to:", fg="yellow") click.secho(BUGS_URL, fg="yellow") try: package, _ = package_from_import_path(requests_session, importpath) except Exception as error: click.echo(error) click.secho("Did you specify a Go package import path?", fg="yellow") context.exit(1) if package != importpath: click.echo(f"Continuing with repo root {package} instead of {importpath}") debian_packages = DebianGolangPackages(requests_session) if debian_packages._check_for_package(package, quiet) and warn_packaged: if not quiet: click.secho("To ignore, pass the --no-warn-packaged flag.", fg="cyan") return with Session(requests_session) as session: seen: List[str] = [] errors: List[ExecutionError] = [] dot = graphviz.Digraph() dot.attr("graph", ratio="fill", size="180,30!", margin="0") dot.node( "comment", "Node colours\\nWhite: not packaged\\nGreen: packaged", shape="none", ) dot.node(package, package) dependency_tree( session, seen, errors, package, include_packaged_deps, include_version_conflicts, debian_packages, dot, max_depth, ) if not source_output: host = package.split("/")[0] short_host = ( KNOWN_HOSTS[host] if host in KNOWN_HOSTS else shorten_host(host) ) name = debianize_name(package, short_host) source_output = Path(name + ".gv") if render: output = source_output.with_suffix(".pdf") dot.render( source_output, view=should_open, format="pdf", outfile=output, overwrite_source=True, ) else: dot.save(source_output) for error in errors: click.echo(error) def dependency_tree( session: Session, seen: List[str], errors: List[ExecutionError], package: str, include_packaged_deps: bool, include_version_conflicts: bool, debian_packages: DebianGolangPackages, dot: Dot, max_depth: Optional[int], level: int = 1, ): try: go_package = session.go_get(package) dep_packages = go_package.find_dependencies() except ExecutionError as error: errors.append(error) click.secho("Error getting dependencies for " + package, fg="red") dot.node(package, package + "\\n(Error getting dependencies)") return for dep_package, _ in dep_packages: if ( (result := debian_packages.library_is_packaged(dep_package)) and (debian_package := result[0]) and (debian_package_version := result[1]) ): if include_packaged_deps: if dep_package not in seen: dot.node( dep_package, f"{dep_package}\\n({debian_package})", fillcolor="green", style="filled", ) label = "" if include_version_conflicts: [go_mod_major, go_mod_minor] = go_package.deps[ dep_package ].vstring.split(".")[:2] [debian_major, debian_minor] = debian_package_version.vstring.split( "." )[:2] if ( ( go_package.deps[dep_package].commit and go_package.deps[dep_package].vstring != debian_package_version.vstring ) or (go_mod_major != debian_major) or (go_mod_major == 0 and go_mod_minor != debian_minor) ): label = ( f"{debian_package_version} ≠ {go_package.deps[dep_package]}" ) dot.edge(package, dep_package, label=label) if dep_package not in seen: seen.append(dep_package) elif dep_package in seen: dot.edge(package, dep_package) elif max_depth is None or (level + 1) > max_depth: dot.node(dep_package, fillcolor="white", style="filled") dot.edge(package, dep_package) seen.append(dep_package) dependency_tree( session, seen, errors, dep_package, include_packaged_deps, include_version_conflicts, debian_packages, dot, max_depth, level + 1, ) gophian/gophian/cli/license_text.py000066400000000000000000000023011464273176300177500ustar00rootroot00000000000000# gophian -- tools to help with Debianizing Go software # Copyright (C) 2024 Maytham Alsudany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import click from gophian.licenses import KNOWN_LICENSES, fetch_license_text @click.command() @click.argument( "lic", metavar="LICENSE", required=True, type=click.Choice(list(KNOWN_LICENSES.values()), case_sensitive=False), ) def license_text(lic: str) -> None: """ Print a license text stanza suitable for inclusion in a DEP-5 d/copyright file. """ click.echo(f"License: {lic}") click.echo(fetch_license_text(lic)) gophian/gophian/cli/make.py000066400000000000000000000767411464273176300162220ustar00rootroot00000000000000# gophian -- tools to help with Debianizing Go software # Copyright (C) 2024 Maytham Alsudany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import re import subprocess import xml.etree.ElementTree as ET from datetime import datetime from enum import Enum, auto from pathlib import Path from shutil import move from typing import List, Optional, Tuple, cast from urllib.parse import urlparse import click import questionary import requests from jinja2 import Environment, PackageLoader, select_autoescape from gophian.__about__ import BUGS_URL from gophian.error import GbpExecutionError, UscanExecutionError from gophian.git import Git from gophian.hosts import KNOWN_HOSTS from gophian.name import debianize_name, shorten_host from gophian.packages import DebianGolangPackages from gophian.salsa import salsa_repo_exists from gophian.session import Session from gophian.vcs import get_short_desc, package_from_import_path from gophian.wnpp import ITPBug, RFPBug @click.command() @click.argument("importpath") @click.option("--quiet/--no-quiet", default=False, help="Don't print warnings.") @click.option( "--type", "package_type_opt", required=False, type=click.Choice(["l", "l+b", "b+l", "b"], case_sensitive=False), help="Type of software being packaged.", ) @click.option( "--name", required=True, envvar="DEBFULLNAME", help="Name of package maintainer. Uses DEBFULLNAME environment variable by default.", ) @click.option( "--email", required=True, envvar="DEBEMAIL", help="Email of package maintainer. Uses DEBEMAIL environment variable by default.", ) @click.option( "--warn-packaged/--no-warn-packaged", default=True, help="Warn if the given import path is already packaged in Debian.", ) @click.option( "--warn-salsa-repo/--no-warn-salsa-repo", default=True, help="Warn if the package already has a repo under the Go team namespace on Salsa.", ) @click.option( "--itp/--no-itp", default=True, help="Generate an ITP template as well.", envvar="GOPHIAN_ITP", ) @click.option( "--todo/--no-todo", default=False, help="Generate a debian/TODO file.", envvar="GOPHIAN_TODO", ) @click.option( "--git-remote", default="ssh", type=click.Choice(["ssh", "https"], case_sensitive=False), help="Protocol to use when setting Git remote.", envvar="GOPHIAN_GIT_REMOTE", ) @click.option( "--gpg-sign/--no-gpg-sign", envvar="GOPHIAN_GPG_SIGN", help=( "GPG sign the commit that merges the upstream tarball into the" "packaging branch. If not passed to Gophian, then it will not be passed" "to git nor gbp and they will use their configured defaults." ), ) @click.pass_context def make( context: click.Context, importpath: str, quiet: bool, package_type_opt: Optional[str], name: str, email: str, warn_packaged: bool, warn_salsa_repo: bool, itp: bool, todo: bool, git_remote: str, gpg_sign: Optional[bool], ): """ Prepare a Go module for packaging in Debian. """ requests_session: requests.Session = context.obj if not quiet: click.secho("gophian is experimental software!", bold=True, fg="yellow") click.secho("Please report any problems to:", fg="yellow") click.secho(BUGS_URL, fg="yellow") with MakeSession(requests_session) as session: try: go_package, git_repo = package_from_import_path( requests_session, importpath ) except Exception as error: click.echo(error) click.secho("Did you specify a Go package import path?", fg="yellow") context.exit(1) if go_package != importpath: click.echo( f"Continuing with repo root {go_package} instead of {importpath}" ) debian_packages = DebianGolangPackages(requests_session) if debian_packages._check_for_package(go_package): if warn_packaged: if not quiet: click.secho( "Pass --no-warn-packaged to ignore this warning and continue.", fg="cyan", ) return host = go_package.lower().split("/")[0] if host in KNOWN_HOSTS: short_host = KNOWN_HOSTS[host] else: short_host = shorten_host(host) if not quiet: click.secho( f"Using '{short_host}' as canoncial hostname for '{host}'", fg="yellow", ) click.secho( "If this is not suitable, please change it manually and report the issue to https://salsa.debian.org/Maytha8/gophian/issues", fg="yellow", ) debian_source_package = debianize_name(go_package, short_host) debian_library_package = debian_source_package + "-dev" try: all_binaries: List[str] = session.package_main_modules(go_package) except Exception: all_binaries: List[str] = session.find_main_modules(go_package) if not quiet and len(all_binaries) > 0: click.echo("Found binaries:") for binary in all_binaries: click.echo(f" - {binary.split('/')[-1]} ({binary})") wnpp = None binary_word = "binaries" if len(all_binaries) > 1 else "binary" if package_type_opt is not None: package_type: PackageType = PackageType.from_opt(package_type_opt) elif len(all_binaries) == 0: package_type: PackageType = PackageType.LIBRARY else: package_type: PackageType = questionary.select( "What type of software are you packaging?", choices=[ questionary.Choice( "Library only", value=PackageType.LIBRARY, checked=True ), questionary.Choice( f"Library and accompanying {binary_word}", value=PackageType.LIBRARY_AND_BINARY, ), questionary.Choice( f"{binary_word.capitalize()} and accompanying library", value=PackageType.BINARY_AND_LIBRARY, ), questionary.Choice( f"{binary_word.capitalize()} only", value=PackageType.BINARY ), ], ).ask() if package_type is None: raise click.Abort() selected_binaries: List[str] = [] if package_type.has_binary(): if len(all_binaries) > 1: binary_choices: List[questionary.Choice] = list( map( lambda b: questionary.Choice( f"{b.split('/')[-1]} ({b})", value=b ), all_binaries, ) ) selected_binaries = questionary.checkbox( "Which binaries would you like to include?", choices=binary_choices ).ask() if selected_binaries is None: raise click.Abort() else: selected_binaries = all_binaries if ( package_type == PackageType.BINARY_AND_LIBRARY or package_type == PackageType.BINARY ): choices: List[str] = list( map(lambda b: b.split("/")[-1], selected_binaries) ) if git_repo.split("/")[-1] not in choices: choices.insert(0, git_repo.split("/")[-1]) choices.insert(0, debian_source_package) debian_source_package = questionary.select( "What do you want to name the source package?", choices=choices ).ask() if debian_source_package is None: raise click.Abort() if not quiet and salsa_repo_exists( requests_session, "go-team/packages/" + debian_source_package ): click.secho( f"Salsa repo of the same name exists for '{debian_source_package}'.", fg="yellow", ) click.echo( f"https://salsa.debian.org/go-team/packages/{debian_source_package}" ) if warn_salsa_repo: click.secho("To ignore, pass the --no-warn-salsa-repo flag.", fg="cyan") return if bug := ITPBug.get(requests_session, debian_source_package): wnpp = bug if not quiet: click.secho(f"Found wnpp bug for {debian_source_package}", fg="cyan") click.secho( f"[#{bug.id}] ITP: {bug.package} -- {bug.description}", fg="cyan" ) elif bug := RFPBug.get(requests_session, debian_source_package): wnpp = bug if not quiet: click.secho(f"Found wnpp bug for {debian_source_package}", fg="cyan") click.secho( f"[#{bug.id}] RFP: {bug.package} -- {bug.description}", fg="cyan" ) work_dir = Path(debian_source_package) if work_dir.exists(): click.secho( f"Output directory '{work_dir}' already exists", fg="red", ) context.exit(1) work_dir.mkdir() env = Environment( loader=PackageLoader("gophian"), autoescape=select_autoescape(), trim_blocks=True, lstrip_blocks=True, keep_trailing_newline=True, ) version, repack, watchfile, tarball = session.prepare_upstream( env, go_package, debian_source_package, ) tarball = move(tarball, work_dir.parent / tarball.name) repo = Git.init(work_dir, "debian/sid", quiet=quiet) if git_remote == "ssh": repo.remote( f"git@salsa.debian.org:go-team/packages/{debian_source_package}.git" ) elif git_remote == "https": repo.remote( f"https://salsa.debian.org/go-team/packages/{debian_source_package}.git" ) cmd = [ "gbp", "import-orig", "--no-interactive", "--debian-branch=debian/sid", "--filter=/debian/**/*", tarball.absolute(), ] if gpg_sign is not None: cmd.append("--sign-tags" if gpg_sign else "--no-sign-tags") out = subprocess.run( cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, cwd=repo.path, ) if out.returncode != 0: raise GbpExecutionError(out) with open(work_dir / ".gitignore", "a") as file: file.write("\n/.pc/\n/_build/") repo.add([".gitignore"]) repo.commit("Add quilt and build directories to gitignore", gpg_sign=gpg_sign) debian_deps = [] debian_build_deps = [ "debhelper-compat (= 13)", "dh-sequence-golang", "golang-any", ] missing_deps = [] missing_test_deps = [] try: pkg = session.go_get(go_package) go_deps = pkg.find_dependencies() for dep, _ in go_deps: if (result := debian_packages.library_is_packaged(dep)) and ( debian_package := result[0] ): debian_deps.append(debian_package) else: missing_deps.append(dep) debian_build_deps += debian_deps go_test_deps = pkg.find_dependencies(True) for dep, _ in go_test_deps: if dep in go_deps: continue elif (result := debian_packages.library_is_packaged(dep)) and ( debian_package := result[0] ): if debian_package not in debian_deps: debian_build_deps.append(debian_package + " ") else: continue else: missing_test_deps.append(dep) except Exception as e: click.echo(e) click.secho( "An error occurred fetching dependencies, skipping...", fg="red" ) if not quiet: for dep in missing_deps: click.secho(f"Dependency {dep} is not packaged in Debian!", fg="yellow") for dep in missing_test_deps: click.secho( f"Test dependency {dep} is not packaged in Debian!", fg="yellow", ) short_desc = get_short_desc(requests_session, git_repo) if (work_dir / "go.mod").exists(): PACKAGE_NAME_REGEX = re.compile(r"^module (\S+)$") match = PACKAGE_NAME_REGEX.search((work_dir / "go.mod").read_text()) if match: go_import_path = match.group(1) else: go_import_path = go_package else: go_import_path = go_package (work_dir / "debian").mkdir() header_template = env.get_template("control/header.jinja") control_stanzas = [] control_stanzas.append( header_template.render( source=debian_source_package, uploaders=f"{name} <{email}>", lib_deps=debian_build_deps, homepage=git_repo, go_import_path=go_import_path, ).strip() ) match package_type: case PackageType.LIBRARY: control_stanzas.append( render_library_package( env, debian_library_package, short_desc, debian_deps ) ) case PackageType.BINARY: for binary in selected_binaries: control_stanzas.append( render_binary_package(env, binary.split("/")[-1], short_desc) ) case PackageType.LIBRARY_AND_BINARY: control_stanzas.append( render_library_package( env, debian_library_package, short_desc, debian_deps ) ) for binary in selected_binaries: control_stanzas.append( render_binary_package(env, binary.split("/")[-1], short_desc) ) case PackageType.BINARY_AND_LIBRARY: for binary in selected_binaries: control_stanzas.append( render_binary_package(env, binary.split("/")[-1], short_desc) ) control_stanzas.append( render_library_package( env, debian_library_package, short_desc, debian_deps ) ) control = "\n\n".join(control_stanzas) + "\n" with (work_dir / "debian/control").open("x") as file: file.write(control) copyr_template = env.get_template("copyright.jinja") with (work_dir / "debian/copyright").open("x") as file: file.write( copyr_template.render( license="TODO", license_text=( " TODO: You can use 'gophian license-text ' to print a license text\n" " stanza suitable for inclusion in this DEP-5 copyright file." ), year=datetime.now().strftime("%Y"), name=name, email=email, homepage=git_repo, upstream_name=go_package.split("/")[-1], repack=repack, ) ) changelog_template = env.get_template("changelog.jinja") with (work_dir / "debian/changelog").open("x") as file: file.write( changelog_template.render( source=debian_source_package, debian_version=version + "-1", bug=f"#{wnpp.id}" if wnpp is not None else "TODO", name=name, email=email, date=datetime.now().strftime("%a, %d %b %Y %H:%M:%S") + " " + datetime.utcnow().astimezone().strftime("%z")[:5], ) ) with (work_dir / "debian/.gitignore").open("x") as file: file.write( "*.debhelper\n" "*.log\n" "*.substvars\n" "/.debhelper/\n" "/debhelper-build-stamp/\n" "/files\n" ) if package_type.has_binary(): for binary in selected_binaries: file.write("/" + binary.split("/")[-1] + "/\n") if package_type.has_library(): file.write("/" + debian_library_package + "/\n") with (work_dir / "debian/rules").open("x") as file: file.write( "#!/usr/bin/make -f\n" "\n" "%:\n" "\tdh $@ --builddirectory=_build --buildsystem=golang\n" ) if package_type == PackageType.BINARY: file.write( "\n" "override_dh_auto_install:\n" "\tdh_auto_install -- --no-source\n" ) (work_dir / "debian/rules").chmod(0o0755) (work_dir / "debian/source").mkdir() with (work_dir / "debian/source/format").open("x") as file: file.write("3.0 (quilt)\n") with (work_dir / "debian/gbp.conf").open("x") as file: file.write("[DEFAULT]\n" "debian-branch = debian/sid\n" "dist = DEP14\n") if ( package_type == PackageType.BINARY_AND_LIBRARY or package_type == PackageType.LIBRARY_AND_BINARY ): with (work_dir / f"debian/{debian_library_package}.install").open( "x" ) as file: file.write("usr/share\n") if len(selected_binaries) > 1: for binary in selected_binaries: with (work_dir / f"debian/{binary.split('/')[-1]}.install").open( "x" ) as file: file.write(f"usr/bin/{binary.split('/')[-1]}\n") else: with ( work_dir / f"debian/{selected_binaries[0].split('/')[-1]}.install" ).open("x") as file: file.write("usr/bin\n") move(watchfile, work_dir / "debian/watch") (work_dir / "debian/upstream").mkdir() with (work_dir / "debian/upstream/metadata").open("x") as file: file.write(gen_debian_upstream_metadata(git_repo)) with (work_dir / "debian/gitlab-ci.yml").open("x") as file: file.write( """# auto-generated, DO NOT MODIFY. # The authoritative copy of this file lives at: # https://salsa.debian.org/go-team/infra/pkg-go-tools/blob/master/config/gitlabciyml.go --- include: - https://salsa.debian.org/go-team/infra/pkg-go-tools/-/raw/master/pipeline/test-archive.yml """ ) if itp: itp_template = env.get_template("itp.jinja") itp_path = Path("itp.txt") if itp_path.exists(): if not quiet: click.secho( "Could not generate an ITP template as itp.txt already exists. Skipping..." ) else: with itp_path.open("x") as file: file.write( itp_template.render( name=name, email=email, package=debian_source_package, short_desc=short_desc, long_desc=( "TODO: long description, what you'd write in debian/control\n" " keep it indented, just like in the control file" ), version=version, upstream="TODO", url=git_repo, license="TODO", ) ) if todo: with (work_dir / "debian/TODO").open("x") as file: file.write( "\n".join( [ debian_source_package, "=" * len(debian_source_package), "", "Resolve all the TODOs in debian/, find them using:", " grep -r TODO debian/", "\n", ] ) ) if len(missing_deps) > 0: file.write( "There are some missing dependencies not packaged for Debian yet:\n" ) for dep in missing_deps: file.write(" - " + dep + "\n") file.write("\n") if len(missing_test_deps) > 0: file.write( "There are some missing test dependencies not packaged for Debian yet:\n" ) for dep in missing_test_deps: file.write(" - " + dep + "\n") file.write("\n") file.write( "\n".join( [ "To build the package, its recommended to use sbuild.", "See https://wiki.debian.org/sbuild#Setup for setup instructions.", "", "When you finish packaging, delete debian/TODO:", " rm debian/TODO", "and commit your changes:", " git add debian && git commit -S -m 'Initial packaging'", "", "To create the packaging repo on Salsa, use:", " gophian create-salsa-repo " + debian_source_package, "", "Once you are happy with your work, push to Salsa:", " git push --all --follow-tags", " # or", " gbp push", "", "If you need any help, feel free to send a mail to debian-go@lists.debian.org or", "send a message on the #debian-golang IRC channel on the OFTC network.", ] ) ) if quiet: return click.secho( "Packaging prepared successfully in " + str(work_dir), bold=True, fg="green", ) click.echo("") if todo: click.secho( "\n".join( [ "A debian/TODO file has been generated for you containing the same information", "here as well as any dependencies that have not been packaged in Debian.", ] ), fg="blue", ) click.echo("") click.echo("Resolve all the TODOs in debian/, find them using:") click.echo(" grep -r TODO debian/") click.echo("") click.echo("To build the package, its recommended to use sbuild.") click.echo("See https://wiki.debian.org/sbuild#Setup for setup instructions.") click.echo("") if todo: click.echo("When you finish packaging, delete debian/TODO:") click.echo(" rm debian/TODO") click.echo("and commit your changes:") click.echo(" git add debian && git commit -S -m 'Initial packaging'") else: click.echo("When you finish packaging, commit your changes:") click.echo(" git add debian && git commit -S -m 'Initial packaging'") click.echo("") click.echo("To create the packaging repo on Salsa, use:") click.echo(" gophian create-salsa-repo " + debian_source_package) click.echo("") click.echo("Once you are happy with your work, push to Salsa:") click.echo(" git push --all --follow-tags") click.echo(" # or") click.echo(" gbp push") click.echo("") click.echo( "If you need any help, feel free to send a mail to debian-go@lists.debian.org or" ) click.echo( "send a message on the #debian-golang IRC channel on the OFTC network." ) click.echo("") # Print experimental warning again, in case the logs drowned it out the first time. click.secho("gophian is experimental software!", bold=True, fg="yellow") click.secho("Please report any problems to:", fg="yellow") click.secho(BUGS_URL, fg="yellow") def gen_debian_watch(env: Environment, repo: str, versioned: bool, repack: bool) -> str: url = urlparse(repo) if versioned: if url.hostname == "github.com": template = env.get_template("watch/github.jinja") return template.render(repo=repo, repack=repack) template = env.get_template("watch/git_tags.jinja") return template.render(repo=repo, repack=repack) else: template = env.get_template("watch/git_commits.jinja") return template.render(repo=repo, repack=repack) def gen_debian_upstream_metadata(repo: str) -> str: url = urlparse(repo) if url.hostname == "github.com" or url.hostname == "codeberg.org": if url_exists(repo + "/issues"): return ( "Bug-Database: " + repo + "/issues\n" "Bug-Submit: " + repo + "/issues/new\n" "Repository: " + repo + ".git\n" "Repository-Browse: " + repo + "\n" ) else: return "Repository: " + repo + ".git\n" "Repository-Browse: " + repo + "\n" if url.hostname == "gitlab.com" or url.hostname == "salsa.debian.org": if url_exists(repo + "/-/issues"): return ( "Bug-Database: " + repo + "/-/issues\n" "Bug-Submit: " + repo + "/-/issues/new\n" "Repository: " + repo + ".git\n" "Repository-Browse: " + repo + "\n" ) else: return "Repository: " + repo + ".git\n" "Repository-Browse: " + repo + "\n" return ( "Bug-Database: TODO\n" "Bug-Submit: TODO\n" "Repository: " + repo + ".git\n" "Repository-Browse: " + repo + "\n" ) def url_exists(url: str) -> bool: res = requests.head(url, timeout=60) return res.status_code == 200 def render_library_package( env: Environment, package: str, short_desc: str, lib_deps: List[str] ) -> str: library_template = env.get_template("control/go_library.jinja") return library_template.render( package=package, lib_deps=lib_deps, short_desc=short_desc, ).strip() def render_binary_package(env: Environment, package: str, short_desc: str) -> str: binary_template = env.get_template("control/go_binary.jinja") return binary_template.render( package=package, short_desc=short_desc, ).strip() class PackageType(Enum): LIBRARY = auto() BINARY = auto() LIBRARY_AND_BINARY = auto() BINARY_AND_LIBRARY = auto() @classmethod def from_opt(cls, opt: str): match opt: case "l": return cls.LIBRARY case "b": return cls.BINARY case "l+b": return cls.LIBRARY_AND_BINARY case "b+l": return cls.BINARY_AND_LIBRARY case _: return cls.LIBRARY def has_library(self) -> bool: return ( self == self.__class__.LIBRARY or self == self.__class__.LIBRARY_AND_BINARY or self == self.__class__.BINARY_AND_LIBRARY ) def has_binary(self) -> bool: return ( self == self.__class__.BINARY or self == self.__class__.LIBRARY_AND_BINARY or self == self.__class__.BINARY_AND_LIBRARY ) class MakeSession(Session): def find_main_modules(self, go_package: str) -> List[str]: self.go_get(go_package) repo_path = self.gopath / "src" / go_package PACKAGE_REGEX = re.compile(r"^package main$") main_modules: List[str] = [] for path in repo_path.rglob("*.go"): with path.open() as file: for line in file: if line.strip() == "": continue elif match := PACKAGE_REGEX.match(line): print(path, match) module = path.parent.relative_to(repo_path) if str(module) not in main_modules: main_modules.append(str(module)) else: break return main_modules def prepare_upstream( self, env: Environment, go_package: str, source_package: str ) -> Tuple[str, bool, Path, Path]: repo = self.go_get(go_package) watch_path = self.tempdir.path / f"{source_package}_watch" repack = (repo.path / "vendor").exists() version = repo.debianized_version if repack: version += "+ds" with watch_path.open("x") as file: file.write(gen_debian_watch(env, repo.repo, repo.versioned, repack)) uscan_args = [ "uscan", "-dd", "--dehs", "--rename", "--destdir", ".", "--watchfile", watch_path, "--package", source_package, "--upstream-version", "0~~", ] if repack: copyright_path = self.tempdir.path / f"{source_package}_copyright" with copyright_path.open("x") as file: file.write( "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n" "Files-Excluded: vendor" ) uscan_args += ["--copyright-file", copyright_path] out = subprocess.run( uscan_args, capture_output=True, cwd=self.tempdir.path, ) if out.returncode != 0: raise UscanExecutionError(out) xml_root = ET.fromstring(out.stdout.decode()) target_path = cast(str, cast(ET.Element, xml_root.find("target-path")).text) tarball_path = self.tempdir.path / Path(target_path) return (version, repack, watch_path, tarball_path) gophian/gophian/cli/search.py000066400000000000000000000026761464273176300165460ustar00rootroot00000000000000# gophian -- tools to help with Debianizing Go software # Copyright (C) 2024 Maytham Alsudany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import click import requests from gophian.packages import DebianGolangPackages @click.command() @click.argument("query") @click.pass_context def search(context: click.Context, query: str): """ Search Debian Go packages by name and import path. """ session: requests.Session = context.obj packages = DebianGolangPackages(session) for package in filter( lambda p: query in p["source"] or query in p["binary"] or query in p["metadata_value"], packages.packages, ): importpaths = list( map(lambda x: x.strip(), package["metadata_value"].split(",")) ) click.echo(package["binary"] + " -- " + ", ".join(importpaths)) gophian/gophian/cli/show.py000066400000000000000000000033031464273176300162450ustar00rootroot00000000000000# gophian -- tools to help with Debianizing Go software # Copyright (C) 2024 Maytham Alsudany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import click import requests from gophian.packages import DebianGolangPackages @click.command() @click.argument("query") @click.pass_context def show(context: click.Context, query: str): """ Show Debian Go package by name or import path. """ session: requests.Session = context.obj packages = DebianGolangPackages(session) package = next( filter( lambda p: query == p["source"] or query == p["binary"] or query == p["metadata_value"], packages.packages, ) ) click.echo(click.style("Source: ", bold=True) + package["source"]) click.echo(click.style("Import path: ", bold=True) + package["metadata_value"]) click.secho("Packages:", bold=True) for binary_package in filter( lambda p: p["source"] == package["source"] and not p["binary"].endswith("-dbgsym"), packages.packages, ): click.echo(" - " + binary_package["binary"]) gophian/gophian/error.py000066400000000000000000000024231464273176300156510ustar00rootroot00000000000000# gophian -- tools to help with Debianizing Go software # Copyright (C) 2024 Maytham Alsudany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import subprocess from click import ClickException class GophianError(ClickException): def __init__(self, *args) -> None: super().__init__(*args) class ExecutionError(subprocess.CalledProcessError): def __init__(self, out: subprocess.CompletedProcess[bytes]): super().__init__(out.returncode, out.args) class GoExecutionError(ExecutionError): pass class GitExecutionError(ExecutionError): pass class GbpExecutionError(ExecutionError): pass class UscanExecutionError(ExecutionError): pass gophian/gophian/git.py000066400000000000000000000107651464273176300153130ustar00rootroot00000000000000# gophian -- tools to help with Debianizing Go software # Copyright (C) 2024 Maytham Alsudany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import subprocess from os import PathLike from pathlib import Path from typing import List, Self from gophian.error import GitExecutionError, GophianError class GitRunner: """ Class to run git commands. """ def __init__(self, **kwargs) -> None: self.quiet: bool = kwargs.get("quiet", True) def run(self, args: List[str], **kwargs) -> subprocess.CompletedProcess[bytes]: args = ["git"] + args quiet = kwargs.get("quiet", self.quiet) supports_quiet = kwargs.get("supports_quiet", False) if supports_quiet and quiet: args.insert(2, "--quiet") if "quiet" in kwargs: kwargs.pop("quiet") if "supports_quiet" in kwargs: kwargs.pop("supports_quiet") out = subprocess.run(args, **kwargs) if out.returncode != 0: raise GitExecutionError(out) return out def get(self, args: List[str], **kwargs) -> str: kwargs["capture_output"] = True return self.run(args, **kwargs).stdout.strip().decode() class Git(GitRunner): """ A local git repository. """ def __init__(self, path: PathLike, **kwargs) -> None: super().__init__(**kwargs) self.path = Path(path) check: bool = kwargs.get("check", True) if check: if not self.path.exists(): raise FileNotFoundError(self.path) if not ((self.path / ".git").exists() and (self.path / ".git").is_dir()): raise NotAGitRepoError(str(self.path)) pass def run(self, args: List[str], **kwargs): return super().run(args, cwd=self.path, **kwargs) def _clone(self, repo_url: str, **kwargs): args = ["clone", repo_url, str(self.path)] if branch := kwargs.get("branch"): args += ["--branch", branch, "-c", "advice.detachedHead=false"] if depth := kwargs.get("depth"): args += ["--depth", str(depth)] super().run(args, supports_quiet=True) @classmethod def clone(cls, repo_url: str, dest: PathLike, **kwargs) -> Self: path = Path(dest).resolve() if not path.exists() or not path.is_dir(): path.mkdir() repo = cls(path, quiet=kwargs.get("quiet", False), check=False) repo._clone(repo_url, **kwargs) return repo @classmethod def init(cls, dest: PathLike, branch: str = "main", **kwargs) -> Self: path = Path(dest).resolve() if not path.exists() or not path.is_dir(): path.mkdir() repo = cls(path, quiet=kwargs.get("quiet", False), check=False) repo.run(["init", "-b", branch], supports_quiet=True) repo = cls(path) return repo def add(self, paths: List[str] = ["."]) -> None: self.run(["add"] + paths) def commit(self, msg: str, **kwargs) -> None: cmd = ["commit", "-m", msg] if kwargs.get("gpg_sign") is not None: cmd.append("--gpg-sign" if kwargs.get("gpg_sign") else "--no-gpg-sign") self.run(cmd, supports_quiet=True) def tags(self) -> List[str]: return self.get(["tag", "--list"], quiet=False).splitlines() def checkout(self, commitish: str) -> None: self.run(["checkout", commitish], supports_quiet=True) def remote(self, url: str, name: str = "origin") -> None: self.run(["remote", "add", name, url]) @staticmethod def remote_tags(url: str, **kwargs) -> List[str]: runner = GitRunner(quiet=kwargs.get("quiet")) return [ line.split("/")[2] for line in runner.get(["ls-remote", "--tags", "--refs", url]).splitlines() ] class NotAGitRepoError(GophianError): def __init__(self, path: str) -> None: super().__init__(f"'{path}' is not a git repo (no .git directory found)") gophian/gophian/hosts.py000066400000000000000000000034351464273176300156640ustar00rootroot00000000000000# gophian -- tools to help with Debianizing Go software # Copyright (C) 2024 Maytham Alsudany # # 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 . # map of known Golang import path hostnames KNOWN_HOSTS = { # dh-make-golang "bazil.org": "bazil", "bitbucket.org": "bitbucket", "blitiri.com.ar": "blitiri", "cloud.google.com": "googlecloud", "code.google.com": "googlecode", "filippo.io": "filippo", "fyne.io": "fyne", "git.sr.ht": "sourcehut", "github.com": "github", "gitlab.com": "gitlab", "go.cypherpunks.ru": "cypherpunks", "go.mongodb.org": "mongodb", "go.opentelemetry.io": "opentelemetry", "go.step.sm": "step", "go.uber.org": "uber", "go4.org": "go4", "gocloud.dev": "gocloud", "golang.org": "golang", "google.golang.org": "google", "gopkg.in": "gopkg", "honnef.co": "honnef", "howett.net": "howett", "k8s.io": "k8s", "modernc.org": "modernc", "pault.ag": "pault", "rsc.io": "rsc", "salsa.debian.org": "debian", "sigs.k8s.io": "k8s-sigs", "software.sslmate.com": "sslmate", # gophian "gitea.com": "gitea", "code.gitea.io": "code-gitea", "codeberg.org": "codeberg", } gophian/gophian/licenses/000077500000000000000000000000001464273176300157525ustar00rootroot00000000000000gophian/gophian/licenses/AGPL-3+.txt000066400000000000000000000014401464273176300174500ustar00rootroot00000000000000 This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. . You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Comment: On Debian systems, the complete text of the GNU Affero General Public License version 3 can be found in "/usr/share/common-licenses/AGPL-3". gophian/gophian/licenses/Apache-2.0.txt000066400000000000000000000012331464273176300201700ustar00rootroot00000000000000 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at . https://www.apache.org/licenses/LICENSE-2.0 . Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Comment: On Debian systems, the full text of the Apache license, version 2.0 can be found at /usr/share/common-licenses/Apache-2.0 gophian/gophian/licenses/BSD-2-Clause.txt000066400000000000000000000023641464273176300205010ustar00rootroot00000000000000 Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: . 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. . 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. . THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. gophian/gophian/licenses/BSD-3-Clause.txt000066400000000000000000000026771464273176300205110ustar00rootroot00000000000000 Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: . 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. . 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. . 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. . THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. gophian/gophian/licenses/Expat.txt000066400000000000000000000020231464273176300175710ustar00rootroot00000000000000 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: . The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. . THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. gophian/gophian/licenses/GPL-2+.txt000066400000000000000000000015071464273176300173520ustar00rootroot00000000000000 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. . This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. . You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Comment: On Debian systems, the complete text of the GNU General Public License version 2 can be found in "/usr/share/common-licenses/GPL-3". gophian/gophian/licenses/GPL-3+.txt000066400000000000000000000014021464273176300173450ustar00rootroot00000000000000 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 . Comment: On Debian systems, the complete text of the GNU General Public License version 3 can be found in "/usr/share/common-licenses/GPL-3". gophian/gophian/licenses/LGPL-2+.txt000066400000000000000000000015511464273176300174650ustar00rootroot00000000000000 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. . This library 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 Library General Public License for more details. . You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Comment: On Debian systems, the complete text of the GNU Library General Public License version 2 can be found in "/usr/share/common-licenses/LGPL-2". gophian/gophian/licenses/LGPL-2.1+.txt000066400000000000000000000015521464273176300176250ustar00rootroot00000000000000 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. . This library 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 Lesser General Public License for more details. . You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Comment: On Debian systems, the complete text of the GNU Lesser General Public License version 2.1 can be found in "/usr/share/common-licenses/GPL-2.1". gophian/gophian/licenses/LGPL-3+.txt000066400000000000000000000016111464273176300174630ustar00rootroot00000000000000 This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser 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 Lesser General Public License along with this program. If not, see . Comment: On Debian systems, the complete text of the GNU Lesser General Public License version 3 can be found in "/usr/share/common-licenses/LGPL-3", as well as the GNU General Public License version 3, which can be found in "/usr/share/common-licenses/GPL-3". gophian/gophian/licenses/__init__.py000066400000000000000000000027221464273176300200660ustar00rootroot00000000000000# gophian -- tools to help with Debianizing Go software # Copyright (C) 2024 Maytham Alsudany # # 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 . from pathlib import Path # Dict that maps SPDX license names to Debian license names # This should list all text files in the licenses/ directory KNOWN_LICENSES = { "MIT": "Expat", "AGPL-3.0-or-later": "AGPL-3+", "GPL-2.0-or-later": "GPL-2+", "GPL-3.0-or-later": "GPL-3+", "LGPL-2.0-or-later": "LGPL-2+", "LGPL-2.1-or-later": "LGPL-2.1+", "LGPL-3-or-later": "LGPL-3+", "Apache-2.0": "Apache-2.0", "BSD-2-Clause": "BSD-2-Clause", "BSD-3-Clause": "BSD-3-Clause", } def fetch_license_text(lic: str) -> str: license_file = Path(__file__).parent / f"{lic}.txt" if license_file.exists(): return license_file.read_text().rstrip() else: return " TODO: Unknown license" gophian/gophian/name.py000066400000000000000000000023611464273176300154410ustar00rootroot00000000000000# gophian -- tools to help with Debianizing Go software # Copyright (C) 2024 Maytham Alsudany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import re from typing import Optional from gophian.hosts import KNOWN_HOSTS def debianize_name(package: str, short_host: Optional[str] = None) -> str: parts = package.lower().split("/") if short_host is None: short_host = KNOWN_HOSTS[parts[0]] parts[0] = short_host name = "golang-" + "-".join(parts) name = name.replace("_", "-") name = re.sub(r"[^a-z0-9\+\-\.]", "", name) return name def shorten_host(host: str) -> str: return ".".join(host.split(".")[:-1]) gophian/gophian/new.py000066400000000000000000000051301464273176300153070ustar00rootroot00000000000000# gophian -- tools to help with Debianizing Go software # Copyright (C) 2024 Maytham Alsudany # # 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 . from typing import List, Optional, Self from datetime import datetime import requests from debian.deb822 import Deb822 class NewPackage: """ A package in the ftpmaster's NEW queue. """ def __init__(self, stanza: Deb822) -> None: self.source: str = stanza["Source"] self.binary: List[str] = list( filter(lambda b: not b.endswith("-dbgsym"), stanza["Binary"].split(", ")) ) self.version: str = stanza["Version"] self.architectures: List[str] = stanza["Architectures"].split(", ") self.age: str = stanza["Age"] self.last_modified: datetime = datetime.fromtimestamp( int(stanza["Last-Modified"]) ) self.queue: str = stanza["Queue"] self.maintainer: str = stanza["Maintainer"] self.changed_by: str = stanza["Changed-By"] self.distribution: str = stanza["Distribution"] self.fingerprint: str = stanza["Fingerprint"] self.closes: List[str] = ( stanza["Closes"].split(", ") if "Closes" in stanza else [] ) self.url: str = ( "https://ftp-master.debian.org/new/" + self.source + "_" + self.version + ".html" ) @classmethod def all(cls, session: requests.Session) -> List[Self]: text = session.get("https://ftp-master.debian.org/new.822", timeout=60).text new_packages: List[Self] = [] for stanza in Deb822.iter_paragraphs(text): new_packages.append(cls(stanza)) return list(filter(lambda p: p.queue == "new", new_packages)) @classmethod def get(cls, session: requests.Session, source_package: str) -> Optional[Self]: packages = cls.all(session) for package in packages: if package.source == source_package: return package return None gophian/gophian/packages.py000066400000000000000000000153051464273176300163010ustar00rootroot00000000000000# gophian -- tools to help with Debianizing Go software # Copyright (C) 2024 Maytham Alsudany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import re from typing import Optional, Tuple, Union import click import requests from looseversion import LooseVersion from gophian.error import GophianError from gophian.new import NewPackage from gophian.salsa import salsa_repo_exists DEB_EXT = re.compile(r"([\+~](debian|dfsg|ds|deb)(\.)?(\d+)?)?-([A-Za-z0-9\+\.~]+)$") class DebianPackage: """ Class representing a Debian source package (can have more than one binary package). """ def __init__(self, session: requests.Session, source: str) -> None: self.session = session self.source = source pass def is_in_package_tracker(self) -> Optional[str]: """ Check if the Debian package can be found at tracker.debian.org. Returns URL of package tracker if found. """ res = self.session.head( "https://tracker.debian.org/pkg/" + self.source, timeout=60 ) if res.status_code != 404: return "https://tracker.debian.org/pkg/" + self.source else: return None def is_in_new_queue(self) -> Optional[NewPackage]: """ Check if the Debian package is in the NEW queue. Returns NewPackage object if found. """ return NewPackage.get(self.session, self.source) def unstable_version(self) -> Optional[str]: """ Check if the Debian package is currently in unstable. Useful to check if a package has been removed. """ res = self.session.get( "https://sources.debian.org/api/src/" + self.source + "/", timeout=60 ) try: data = res.json() except requests.JSONDecodeError: print(res.status_code, res.text) raise JSONDecodeError( f"Failed to decode JSON from sources.d.o response (package: {self.source})" ) # sources api returns status code 200 but body {error:404} if res.status_code == 404 or ("error" in data and data["error"] == 404): return return ( DEB_EXT.sub("", data["versions"][0]["version"]) if ( "sid" in data["versions"][0]["suites"] or "experimental" in data["versions"][0]["suites"] ) else None ) class DebianGolangPackages: """ Class representing the list of all Debian Go packages. """ def __init__(self, session: requests.Session): self.session = session def filter_dbgsym(package): return not package["binary"].endswith("-dbgsym") self.packages = list( filter( filter_dbgsym, self.session.get( "https://api.ftp-master.debian.org/binary/by_metadata/Go-Import-Path", timeout=60, ).json(), ) ) def is_packaged(self, go_package: str) -> Union[str, None]: """ Check if the given Go package has been packaged for Debian. """ for deb_package in self.packages: importpaths = list( map(lambda x: x.strip(), deb_package["metadata_value"].split(",")) ) if ( len( list( filter( lambda i: i == go_package or i.startswith(deb_package["metadata_value"] + "/"), importpaths, ) ) ) > 0 ): return deb_package["source"] return None def library_is_packaged( self, go_package: str ) -> Optional[Tuple[str, LooseVersion]]: """ Check if the given Go library has been packaged for Debian. """ for deb_package in self.packages: if not deb_package["binary"].endswith("-dev"): continue if ( deb_package["metadata_value"] == go_package or go_package.startswith(deb_package["metadata_value"] + "/") ) and ( version := DebianPackage( self.session, deb_package["source"] ).unstable_version() ): return deb_package["binary"], LooseVersion(version) return None def _check_for_package(self, package_name: str, quiet: bool = False) -> bool: if debian_package := self.is_packaged(package_name): if not quiet: click.secho( f"Already packaged for Debian: {debian_package}", fg="yellow" ) package = DebianPackage(self.session, debian_package) if package.is_in_package_tracker(): if version := package.unstable_version(): click.echo("Latest version in Debian repos is " + version) click.echo("https://tracker.debian.org/pkg/" + debian_package) else: click.echo("Package was removed from Debian unstable") if salsa_repo_exists( self.session, "go-team/packages/" + package.source ): click.echo( "The Salsa repo for the package still exists though:" ) click.echo( "https://salsa.debian.org/go-team/packages/" + package.source ) elif new_package := NewPackage.get(self.session, debian_package): click.echo("Waiting in NEW queue: " + new_package.url) else: click.echo( "Could not find the package on the Package Tracker, nor in the NEW queue" ) return True else: return False class JSONDecodeError(GophianError): pass gophian/gophian/salsa.py000066400000000000000000000016521464273176300156260ustar00rootroot00000000000000# gophian -- tools to help with Debianizing Go software # Copyright (C) 2024 Maytham Alsudany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import requests def salsa_repo_exists(session: requests.Session, repo: str) -> bool: res = session.head("https://salsa.debian.org/" + repo) return res.status_code == 200 gophian/gophian/session/000077500000000000000000000000001464273176300156305ustar00rootroot00000000000000gophian/gophian/session/__init__.py000066400000000000000000000065731464273176300177540ustar00rootroot00000000000000# gophian -- tools to help with Debianizing Go software # Copyright (C) 2024 Maytham Alsudany # # 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 . # package = repo root with go.mod # module = Go root package and packages located in subdir of module # import_path = import path of Go module # deb_package = Debian package import subprocess from typing import Dict, List, Self import requests from gophian.error import GoExecutionError from gophian.session.git import GoPackage from gophian.tempdir import TemporaryDirectory from gophian.vcs import package_from_import_path class Session: """ A session with cloned repos in a GOPATH-like temporary directory. """ def __init__(self, requests_session: requests.Session) -> None: self.requests_session = requests_session self.tempdir = TemporaryDirectory() self.gopath = self.tempdir.path self.stdlib = stdlib() def cleanup(self) -> None: self.tempdir.cleanup() def __enter__(self) -> Self: return self def __exit__(self, *_) -> None: self.cleanup() downloaded_packages: Dict[str, GoPackage] = {} def go_get(self, import_path: str) -> GoPackage: package_import_path, repo = package_from_import_path( self.requests_session, import_path ) if package_import_path in self.downloaded_packages: return self.downloaded_packages[package_import_path] package = GoPackage(self, package_import_path, repo) self.downloaded_packages[package_import_path] = package return package def package_modules(self, package: str) -> List[str]: repo = self.go_get(package) out = subprocess.run( ["env", f"GOPATH={self.gopath}", "go", "list", package + "/..."], capture_output=True, cwd=repo.path, ) return out.stdout.decode().splitlines() def package_main_modules(self, package: str) -> List[str]: modules = self.package_modules(package) main_modules: List[str] = [] for module in modules: out = subprocess.run( [ "env", f"GOPATH={self.gopath}", "go", "list", "-f", "{{.Name}}", module, ], capture_output=True, cwd=self.gopath / "src" / package, ) if out.stdout.decode().strip() == "main": main_modules.append(module) return main_modules def stdlib() -> List[str]: out = subprocess.run( ["go", "list", "std"], capture_output=True, ) if out.returncode != 0: raise GoExecutionError(out) return out.stdout.decode().splitlines() + ["C"] gophian/gophian/session/git.py000066400000000000000000000206261464273176300167730ustar00rootroot00000000000000# gophian -- tools to help with Debianizing Go software # Copyright (C) 2024 Maytham Alsudany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import re import subprocess from datetime import datetime from typing import TYPE_CHECKING, Any, Dict, List, Tuple import click from looseversion import LooseVersion from gophian.error import GophianError from gophian.git import Git from gophian.vcs import package_from_import_path if TYPE_CHECKING: from gophian.session import Session GO_MOD_MODULE_REGEX = re.compile(r"^module (\S+)$") GO_MOD_GO_REGEX = re.compile(r"^go (\d[\d\.]*)$") GO_MOD_REQUIREMENT_REGEX = re.compile(r"^(\S+) (\S+)(?: // indirect)?$") class GoPackage(Git): def __init__(self, session: "Session", package: str, repo: str) -> None: self.package = package self.path = session.gopath / "src" / package self.session = session self.repo = repo super().__init__(self.path, quiet=True, check=False) tags_dict: Dict[str, str] = {} all_tags = Git.remote_tags(repo, quiet=True) for tag in all_tags: if match := re.search(r"^v?(\d[\d\.]+)$", tag, re.MULTILINE): tags_dict[match.group(1)] = match.group(0) versions = [LooseVersion(tag) for tag in tags_dict.keys()] versions.sort() if len(versions) > 0: version = versions[-1] commitish = tags_dict[str(version)] self.versioned = True self.debianized_version = str(version) self._clone(repo, branch=commitish, depth=1) else: iso_date, commit_hash = self.get(["log", "-1", "--format=%cI %H"]).split( " " ) date = datetime.fromisoformat(iso_date).strftime("%Y%m%d") self.versioned = False self.debianized_version = f"0.0~git{date}.{commit_hash[:7]}" self._clone(repo, depth=1) self.deps: Dict[str, GoVersion] = {} for filename in self.path.rglob("**/go.mod"): with filename.open("r") as file: inside_require = False for i, line in enumerate(file): line = line.strip() if line == "" or line.startswith("//"): continue elif inside_require: if match := GO_MOD_REQUIREMENT_REGEX.match(line): if not line.endswith("// indirect"): dep, _ = package_from_import_path( self.session.requests_session, match.group(1) ) self.deps[dep] = GoVersion(match.group(2)) elif line == ")": inside_require = False else: raise GoModParseError( i + 1, self.path, "Invalid 'require' directive. (84)" ) elif line.startswith("require "): line = line[8:] if line.startswith("("): indirect = line.endswith("// indirect") if comment_index := line.find("//") != -1: line = line[:comment_index].strip() if line == "(": inside_require = True else: print("Not == '('") print("'" + line + "'") if line.endswith(")"): line = line[1:-1] if match := GO_MOD_REQUIREMENT_REGEX.match(line): if not indirect: dep, _ = package_from_import_path( self.session.requests_session, match.group(1), ) self.deps[dep] = GoVersion(match.group(2)) else: raise GoModParseError( i + 1, self.path, "Invalid 'require' directive. (105)", ) else: if match := GO_MOD_REQUIREMENT_REGEX.match(line): if not indirect: dep, _ = package_from_import_path( self.session.requests_session, match.group(1), ) self.deps[dep] = GoVersion(match.group(2)) else: raise GoModParseError( i + 1, self.path, "Invalid 'require' directive. (117)", ) elif match := GO_MOD_MODULE_REGEX.match(line): self.module = match.group(1) elif match := GO_MOD_GO_REGEX.match(line): self.go_version = LooseVersion(match.group(1)) def find_dependencies(self, test: bool = False) -> List[Tuple[str, str]]: all_imports: List[str] = [] out = subprocess.run( [ "env", f"GOPATH={self.session.gopath}", "GO111MODULE=off", "go", "list", "-f", "{{.TestImports}}" if test else "{{.Imports}}", f"{self.package}/...", ], cwd=(self.session.gopath / "src" / self.package), capture_output=True, ) # Ignore errors from go, as they're about missing dependencies in # GOPATH (and we don't care about this). for pkg in out.stdout.splitlines(): dep_string = pkg.strip().decode()[1:-1] all_imports += dep_string.split(" ") def filter_deps(dep: str): return ( not dep.startswith(self.package) and dep not in self.session.stdlib and dep != "" ) lib_imports: List[str] = remove_duplicates( list(filter(filter_deps, all_imports)) ) deps: List[Tuple[str, str]] = [] for imp in lib_imports: if any(imp.startswith(dep) for dep in deps): continue try: deps.append( package_from_import_path(self.session.requests_session, imp) ) except Exception as e: click.echo(e) continue return deps class GoModParseError(GophianError): def __init__(self, line, path, msg) -> None: self.line = line super().__init__(f"{path}:{line} {msg}") T = Any def remove_duplicates(li: List[T]) -> List[T]: return list(dict.fromkeys(li)) class GoVersion(LooseVersion): def __init__(self, vstring: str) -> None: self.commit = False if vstring.startswith("v"): vstring = vstring[1:] if "-" in vstring: self.commit = True [semver, date, commit] = vstring.split("-") if semver == "0.0.0": semver = "0.0" date = date[:8] commit = commit[:7] vstring = f"{semver}~git{date}.{commit}" super().__init__(vstring) gophian/gophian/tempdir.py000066400000000000000000000021021464273176300161560ustar00rootroot00000000000000# gophian -- tools to help with Debianizing Go software # Copyright (C) 2024 Maytham Alsudany # # 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 . from pathlib import Path import tempfile class TemporaryDirectory(tempfile.TemporaryDirectory): """ Wrapper around tempfile.TemporaryDirectory that uses pathlib.Path. """ def __init__(self) -> None: super().__init__() self.path = Path(self.name) def __enter__(self): return self.path gophian/gophian/templates/000077500000000000000000000000001464273176300161435ustar00rootroot00000000000000gophian/gophian/templates/changelog.jinja000066400000000000000000000002061464273176300211050ustar00rootroot00000000000000{{source}} ({{debian_version}}) UNRELEASED; urgency=medium * Initial release (Closes: {{bug}}) -- {{name}} <{{email}}> {{date}} gophian/gophian/templates/control/000077500000000000000000000000001464273176300176235ustar00rootroot00000000000000gophian/gophian/templates/control/go_binary.jinja000066400000000000000000000004011464273176300226040ustar00rootroot00000000000000Package: {{ package }} Section: TODO Architecture: any Depends: ${misc:Depends}, ${shlibs:Depends}, Static-Built-Using: ${misc:Static-Built-Using} Description: {{ short_desc if short_desc else "TODO" }} (program) {{ long_desc if long_desc else " TODO" }} gophian/gophian/templates/control/go_library.jinja000066400000000000000000000004001464273176300227630ustar00rootroot00000000000000Package: {{ package }} Architecture: all Multi-Arch: foreign Depends: {% if lib_deps %} {{ lib_deps|join(',\n ') }}, {% endif %} ${misc:Depends}, Description: {{ short_desc if short_desc else "TODO" }} (library) {{ long_desc if long_desc else " TODO" }} gophian/gophian/templates/control/header.jinja000066400000000000000000000007301464273176300220700ustar00rootroot00000000000000Source: {{source}} Section: golang Priority: optional Maintainer: Debian Go Packaging Team Uploaders: {{ uploaders }} Rules-Requires-Root: no Build-Depends: {{ lib_deps|join(',\n ') }}, Testsuite: autopkgtest-pkg-go Standards-Version: 4.7.0 Vcs-Browser: https://salsa.debian.org/go-team/packages/{{source}} Vcs-Git: https://salsa.debian.org/go-team/packages/{{source}}.git Homepage: {{ homepage }} XS-Go-Import-Path: {{ go_import_path }} gophian/gophian/templates/copyright.jinja000066400000000000000000000007131464273176300211710ustar00rootroot00000000000000Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ Source: {{ homepage }} Upstream-Name: {{ upstream_name }} Upstream-Contact: TODO {% if repack %} Files-Excluded: vendor/* {% endif %} Files: * Copyright: TODO License: {{ license }} Files: debian/* Copyright: {{ year }} {{ name }} <{{ email }}> License: {{ license }} Comment: Debian packaging is licensed under the same terms as upstream License: {{ license }} {{ license_text }} gophian/gophian/templates/itp.jinja000066400000000000000000000013211464273176300177510ustar00rootroot00000000000000From: {{ name }} <{{ email }}> To: submit@bugs.debian.org Subject: ITP: {{ package }} -- {{ short_desc }} Package: wnpp Severity: wishlist Owner: {{ name }} <{{ email }}> X-Debbugs-CC: debian-devel@lists.debian.org, debian-go@lists.debian.org * Package name : {{ package }} Version : {{ version }} Upstream Contact: {{ upstream }} * URL : {{ url }} * License : {{ license }} Programming Lang: Go Description : {{ short_desc }} {{ long_desc }} TODO: reasoning perhaps This package will be maintained within the Debian Go Packaging Team. {% if not email.endswith('@debian.org') %} I will need a DD to sponsor and upload this package. {% endif %} -- Kind regards, {{ name }} gophian/gophian/templates/watch/000077500000000000000000000000001464273176300172515ustar00rootroot00000000000000gophian/gophian/templates/watch/git_commits.jinja000066400000000000000000000003001464273176300225750ustar00rootroot00000000000000version=4 {% if repack %} opts="mode=git, pgpmode=none,\ dversionmangle=s/\+ds\d*$//,repacksuffix=+ds" \ {% else %} opts="mode=git, pgpmode=none" \ {% endif %} {{ repo }}.git \ HEAD gophian/gophian/templates/watch/git_tags.jinja000066400000000000000000000003231464273176300220650ustar00rootroot00000000000000version=4 {% if repack %} opts="mode=git, pgpmode=none,\ dversionmangle=s/\+ds\d*$//,repacksuffix=+ds" \ {% else %} opts="mode=git, pgpmode=none" \ {% endif %} {{ repo }}.git \ refs/tags/v?(\d[\d\.]*) gophian/gophian/templates/watch/github.jinja000066400000000000000000000006161464273176300215530ustar00rootroot00000000000000version=4 opts="filenamemangle=s%(?:.*?)?v?(\d[\d.]*)\.tar\.gz%@PACKAGE@-$1.tar.gz%,\ {% if repack %} uversionmangle=s/(\d)[_\.\-\+]?(RC|rc|pre|dev|beta|alpha)[.]?(\d*)$/$1~$2$3/,\ dversionmangle=s/\+ds\d*$//,repacksuffix=+ds" \ {% else %} uversionmangle=s/(\d)[_\.\-\+]?(RC|rc|pre|dev|beta|alpha)[.]?(\d*)$/$1~$2$3/" \ {% endif %} {{ repo }}/tags \ .*/v?(\d[\d\.]*)\.tar\.gz gophian/gophian/vcs.py000066400000000000000000000073131464273176300153160ustar00rootroot00000000000000# gophian -- tools to help with Debianizing Go software # Copyright (C) 2024 Maytham Alsudany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import re from typing import Tuple from urllib.parse import quote as urlencode, urlparse import requests from gophian.error import GophianError GO_IMPORT_META_REGEX = re.compile( r"" ) def package_from_import_path(session: requests.Session, path: str) -> Tuple[str, str]: """ Get the root package and repo from the given import path. """ if path.split("/")[0] == "github.com": repo = "/".join(path.split("/")[0:3]) return (repo, strip_git_suffix("https://" + repo)) try: return get_repo_meta(session, path) except NoRootRepoError: raise NoRootRepoError(path) def get_repo_meta(session: requests.Session, path: str) -> Tuple[str, str]: """ Get the root package and repo by recursively downloading and checking website pages for a 'go-import' meta tag. """ res = session.get("https://" + path, timeout=60, params={"go-get": "1"}) match = GO_IMPORT_META_REGEX.search(res.text) if match is None: parts = path.split("/") if len(parts[:-1]) < 1: raise NoRootRepoError(path) else: return get_repo_meta(session, "/".join(parts[:-1])) return ( match.group(1), strip_git_suffix(match.group(2)), ) def get_short_desc(session: requests.Session, repo_url: str) -> str: url = urlparse(repo_url) path = url.path[1:] desc = None if url.hostname == "github.com": repo = session.get(f"https://api.github.com/repos/{path}", timeout=60).json() if repo["description"] is not None and len(repo["description"]) > 0: desc = repo["description"] if url.hostname == ["codeberg.org", "gitea.com"]: repo = session.get( f"https://{url.hostname}/api/v1/repos/{path}", timeout=60 ).json() if repo["description"] is not None and len(repo["description"]) > 0: desc = repo["description"] if url.hostname in ["salsa.debian.org", "gitlab.com"]: repo = session.get( f"https://{url.hostname}/api/v4/projects/{urlencode(path)}", timeout=60 ).json() if repo["description"] is not None and len(repo["description"]) > 0: desc = repo["description"] if desc is None: return "TODO" desc = remove_punctuation(desc) desc = remove_article(desc) return desc def remove_punctuation(s: str) -> str: if s[-1] in [".", "!", "?"]: return s[:-1] else: return s def remove_article(s: str) -> str: if s.lower().startswith("a "): return s[2:] elif s.lower().startswith("an "): return s[3:] else: return s def strip_git_suffix(s: str) -> str: if s.endswith(".git/"): return s[:-5] if s.endswith(".git"): return s[:-4] return s class NoRootRepoError(GophianError): def __init__(self, path: str): super().__init__(f"No root repo could be determined for the path '{path}'") gophian/gophian/wnpp.py000066400000000000000000000076451464273176300155170ustar00rootroot00000000000000# gophian -- tools to help with Debianizing Go software # Copyright (C) 2024 Maytham Alsudany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import re from enum import Enum, auto from typing import List, Optional, Self import requests WNPP_BUG_PATTERN = re.compile( r'(?P[A-Za-z0-9\-\.]+): (?P[\S ]+)' ) class WnppBugType(Enum): """ Enum representing the different types of WNPP bugs. """ ITP = auto() RFP = auto() class WnppBug: """ Class to represent a WNPP bug. """ def __init__( self, type: WnppBugType, id: str, package: str, description: str ) -> None: self.type = type self.id = id self.package = package self.description = description class ITPBug(WnppBug): """ Class to represent an ITP (Intent to Package) bug. """ def __init__(self, id: str, package: str, description: str) -> None: self.type = WnppBugType.ITP self.id = id self.package = package self.description = description @classmethod def all(cls, session: requests.Session) -> List[Self]: """ Fetch a list of all open ITP bugs. """ html = session.get( "https://www.debian.org/devel/wnpp/being_packaged", timeout=60 ).text return list( map(lambda g: cls(g[0], g[1], g[2]), WNPP_BUG_PATTERN.findall(html)) ) @classmethod def search(cls, session: requests.Session, package: str) -> List[Self]: """ Search for ITP bugs whose package name contain the given package name. """ itps = cls.all(session) return [itp for itp in itps if package in itp.package] @classmethod def get(cls, session: requests.Session, package: str) -> Optional[Self]: """ Find the ITP bug corresponding to the given package name. """ itps = cls.all(session) for itp in itps: if package == itp.package: return itp return None class RFPBug(WnppBug): """ Class to represent an RFP (Request for Package) bug. """ def __init__(self, id: str, package: str, description: str) -> None: self.type = WnppBugType.RFP self.id = id self.package = package self.description = description @classmethod def all(cls, session: requests.Session) -> List[Self]: """ Fetch a list of all open RFP bugs. """ html = session.get( "https://www.debian.org/devel/wnpp/requested", timeout=60 ).text return list( map(lambda g: cls(g[0], g[1], g[2]), WNPP_BUG_PATTERN.findall(html)) ) @classmethod def search(cls, session: requests.Session, package: str) -> List[Self]: """ Search for RFP bugs whose package name contain the given package name. """ rfps = cls.all(session) return [rfp for rfp in rfps if package in rfp.package] @classmethod def get(cls, session: requests.Session, package: str) -> Optional[Self]: """ Find the RFP bug corresponding to the given package name. """ rfps = cls.all(session) for rfp in rfps: if package == rfp.package: return rfp return None gophian/man/000077500000000000000000000000001464273176300132735ustar00rootroot00000000000000gophian/man/Makefile000066400000000000000000000001561464273176300147350ustar00rootroot00000000000000#!/usr/bin/env make man: $(basename $(wildcard *.1.scd)) clean: rm -f ./*.1 %.1: %.1.scd scdoc < $< > $@ gophian/man/gophian-create-salsa-repo.1.scd000066400000000000000000000013141464273176300210560ustar00rootroot00000000000000GOPHIAN-CREATE-SALSA-REPO(1) # NAME gophian-create-salsa-repo - Create a Salsa repo within the Debian Go Package Team # SYNOPSIS *gophian create-salsa-repo* [OPTIONS] [PROJECT] # DESCRIPTION This subcommand helps you create a Salsa repo within the Debian Go package Team under the correct namespace (go-team/packages) and with the correct repository CI configuration and description. Using this does not require any form of authentication. # ARGUMENTS *PROJECT* - The name of repository to be created. When not specified, gophian will check for a debian/control file in the current working directory, and if found, will use the value of the "Source" field. # OPTIONS *--help* - Show help message and exit. gophian/man/gophian-estimate-graphviz.1.scd000066400000000000000000000034501464273176300212150ustar00rootroot00000000000000GOPHIAN-ESTIMATE-GRAPHVIZ(1) # NAME gophian-estimate-graphviz - Visualize the dependency tree of a given Go package # SYNOPSIS *gophian estimate-graphviz* [SOURCE_OUTPUT] [OPTIONS] # DESCRIPTION This subcommand is only available when python3-graphviz is installed. This subcommand recursively finds all dependencies of a given package and checks if they are packaged in Debian, producing a dependency tree using Graphviz showing dependencies that are available as Debian packages and which are not. This is useful for large or complex dependency graphs that are much better depicted by a Graphviz tree. A source Graphviz file will be written to *SOURCE_OUTPUT*, and unless *--no-render* is passed, a rendered PDF will be written in the same directory as the source file with the same basename, but the ".pdf" output. # ARGUMENTS *IMPORTPATH* - The import path of the Go package being estimated. *SOURCE_OUTPUT* - Output path of the source Graphviz code. By default, this is the Debianized version of the import path e.g. golang-github-dsnet-compress.gv. # OPTIONS *--[no-]quiet* - Don't print warnings. *--[no-]open* - View rendered output in the most suitable application. (default: on) *--[no-]render* - Render the graph using Graphviz. (default: on) *--[no-]warn-packaged* - Warn if the given Go package has already been packaged for Debian. (default: on) *--[no-]include-packaged-deps* - Include packaged dependencies in the estimate. (default: on) *--[no-]include-version-conflicts* - Include any version conflicts between the package's go.mod and the version in Debian unstable. Ignored if *--no-include-packaged-deps* is passed. (default: off) *--max-depth* - Maximum recursion depth of unpackaged dependencies. *--help* - Show help message and exit. # SEE ALSO _gophian-estimate_(1) gophian/man/gophian-estimate.1.scd000066400000000000000000000021011464273176300173550ustar00rootroot00000000000000GOPHIAN-ESTIMATE(1) # NAME gophian-estimate - Estimate work required to Debianize a given Go package # SYNOPSIS *gophian estimate* [OPTIONS] # DESCRIPTION This subcommand recursively finds all dependencies of a given package and checks if they are packaged in Debian, producing a coloured tree to indicate which dependencies are already available as packages, and which are not. # ARGUMENTS *IMPORTPATH* - The import path of the Go package being estimated. # OPTIONS *--[no-]quiet* - Don't print warnings. *--[no-]warn-packaged* - Warn if the given Go package has already been packaged for Debian. (default: on) *--[no-]include-packaged-deps* - Include packaged dependencies in the estimate. (default: on) *--[no-]include-version-conflicts* - Include any version conflicts between the package's go.mod and the version in Debian unstable. Ignored if *--no-include-packaged-deps* is passed. (default: off) *--max-depth* - Maximum recursion depth of unpackaged dependencies. *--help* - Show help message and exit. # SEE ALSO _gophian-estimate-graphviz_(1) gophian/man/gophian-license-text.1.scd000066400000000000000000000005741464273176300201620ustar00rootroot00000000000000GOPHIAN-LICENSE-TEXT(1) # NAME gophian-license-text - Print DEP-5 license stanza suitable for d/copyright. # SYNOPSIS *gophian search* [OPTIONS] # DESCRIPTION Print a license text stanza suitable for inclusion in a DEP-5 d/copyright file. # ARGUMENTS *LICENSE* - Name of license as known by Debian. e.g. GPL-3+ # OPTIONS *--help* - Show help message and exit. gophian/man/gophian-make.1.scd000066400000000000000000000126321464273176300164710ustar00rootroot00000000000000GOPHIAN-MAKE(1) # NAME gophian-make - Prepare a Go module for packaging in Debian # SYNOPSIS *gophian make* [OPTIONS] # DESCRIPTION This subcommand prepares a Debian package for Go software, producing a DEP-14 and Go team compliant Git repository that has the latest appropriate upstream source imported, and initial packaging files that have been filled out intelligently as best as possible. Before starting, Gophian will check if the *IMPORTPATH* passed has already been packaged for Debian. This makes use of the same functionality used by _gophian-show_(1) and _gophian-search_(1), which makes use of the *XS-Go-Import-Path* field specified in Debian source packages. If found, it will warn you, and unless the *--no-warn-packaged* option was passed, the program will exit. If Gophian finds binary programs (files that start with "package 'main'") in the upstream code, it will prompt you to choose what type of package you intend to create. The prompt can be skipped ahead of time by setting the *--type* option. - *Library only* - Package is only intended to be imported by other programs. The source package will be named after the library. This is most Go packages depended on by other projects. - *Library and accompanying binaries* - Package is intended to be imported by other programs, with a helper or side program(s), usually meant to be used alongside the library. The source package will be named after the library. For example, the main purpose of github.com/go-git/go-git is to be used by other code, but also includes a proof-of-concept CLI called go-git. - *Binaries and accompanying library* - Package is intended to be used by the end user as a program, but also supplies a library to programs that want to consume it. The source package will be named after the binary. For example, Docker is mainly used as a CLI, but is also intentionally developed by upstream in such a way that it is reusable to other projects, and so is also available as a library. - *Binary only* - Package is only intended to be used as a program by the end user, and no library package should be created. The source package will be named after the binary. This is most end-user programs written in Go. If no binary packages are found, the "library only" package type is chosen automatically without prompting you. If you selected one of the package types that include one or more binaries, you will then be prompted to select which binaries you'd like to include in the generated d/control template. You should use this opportunity to check for and exclude any example programs that are not intended to be built. If you selected one of the package types "*Binaries and accompanying library*" or "*Binary only*", you will be prompted to choose which binary to name the source package after. This should usually be the name of the primary program intended to be used by the end user, which is often also the name of the upstream project itself. Following this, Gophian will check for any existing Salsa repos under the Go team with this name of source package, and warn you if one has been found. The program will then exit unless the *--no-warn-salsa* flag was passed. Gophian will also check for any open Intent to Package (ITP) or Request for Package (RFP) bugs matching the source package name and warn you. If found, this will be filled in the generated d/changelog for you. Gophian will now prepare the packaging Git repository, importing the latest upstream source and generating the initial packaging files. It will also check for any unpackaged dependencies and test dependencies and warn you about them. Once this is complete, it is strongly recommended you review all the Debian packaging files generated by Gophian and ensure all information is correct, and then fill in any missing information and complete any additional packaging work required. # ARGUMENTS *IMPORTPATH* - The import path of the Go package being Debianized. # OPTIONS *--type* [l|l+b|b+l|b] - Select the type of software being packaged. Can be one of "*Library only*", "*Library and accompanying binaries*", "*Binaries and accompanying library*", or "*Binaries only*", denoted by "l", "l+b", "b+l", or "b" respectively. *--name* - Name of package maintainer. Uses _DEBFULLNAME_ environment variable by default. (required) *--email* - Email of package maintainer. Uses _DEBEMAIL_ environment variable by default. (required) *--[no-]quiet* - Don't print warnings. *--[no-]warn-packaged* - Warn if the given Go package has already been packaged for Debian. (default: true) *--[no-]warn-salsa* - Warn if the package already has a repo under the Go team namespace on Salsa. (default: true) *--[no-]itp* - Generate an ITP template as well. (default: false) *--[no-]todo* - Generate a debian/TODO file. (default: false) *--[no-]gpg-sign* - GPG sign the commit that merges the upstream tarball into the packaging branch. If not passed to Gophian, then it will not be passed to git nor gbp and they will use their configured defaults. *--git-remote* [ssh|https] - Protocol to use when setting Git remote. (default: ssh) *--help* - Show help message and exit. # ENVIRONMENT _DEBFULLNAME_ - Used for *--name*. _DEBEMAIL_ - Used for *--email*. _GOPHIAN_ITP_ - Used for *--[no-]itp*. _GOPHIAN_TODO_ - Used for *--[no-]todo*. _GOPHIAN_REMOTE_ - Used for *--git-remote*. _GOPHIAN_GPG_SIGN_ - Used for *--[no-]gpg-sign*. # SEE ALSO _gophian_(1), _gophian-license-text_(1) gophian/man/gophian-search.1.scd000066400000000000000000000010241464273176300170120ustar00rootroot00000000000000GOPHIAN-SEARCH(1) # NAME gophian-search - Search Debian Go packages by name and import path # SYNOPSIS *gophian search* [OPTIONS] # DESCRIPTION Search for and list Debian packages with the given package name or Go import path. This subcommand makes use of the *XS-Go-Import-Path* field specified Debian source packages for Go programs and libraries, and can only find packages with this field specified. # ARGUMENTS *QUERY* - Debian package name or Go import path. # OPTIONS *--help* - Show help message and exit. gophian/man/gophian-show.1.scd000066400000000000000000000010461464273176300165310ustar00rootroot00000000000000GOPHIAN-SHOW(1) # NAME gophian-show - Show Debian Go package by name or import path # SYNOPSIS *gophian show* [OPTIONS] # DESCRIPTION Show Debian package information for the given package name or Go import path. This subcommand makes use of the *XS-Go-Import-Path* field specified Debian source packages for Go programs and libraries, and can only find packages with this field specified. # ARGUMENTS *QUERY* - Debian package name or Go import path. # OPTIONS *--help* - Show help message and exit. # SEE ALSO _gophian-search_(1) gophian/man/gophian.1.scd000066400000000000000000000052461464273176300155610ustar00rootroot00000000000000GOPHIAN(1) # NAME gophian - Tools to help with Debianizing Go software # SYNOPSIS *gophian* [OPTIONS] # DESCRIPTION The currently recommended dh-make-golang tool is known to be unreliable and relies on various outdated and deprecated libraries to function. gophian seeks to change that, by replicating the functionality of "go get" in Python, and providing something that works out of the box, as well as adding on more features and more intelligence to improve the Go packaging experience. So you want to package some nifty piece of software you found, and its written in Go? Look no further than Gophian! To start out, make sure that it hasn't already been packaged using _https://packages.debian.org_ or "apt search". Ensure that there isn't already an existing effort by checking for any open Intent to Package (ITP) bugs using _wnpp-check_(1). Next, you'll want to use _gophian-estimate_(1) to estimate the amount of work that will be needed to package this software for Debian. This subcommand will list any dependencies that are not available as packages in Debian yet in a tree format. _gophian-estimate-graphviz_(1) may also be useful to create visual tree with Graphviz, especially for large or complex dependency graphs. Then, you can use _gophian-make_(1) to prepare some initial Debian packaging for the software, including setting up a Git repo, importing the latest upstream version, and creating some packaging templates, inferring and filling in values for you if available. Refer to _gophian-make_(1) for an in-depth explanation of this subcommand's use. Refer to the individual subcommand manual pages for more detailed information. # SUBCOMMANDS *create-salsa-repo* - See _gophian-create-salsa-repo_(1) *estimate* - See _gophian-estiimate_(1) *estimate-graphviz* - See _gophian-estimate-graphviz_(1) *license-text* - See _gophian-license-text_(1) *make* - See _gophian-make_(1) *search* - See _gophian-search_(1) *show* - See _gophian-show_(1) # OPTIONS *--version* - Print version and exit. *--copyright* - Print copyright notice and exit. *--help* - Show help message and exit. # ENVIRONMENT The gophian utility supports the standard _DEBFULLNAME_ and _DEBEMAIL_ environment variables. See _devscripts_(1) for more information about these variables. # AUTHORS Maintained by Maytham Alsudany . # REPORTING BUGS Please submit bugs to https://codeberg.org/Maytha8/gophian/issues. Alternatively, you may send an email directly to the author, see *AUTHORS*. # SEE ALSO _gophian-create-salsa-repo_(1), _gophian-estimate_(1), _gophian-estimate-graphviz_(1), _gophian-license-text_(1), _gophian-make_(1), _gophian-search_(1), _gophian-show_(1) gophian/pyproject.toml000066400000000000000000000011421464273176300154320ustar00rootroot00000000000000[project] name = "gophian" dynamic = ["version"] dependencies = [ "Jinja2", "click", "python-debian", "python-debianbts", "questionary", "requests", "requests-cache", "treelib", "looseversion", ] [tool.setuptools.dynamic] version = {attr = "gophian.__about__.VERSION"} [tool.setuptools.packages.find] include = ["gophian*"] [project.scripts] gophian = "gophian.cli:cli" [project.optional-dependencies] # development dev = ["pre-commit", "ruff"] graphviz = ["graphviz"] [build-system] requires = ["setuptools"] build-backend = "setuptools.build_meta" [tool.ruff.lint] ignore = ["E501"]