pax_global_header00006660000000000000000000000064143061421750014515gustar00rootroot0000000000000052 comment=0776b5ff9ecf63418dc8158b73686876e4a04ae8 dependency-info-2.2.0/000077500000000000000000000000001430614217500145655ustar00rootroot00000000000000dependency-info-2.2.0/.bandit000066400000000000000000000000401430614217500160210ustar00rootroot00000000000000[bandit] targets = /src/depinfo dependency-info-2.2.0/.editorconfig000066400000000000000000000005071430614217500172440ustar00rootroot00000000000000# Editor Configuration (http://editorconfig.org) root = true [*] charset = utf-8 indent_style = space indent_size = 4 end_of_line = lf insert_final_newline = true trim_trailing_whitespace = true max_line_length = 88 [*.{json,yml}] indent_size = 2 [*.{md,rst}] trim_trailing_whitespace = false [Makefile] indent_style = tab dependency-info-2.2.0/.gitattributes000066400000000000000000000000451430614217500174570ustar00rootroot00000000000000src/depinfo/_version.py export-subst dependency-info-2.2.0/.github/000077500000000000000000000000001430614217500161255ustar00rootroot00000000000000dependency-info-2.2.0/.github/CODE_OF_CONDUCT.md000066400000000000000000000122441430614217500207270ustar00rootroot00000000000000# Contributor Covenant Code of Conduct ## Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards Examples of behavior that contributes to a positive environment for our community include: * Demonstrating empathy and kindness toward other people * Being respectful of differing opinions, viewpoints, and experiences * Giving and gracefully accepting constructive feedback * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience * Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: * The use of sexualized language or imagery, and sexual attention or advances of any kind * Trolling, insulting or derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or email address, without their explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [midnighter@posteo.net](mailto:midnighter@posteo.net?subject=Code%20of%20Conduct). All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. ## Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: ### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. ### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. ### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the community. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see the FAQ at https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. dependency-info-2.2.0/.github/CONTRIBUTING.rst000066400000000000000000000065751430614217500206030ustar00rootroot00000000000000============ Contributing ============ Contributions are welcome, and they are greatly appreciated! Every little bit helps, and credit will always be given. You can contribute in many ways: Report Bugs =========== Report bugs at https://github.com/Midnighter/dependency-info/issues. If you are reporting a bug, please follow the template guidelines. The more detailed your report, the easier and thus faster we can help you. Fix Bugs ======== Look through the GitHub issues for bugs. Anything tagged with "bug" and "help wanted" is open to whoever wants to implement it. Implement Features ================== Look through the GitHub issues for features. Anything tagged with "enhancement" and "help wanted" is open to whoever wants to implement it. Write Documentation =================== dependency-info could always use more documentation, whether as part of the official documentation, in docstrings, or even on the web in blog posts, articles, and such. Submit Feedback =============== The best way to send feedback is to file an issue at https://github.com/Midnighter/dependency-info/issues. If you are proposing a feature: * Explain in detail how it would work. * Keep the scope as narrow as possible, to make it easier to implement. * Remember that this is a volunteer-driven project, and that contributions are welcome :) Get Started! ============ Ready to contribute? Here's how to set up dependency-info for local development. 1. Fork the https://github.com/Midnighter/dependency-info repository on GitHub. 2. Clone your fork locally .. code-block:: console git clone git@github.com:your_name_here/dependency-info.git 3. Install your local copy into a a Python virtual environment. You can `read this guide to learn more `_ about them and how to create one. Alternatively, particularly if you are a Windows or Mac user, you can also use `Anaconda `_. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development .. code-block:: console mkvirtualenv my-env cd dependency-info/ pip install -e .[development] 4. Create a branch for local development using the ``devel`` branch as a starting point. Use ``fix`` or ``feat`` as a prefix .. code-block:: console git checkout devel git checkout -b fix-name-of-your-bugfix Now you can make your changes locally. 5. When you're done making changes, apply the quality assurance tools and check that your changes pass our test suite. This is all included with tox .. code-block:: console make qa tox 6. Commit your changes and push your branch to GitHub. Please use `semantic commit messages `_. .. code-block:: console git add . git commit -m "fix: Your summary of changes" git push origin fix-name-of-your-bugfix 7. Open the link displayed in the message when pushing your new branch in order to submit a pull request. Pull Request Guidelines ======================= Before you submit a pull request, check that it meets these guidelines: 1. The pull request should include tests. 2. If the pull request adds functionality, the docs should be updated. Put your new functionality into a function with a docstring. dependency-info-2.2.0/.github/ISSUE_TEMPLATE/000077500000000000000000000000001430614217500203105ustar00rootroot00000000000000dependency-info-2.2.0/.github/ISSUE_TEMPLATE/01-bug-report.md000066400000000000000000000017751430614217500231500ustar00rootroot00000000000000--- name: Bug report about: Report a bug to help improve this project --- #### Problem description Please explain: * **what** you tried to achieve, * **how** you went about it (referring to the code sample), and * **why** the current behaviour is a problem and what output you expected instead. #### Code Sample Create a [minimal, complete, verifiable example](https://stackoverflow.com/help/mcve). ```python ``` ``` ``` ### Context
``` ```
dependency-info-2.2.0/.github/ISSUE_TEMPLATE/02-question.md000066400000000000000000000010311430614217500227130ustar00rootroot00000000000000--- name: Question about: Ask a question --- ### Checklist - [ ] I searched the [documentation](https://dependency-info.readthedocs.io). - [ ] I looked through [similar issues on GitHub](https://github.com/Midnighter/dependency-info/issues). - [ ] I looked up "How to do ... in dependency-info" on a search engine. ### Question dependency-info-2.2.0/.github/ISSUE_TEMPLATE/03-feature-request.md000066400000000000000000000017561430614217500242040ustar00rootroot00000000000000--- name: Feature request about: Suggest an idea for this project --- ### Checklist - [ ] There are [no similar issues or pull requests](https://github.com/Midnighter/dependency-info/issues) for this yet. ### Is your feature related to a problem? Please describe it. ## Describe the solution you would like. ## Describe alternatives you considered ## Additional context dependency-info-2.2.0/.github/PULL_REQUEST_TEMPLATE.md000066400000000000000000000002171430614217500217260ustar00rootroot00000000000000* [ ] fix #(issue number) * [ ] description of feature/fix * [ ] tests added/passed * [ ] add an entry to the [next release](../CHANGELOG.rst) dependency-info-2.2.0/.github/SUPPORT.md000066400000000000000000000001351430614217500176220ustar00rootroot00000000000000## Support * Please open [an issue](https://github.com/Midnighter/dependency-info/issues). dependency-info-2.2.0/.github/workflows/000077500000000000000000000000001430614217500201625ustar00rootroot00000000000000dependency-info-2.2.0/.github/workflows/main.yml000066400000000000000000000041521430614217500216330ustar00rootroot00000000000000name: CI-CD on: push: branches: - stable - devel tags: - '[0-9]+.[0-9]+.[0-9]+' - '[0-9]+.[0-9]+.[0-9]+rc[0-9]+' pull_request: branches: - stable - devel jobs: test: runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: os: [ubuntu-latest, macos-latest, windows-latest] python-version: ["3.7", "3.8", "3.9", "3.10"] steps: - uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v3 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | python -m pip install --upgrade pip setuptools wheel python -m pip install tox tox-gh-actions - name: Test with tox run: tox -- --cov-report=xml - name: Report coverage shell: bash run: bash <(curl -s https://codecov.io/bash) release: needs: test if: startsWith(github.ref, 'refs/tags') runs-on: ${{ matrix.os }} strategy: matrix: os: [ubuntu-latest] python-version: ["3.10"] steps: - uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v3 with: python-version: ${{ matrix.python-version }} - name: Get tag id: tag run: echo "::set-output name=version::${GITHUB_REF#refs/tags/}" - name: Install dependencies run: | python -m pip install --upgrade pip setuptools wheel python -m pip install twine build - name: Build package run: python -m build - name: Publish to PyPI env: TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }} TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} run: twine upload --skip-existing --non-interactive dist/* - name: GH Release uses: softprops/action-gh-release@v0.1.14 with: body: > Please see https://github.com/${{ github.repository }}/blob/${{ steps.tag.outputs.version }}/CHANGELOG.rst for the full release notes. draft: false prerelease: false dependency-info-2.2.0/.gitignore000066400000000000000000000024061430614217500165570ustar00rootroot00000000000000# Created by .ignore support plugin (hsz.mobi) ### Python template # 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/ *.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/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover .hypothesis/ .pytest_cache/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # pyenv .python-version # celery beat schedule file celerybeat-schedule # 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/ # idea .idea/ dependency-info-2.2.0/CHANGELOG.rst000066400000000000000000000023671430614217500166160ustar00rootroot00000000000000========== Change Log ========== Next Release ------------ 2.2.0 (2022-09-07) ------------------ * Adjust the output order and put the root package in its own section (#14). 2.1.1 (2022-06-02) ------------------ * Update main readme. * Fix bug with formatting empty pairs. 2.1.0 (2022-06-02) ------------------ * Refactor application code. * Rename display type to format. * Introduce deprecated ``print_dependencies`` and ``show_versions`` functions for compatibility. * Test the CLI. 2.0.0 (2022-05-29) ------------------ * Switch to hexagonal architecture. * Switch to code organization inspired by Domain-Driven Design (DDD). * Implement a command line interface (CLI). * Implement a markdown table display. * Create a typed package. * Improve stylistic and type testing. 1.7.0 (2021-02-03) ------------------ * Improve parsing of package information (#6). 1.6.0 (2020-10-11) ------------------ * Switch to versioneer-518. * Remove ``pipdeptree`` and use ``importlib.metadata`` instead. * Support Python version 3.6 - 3.9. 1.5.1 (2019-02-17) ------------------ * Improve internal quality control. 1.5.0 (2019-02-07) ------------------ * Require a newer pipdeptree version. * Introduce black. * Fix parametrized test cases. * Update package configuration. dependency-info-2.2.0/LICENSE000066400000000000000000000236751430614217500156070ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS dependency-info-2.2.0/MANIFEST.in000066400000000000000000000001321430614217500163170ustar00rootroot00000000000000include src/depinfo/_version.py include README.rst include LICENSE include pyproject.toml dependency-info-2.2.0/Makefile000066400000000000000000000041301430614217500162230ustar00rootroot00000000000000################################################################################ # COMMANDS # ################################################################################ .PHONY: qa ## Apply code quality assurance tools. qa: isort src/depinfo/ tests/ setup.py black src/depinfo/ tests/ setup.py ################################################################################ # Self Documenting Commands # ################################################################################ .DEFAULT_GOAL := show-help # Inspired by # # sed script explained: # /^##/: # * save line in hold space # * purge line # * Loop: # * append newline + line to hold space # * go to next line # * if line starts with doc comment, strip comment character off and loop # * remove target prerequisites # * append hold space (+ newline) to line # * replace newline plus comments by `---` # * print line # Separate expressions are necessary because labels cannot be delimited by # semicolon; see .PHONY: show-help show-help: @echo "$$(tput bold)Available rules:$$(tput sgr0)" @echo @sed -n -e "/^## / { \ h; \ s/.*//; \ :doc" \ -e "H; \ n; \ s/^## //; \ t doc" \ -e "s/:.*//; \ G; \ s/\\n## /---/; \ s/\\n/ /g; \ p; \ }" ${MAKEFILE_LIST} \ | LC_ALL='C' sort --ignore-case \ | awk -F '---' \ -v ncol=$$(tput cols) \ -v indent=19 \ -v col_on="$$(tput setaf 6)" \ -v col_off="$$(tput sgr0)" \ '{ \ printf "%s%*s%s ", col_on, -indent, $$1, col_off; \ n = split($$2, words, " "); \ line_length = ncol - indent; \ for (i = 1; i <= n; i++) { \ line_length -= length(words[i]) + 1; \ if (line_length <= 0) { \ line_length = ncol - indent - length(words[i]) - 1; \ printf "\n%*s ", -indent, " "; \ } \ printf "%s ", words[i]; \ } \ printf "\n"; \ }' \ | more $(shell test $(shell uname) = Darwin && \ echo '--no-init --raw-control-chars') dependency-info-2.2.0/README.rst000066400000000000000000000045441430614217500162630ustar00rootroot00000000000000============================== Package Dependency Information ============================== .. image:: https://img.shields.io/pypi/v/depinfo.svg :target: https://pypi.org/project/depinfo/ :alt: Current PyPI Version .. image:: https://img.shields.io/pypi/pyversions/depinfo.svg :target: https://pypi.org/project/dependency-info/ :alt: Supported Python Versions .. image:: https://img.shields.io/pypi/l/depinfo.svg :target: https://www.apache.org/licenses/LICENSE-2.0 :alt: Apache Software License Version 2.0 .. image:: https://img.shields.io/badge/Contributor%20Covenant-v2.0%20adopted-ff69b4.svg :target: .github/CODE_OF_CONDUCT.md :alt: Code of Conduct .. image:: https://github.com/Midnighter/dependency-info/workflows/CI-CD/badge.svg :target: https://github.com/Midnighter/dependency-info/workflows/CI-CD :alt: GitHub Actions .. image:: https://codecov.io/gh/Midnighter/dependency-info/branch/stable/graph/badge.svg :target: https://codecov.io/gh/Midnighter/dependency-info :alt: Codecov .. image:: https://img.shields.io/badge/code%20style-black-000000.svg :target: https://github.com/ambv/black :alt: Code Style Black Example ======= The simplest way to display dependencies is to use the command line tool: .. code-block:: console depinfo "your-package-name" To print the dependencies of this package use (also try the ``--markdown`` option): .. code-block:: console depinfo "depinfo" .. code-block:: console Package Information ------------------- depinfo 2.2.0 Dependency Information ---------------------- black 22.3.0 importlib-metadata missing isort 5.10.1 rich 12.4.4 tox 3.25.0 Build Tools Information ----------------------- pbr 5.9.0 pip 22.1.2 setuptools 62.3.2 wheel 0.37.1 Platform Information -------------------- Linux 5.17.5-76051705-generic-x86_64 CPython 3.10.2 Alternatively you can use this package directly from Python .. code-block:: python from depinfo.application import DisplayApplication DisplayApplication.run("depinfo") Copyright ========= * Copyright © 2018-2022, Moritz E. Beber. * Free software distributed under the `Apache Software License 2.0 `_. dependency-info-2.2.0/pyproject.toml000066400000000000000000000004231430614217500175000ustar00rootroot00000000000000[build-system] build-backend = "setuptools.build_meta" requires = [ "setuptools>=40.6.0", "versioneer-518", "wheel" ] [tool.black] line-length = 88 python-version = ["py38"] [[tool.mypy.overrides]] module = [ "importlib_metadata", ] ignore_missing_imports = true dependency-info-2.2.0/setup.cfg000066400000000000000000000034311430614217500164070ustar00rootroot00000000000000[metadata] name = depinfo url = https://github.com/Midnighter/dependency-info download_url = https://pypi.org/project/depinfo/ project_urls = Source Code = https://github.com/Midnighter/dependency-info Bug Tracker = https://github.com/Midnighter/dependency-info/issues author = Moritz E. Beber author_email = midnighter@posteo.net classifiers = Development Status :: 5 - Production/Stable Intended Audience :: Developers License :: OSI Approved :: Apache Software License Natural Language :: English Operating System :: OS Independent Programming Language :: Python :: 3 :: Only Programming Language :: Python :: 3.7 Programming Language :: Python :: 3.8 Programming Language :: Python :: 3.9 Programming Language :: Python :: 3.10 Programming Language :: Python :: 3.11 Topic :: Utilities license = Apache-2.0 description = List any package's direct dependencies and their versions. long_description = file: README.rst long_description_content_type = text/x-rst keywords = dependency tree version [options] zip_safe = True install_requires = importlib_metadata; python_version <'3.8' python_requires = >=3.7 tests_require = tox packages = find: package_dir = = src [options.packages.find] where = src [options.package_data] depinfo = py.typed [options.entry_points] console_scripts = depinfo = depinfo.infrastructure.application.cli:main [options.extras_require] development = black isort tox rich = rich # See the docstring in versioneer.py for instructions. Note that you must # re-run 'versioneer.py setup' after changing this section, and commit the # resulting files. [versioneer] VCS = git style = pep440 versionfile_source = src/depinfo/_version.py versionfile_build = depinfo/_version.py tag_prefix = dependency-info-2.2.0/setup.py000066400000000000000000000014771430614217500163100ustar00rootroot00000000000000#!/usr/bin/env python # Copyright (c) 2018, Moritz E. # # 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. """Set up the dependency information package.""" import versioneer from setuptools import setup # All other arguments are defined in `setup.cfg`. setup(version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass()) dependency-info-2.2.0/src/000077500000000000000000000000001430614217500153545ustar00rootroot00000000000000dependency-info-2.2.0/src/depinfo/000077500000000000000000000000001430614217500170005ustar00rootroot00000000000000dependency-info-2.2.0/src/depinfo/__init__.py000066400000000000000000000013721430614217500211140ustar00rootroot00000000000000# Copyright (c) 2018, Moritz E. Beber # # 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. """Create top level imports.""" __author__ = "Moritz E. Beber" __email__ = "midnighter@posteo.net" from .application.compatibility import print_dependencies, show_versions dependency-info-2.2.0/src/depinfo/_version.py000066400000000000000000000000001430614217500211640ustar00rootroot00000000000000dependency-info-2.2.0/src/depinfo/application/000077500000000000000000000000001430614217500213035ustar00rootroot00000000000000dependency-info-2.2.0/src/depinfo/application/__init__.py000066400000000000000000000014421430614217500234150ustar00rootroot00000000000000# Copyright (c) 2022, Moritz E. Beber # # 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. from .display_format import DisplayFormat from .abstract_display_service import AbstractDisplayService from .display_service_registry import DisplayServiceRegistry from .display_application import DisplayApplication dependency-info-2.2.0/src/depinfo/application/abstract_display_service.py000066400000000000000000000024221430614217500267250ustar00rootroot00000000000000# Copyright (c) 2022, Moritz E. Beber # # 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. """Provide an abstract base class for dependency information display services.""" from abc import ABC, abstractmethod from depinfo.domain import DependencyReport class AbstractDisplayService(ABC): """Define an abstract base class for dependency information display services.""" @classmethod @abstractmethod def display(cls, report: DependencyReport, max_depth: int = 1, **kwargs) -> None: """ Display a dependency report to a desired maximum depth. Args: report: A dependency report instance. max_depth: The maximum desired depth (default 1). **kwargs: Keyword arguments are passed on to the actual display method. """ dependency-info-2.2.0/src/depinfo/application/compatibility.py000066400000000000000000000033131430614217500245260ustar00rootroot00000000000000# Copyright (c) 2018, Moritz E. Beber # # 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. """Provide deprecated functions for compatibility with previous versions.""" from warnings import warn from .display_application import DisplayApplication def print_dependencies(package_name: str) -> None: """Display dependency information for the given package in a simple format.""" warn( DeprecationWarning( "The function 'print_dependencies' is deprecated since version 2.0.0. " "Please use either the command " "line interface with command 'depinfo' or import " "'depinfo.application.DisplayApplication' in your Python project." ) ) DisplayApplication.run(package_name=package_name) def show_versions() -> None: """Display dependency information for this package in a simple format.""" warn( DeprecationWarning( "The function 'show_versions' is deprecated since version 2.0.0. " "Please use either the command " "line interface with command 'depinfo' or import " "'depinfo.application.DisplayApplication' in your Python project." ) ) DisplayApplication.run(package_name="depinfo") dependency-info-2.2.0/src/depinfo/application/display_application.py000066400000000000000000000040011430614217500257000ustar00rootroot00000000000000# Copyright (c) 2022, Moritz E. Beber # # 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. """Provide an application that displays dependency information.""" from typing import Iterable from depinfo.domain import DependencyReport from .display_format import DisplayFormat from .display_service_registry import DisplayServiceRegistry class DisplayApplication: """Define an application that displays dependency information.""" @classmethod def run( cls, package_name: str, display_format: DisplayFormat = DisplayFormat.Simple, build_tools: Iterable[str] = ( "conda", "flit", "hatch", "mamba", "pbr", "pip", "poetry", "setuptools", "wheel", ), max_depth: int = 1, ) -> None: """ Display the given package's dependencies in the desired format. Args: package_name: The package name for which to generate dependency information. display_format: One of the supported display formats. build_tools: A list of build packages to include. max_depth: The maximum desired depth of requirements nesting. """ report = DependencyReport.from_root( root=package_name, build_tools=build_tools, max_depth=max_depth, ) DisplayServiceRegistry.display_service(display_format=display_format).display( report=report, max_depth=max_depth ) dependency-info-2.2.0/src/depinfo/application/display_format.py000066400000000000000000000021311430614217500246670ustar00rootroot00000000000000# Copyright (c) 2022, Moritz E. Beber # # 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. """Provide a controlled vocabulary for display formats.""" from enum import Enum, auto class AutoNameEnum(Enum): """Define an enumeration base class whose fields' names match the values.""" @staticmethod def _generate_next_value_(name: str, _, __, ___) -> str: """Use a field's name as its value.""" return name class DisplayFormat(AutoNameEnum): """Define an enumeration for supported display formats.""" Simple = auto() Markdown = auto() Rich = auto() Textual = auto() dependency-info-2.2.0/src/depinfo/application/display_service_registry.py000066400000000000000000000027731430614217500270030ustar00rootroot00000000000000# Copyright (c) 2022, Moritz E. Beber # # 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. """Provide a display service registry.""" from typing import Type from .abstract_display_service import AbstractDisplayService from .display_format import DisplayFormat class DisplayServiceRegistry: """Define a registry that returns display service classes based on given type.""" @classmethod def display_service( cls, display_format: DisplayFormat ) -> Type[AbstractDisplayService]: """Return a display service class based on the given display format.""" if display_format is DisplayFormat.Simple: from depinfo.infrastructure.application import SimpleDisplayService return SimpleDisplayService elif display_format is DisplayFormat.Markdown: from depinfo.infrastructure.application import MarkdownTableDisplayService return MarkdownTableDisplayService else: raise ValueError(f"Unknown display format {display_format}.") dependency-info-2.2.0/src/depinfo/domain/000077500000000000000000000000001430614217500202475ustar00rootroot00000000000000dependency-info-2.2.0/src/depinfo/domain/__init__.py000066400000000000000000000013601430614217500223600ustar00rootroot00000000000000# Copyright (c) 2022, Moritz E. Beber # # 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. """Provide domain models.""" from .platform import Platform from .python import Python from .package import Package from .dependency_report import DependencyReport dependency-info-2.2.0/src/depinfo/domain/dependency_report.py000066400000000000000000000113621430614217500243350ustar00rootroot00000000000000# Copyright (c) 2022, Moritz E. Beber # # 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. """Provide a dependency report model with requirements information.""" from __future__ import annotations from collections import deque from dataclasses import dataclass from typing import Deque, Dict, Iterable, Iterator, List, Tuple from .package import Package from .platform import Platform from .python import Python @dataclass(frozen=True) class DependencyReport: """ Define a dependency report with requirements information. A package is defined by its name, version, and requirements. It can be constructed from its name via a convenient factory method. Attributes: root: The root package instance for which to follow dependencies. platform: A `Platform` information instance. python: A `Python` information instance. build_tools: A list of package instances which are considered build tools rather than direct dependencies. packages: A map from package names to instances. """ root: Package platform: Platform python: Python build_tools: List[Package] packages: Dict[str, Package] @classmethod def from_root( cls, root: str, build_tools: Iterable[str], max_depth: int = 1, ) -> DependencyReport: """ Return a package instance potentially with its requirements. A factory class method that returns a package with its name and versions, as well as nested requirements as packages themselves. Args: root: The distribution name of the root package. build_tools: A list of build packages to include. max_depth: The maximum desired depth of requirements nesting. Returns: A dependency report instance with potentially nested requirements. """ discovered = deque([(0, root)]) packages: Dict[str, Package] = {} while len(discovered) > 0: level, name = discovered.popleft() if name in packages: continue packages[name] = pkg = Package.from_name(name) if level < max_depth: discovered.extend(((level + 1, req) for req in pkg.requirements)) tools: List[Package] = [] for name in build_tools: if name in packages: tools.append(packages[name]) continue packages[name] = pkg = Package.from_name(name) tools.append(pkg) return cls( root=packages[root], build_tools=tools, packages=packages, platform=Platform.create(), python=Python.create(), ) def iter_requirements(self, max_depth: int = 1) -> Iterator[Tuple[int, Package]]: """ Iterate over the root package's nested requirements up to a maximum depth. Args: max_depth: The maximum desired depth of requirements nesting to iterate over. Yields: Dependency nesting level, package pairs. """ discovered: Deque[Tuple[int, Package]] = deque() if max_depth > 0: discovered.extend( ((1, self.packages[req]) for req in self.root.requirements) ) while len(discovered) > 0: level, pkg = discovered.popleft() if level < max_depth: discovered.extend( ((level + 1, self.packages[req]) for req in pkg.requirements) ) yield level, pkg def iter_unique_requirements( self, missing_version: str = "missing", max_depth: int = 1 ) -> Iterator[Tuple[str, str]]: """ Iterate over package name, version pairs up to a maximum dependency depth. Args: missing_version: A string to replace missing version information. max_depth: The maximum desired depth of dependency information. Yields: Package name, version pairs. """ seen = set() for _, pkg in self.iter_requirements(max_depth=max_depth): if pkg.name in seen: continue yield pkg.name, missing_version if pkg.version is None else pkg.version seen.add(pkg.name) dependency-info-2.2.0/src/depinfo/domain/package.py000066400000000000000000000060641430614217500222220ustar00rootroot00000000000000# Copyright (c) 2022, Moritz E. Beber # # 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. """Provide a package model.""" from __future__ import annotations import re import sys from dataclasses import dataclass from typing import ClassVar, List, Optional, Pattern if sys.version_info < (3, 8): from importlib_metadata import PackageNotFoundError, distribution else: from importlib.metadata import PackageNotFoundError, distribution @dataclass(frozen=True) class Package: """ Define a package model. A package is defined by its name, version, and requirements. It can be constructed from its name via a convenient factory method. Attributes: name: The package name. version: The package version. requirements: The package's requirements as other packages (if any). """ name: str version: Optional[str] requirements: List[str] _req_pattern: ClassVar[Pattern] = re.compile(r"[\s();<>=]") @classmethod def from_name(cls, name: str) -> Package: """ Return a package instance from its distribution name. A factory class method that returns a package with its name and version, as well as requirements. Args: name: A package's distribution name. Returns: A package instance with its version and requirements if it is installed in the current environment; otherwise only the name is set whereas the version and requirements are empty. """ name = cls._normalize_name(name) try: dist = distribution(name) except PackageNotFoundError: result = cls(name=name, version=None, requirements=[]) else: result = cls( name=name, version=dist.version, requirements=[] if dist.requires is None else [cls._normalize_name(cls._get_name(req)) for req in dist.requires], ) return result @classmethod def _normalize_name(cls, name: str) -> str: """Normalize a package's name to lower case with hyphens only.""" return name.lower().replace("_", "-") @classmethod def _get_name(cls, requirement: str) -> str: """ Return the package name from requirement metadata. Args: requirement: Package requirement metadata as described in PEP 566 (https://peps.python.org/pep-0566/). Returns: The package name. """ return cls._req_pattern.split(requirement, maxsplit=1)[0] dependency-info-2.2.0/src/depinfo/domain/platform.py000066400000000000000000000023351430614217500224500ustar00rootroot00000000000000# Copyright (c) 2022, Moritz E. Beber # # 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. """Provide a platform description.""" from __future__ import annotations import platform from typing import NamedTuple class Platform(NamedTuple): """ Define a platform description. Attributes: name: The platform name, typically one of Linux, Darwin, or Windows. version: The platform's full release string and machine architecture. """ name: str version: str @classmethod def create(cls) -> Platform: """Return a platform instance generated from the current environment.""" return cls( name=platform.system(), version=f"{platform.release()}-{platform.machine()}" ) dependency-info-2.2.0/src/depinfo/domain/python.py000066400000000000000000000022631430614217500221450ustar00rootroot00000000000000# Copyright (c) 2022, Moritz E. Beber # # 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. """Provide a Python distribution description.""" from __future__ import annotations import platform from typing import NamedTuple class Python(NamedTuple): """ Define a Python distribution description. Attributes: name: The implementation name, usually this is CPython. version: The Python version. """ name: str version: str @classmethod def create(cls) -> Python: """Return a Python instance generated from the current environment.""" return cls( name=platform.python_implementation(), version=platform.python_version() ) dependency-info-2.2.0/src/depinfo/infrastructure/000077500000000000000000000000001430614217500220605ustar00rootroot00000000000000dependency-info-2.2.0/src/depinfo/infrastructure/__init__.py000066400000000000000000000011101430614217500241620ustar00rootroot00000000000000# Copyright (c) 2022, Moritz E. Beber # # 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. dependency-info-2.2.0/src/depinfo/infrastructure/application/000077500000000000000000000000001430614217500243635ustar00rootroot00000000000000dependency-info-2.2.0/src/depinfo/infrastructure/application/__init__.py000066400000000000000000000013131430614217500264720ustar00rootroot00000000000000# Copyright (c) 2022, Moritz E. Beber # # 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. from .simple_display_service import SimpleDisplayService from .markdown_table_display_service import MarkdownTableDisplayService dependency-info-2.2.0/src/depinfo/infrastructure/application/cli.py000066400000000000000000000057711430614217500255160ustar00rootroot00000000000000# Copyright (c) 2022, Moritz E. Beber # # 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. """Provide a command line interface for printing dependency information.""" import argparse import logging import sys from typing import List, Optional from depinfo.application import DisplayApplication, DisplayFormat logger = logging.getLogger() MAX_DEPTH = 5 def parse_arguments(argv: Optional[List[str]] = None) -> argparse.Namespace: """Define and immediately parse command line arguments.""" parser = argparse.ArgumentParser( description="Display a package's dependencies, platform, and Python " "information.", ) parser.add_argument( "package_name", metavar="PACKAGE", help="The package's distribution name.", ) default_build_tools = "conda,flit,hatch,mamba,pbr,pip,poetry,setuptools,wheel" parser.add_argument( "--build-tools", help=f"A comma separated list of Python package managers " f"(default {default_build_tools}).", default=default_build_tools, ) default_max_depth = 1 parser.add_argument( "-d", "--max-depth", type=int, help=f"The maximum desired depth of nested dependencies to show " f"(default {default_max_depth}). Should be >= 0 and <{MAX_DEPTH}.", default=default_max_depth, ) parser.add_argument( "--markdown", action="store_true", help="Display information as markdown tables (default false).", ) default_log_level = "WARNING" parser.add_argument( "-l", "--log-level", help=f"The desired log level (default {default_log_level}).", choices=("CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG"), default=default_log_level, ) return parser.parse_args(argv) def main(argv: Optional[List[str]] = None) -> None: """Coordinate argument parsing, input validation, and program execution.""" args = parse_arguments(argv) logging.basicConfig(level=args.log_level, format="[%(levelname)s] %(message)s") if not (0 <= args.max_depth < MAX_DEPTH): logger.critical(f"The maximum depth must be >=0 and <{MAX_DEPTH}.") sys.exit(2) if args.markdown: display_format = DisplayFormat.Markdown else: display_format = DisplayFormat.Simple DisplayApplication.run( package_name=args.package_name, display_format=display_format, build_tools=[token.strip() for token in args.build_tools.split(",")], max_depth=args.max_depth, ) dependency-info-2.2.0/src/depinfo/infrastructure/application/markdown_table_display_service.py000066400000000000000000000076611430614217500332050ustar00rootroot00000000000000# Copyright (c) 2022, Moritz E. Beber # # 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. """Provide a service that displays dependency information as markdown tables.""" from operator import itemgetter from typing import List, Tuple from depinfo.application import AbstractDisplayService from depinfo.domain import DependencyReport class MarkdownTableDisplayService(AbstractDisplayService): """Define a service that displays dependency information as markdown tables.""" @classmethod def display(cls, report: DependencyReport, max_depth: int = 1, **kwargs) -> None: """ Display a dependency report to a desired maximum depth as markdown tables. Args: report: A dependency report instance. max_depth: The maximum desired depth (default 1). **kwargs: Keyword arguments are ignored. """ assert report.root.version is not None # noqa: S101 print( "\n".join( [ "", "### Package Information", "", *cls._format_table( ["Package", "Version"], [(report.root.name, report.root.version)], ), ] ) ) requirements = sorted( report.iter_unique_requirements( missing_version="**missing**", max_depth=max_depth ), key=itemgetter(0), ) print( "\n".join( [ "", "### Dependency Information", "", *cls._format_table(["Package", "Version"], requirements), ] ) ) tools = sorted( ( (pkg.name, pkg.version) for pkg in report.build_tools if pkg.version is not None ), key=itemgetter(0), ) print( "\n".join( [ "", "### Build Tools Information", "", *cls._format_table(["Package", "Version"], tools), ] ) ) print( "\n".join( [ "", "### Platform Information", "", *cls._format_table( ["", ""], [ (report.platform.name, report.platform.version), (report.python.name, report.python.version), ], ), ] ) ) @classmethod def _format_table( cls, header: List[str], pairs: List[Tuple[str, str]] ) -> List[str]: """Format pairs of information as a markdown table with two columns.""" if not pairs: return [] max_len_name = max(max((len(pair[0]) for pair in pairs)), len(header[0])) max_len_version = max(max((len(pair[1]) for pair in pairs)), len(header[1])) result = [ f"| {header[0]:^{max_len_name}} | {header[1]:^{max_len_version}} |", f"|:{'-' * max_len_name}-|-{'-' * max_len_version}:|", ] result.extend( f"| {name:<{max_len_name}} | {version:>{max_len_version}} |" for name, version in pairs ) return result dependency-info-2.2.0/src/depinfo/infrastructure/application/simple_display_service.py000066400000000000000000000065041430614217500315000ustar00rootroot00000000000000# Copyright (c) 2022, Moritz E. Beber # # 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. """Provide a service that displays dependency information as simple tables.""" from operator import itemgetter from typing import List, Tuple from depinfo.application import AbstractDisplayService from depinfo.domain import DependencyReport class SimpleDisplayService(AbstractDisplayService): """Define a service that displays dependency information as simple tables.""" @classmethod def display(cls, report: DependencyReport, max_depth: int = 1, **kwargs) -> None: """ Display a dependency report to a desired maximum depth as simple tables. Args: report: A dependency report instance. max_depth: The maximum desired depth (default 1). **kwargs: Keyword arguments are ignored. """ assert report.root.version is not None # noqa: S101 print( cls._format_section( "Package Information", [(report.root.name, report.root.version)] ) ) print( cls._format_section( "Dependency Information", sorted( report.iter_unique_requirements( missing_version="missing", max_depth=max_depth ), key=itemgetter(0), ), ) ) print( cls._format_section( "Build Tools Information", sorted( ( (pkg.name, pkg.version) for pkg in report.build_tools if pkg.version is not None ), key=itemgetter(0), ), ) ) print( cls._format_section( "Platform Information", [ (report.platform.name, report.platform.version), (report.python.name, report.python.version), ], ) ) @classmethod def _format_section(cls, title: str, pairs: List[Tuple[str, str]]) -> str: """Format a report section with a title.""" return "\n".join( [ "", title, "-" * len(title), *cls._format_pairs(pairs), ] ) @classmethod def _format_pairs(cls, pairs: List[Tuple[str, str]]) -> List[str]: """Format pairs as two fixed width, left- and right-aligned columns.""" if not pairs: return [] max_len_name = max((len(pair[0]) for pair in pairs)) max_len_version = max((len(pair[1]) for pair in pairs)) return [ f"{name:<{max_len_name}} {version:>{max_len_version}}" for name, version in pairs ] dependency-info-2.2.0/src/depinfo/py.typed000066400000000000000000000000001430614217500204650ustar00rootroot00000000000000dependency-info-2.2.0/tests/000077500000000000000000000000001430614217500157275ustar00rootroot00000000000000dependency-info-2.2.0/tests/integration/000077500000000000000000000000001430614217500202525ustar00rootroot00000000000000dependency-info-2.2.0/tests/integration/test_cli.py000066400000000000000000000057511430614217500224420ustar00rootroot00000000000000# Copyright (c) 2022, Moritz E. Beber # # 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. """Test the depinfo command line interface.""" from typing import List import pytest from depinfo.infrastructure.application.cli import main @pytest.mark.parametrize( "options", [ ["-h"], ["--help"], ], ) def test_help(capsys, options: List[str]) -> None: """Expect the help message to be shown.""" with pytest.raises(SystemExit) as exc: main(options) assert exc.value.code == 0 captured = capsys.readouterr() assert "usage:" in captured.out assert "positional arguments:" in captured.out def test_simple_format(capsys) -> None: """Expect the dependency information in simple format.""" main(["depinfo"]) captured = capsys.readouterr() lines = captured.out.split("\n") assert lines[1].startswith("Package Information") assert lines[2].startswith("-------------------") assert lines[3].startswith("depinfo") assert lines[5].startswith("Dependency Information") assert lines[6].startswith("----------------------") assert any(line.startswith("pip") for line in lines[7:]) assert any(line.startswith("setuptools") for line in lines[7:]) assert any(line.startswith("wheel") for line in lines[7:]) assert any(line.startswith("Build Tools Information") for line in lines[7:]) assert any(line.startswith("Platform Information") for line in lines[7:]) def test_markdown_format(capsys) -> None: """Expect the dependency information in markdown format.""" main(["--markdown", "depinfo"]) captured = capsys.readouterr() assert "### Package Information" in captured.out assert "| depinfo " in captured.out assert "### Dependency Information" in captured.out assert "### Build Tools Information" in captured.out assert "| pip " in captured.out assert "| setuptools " in captured.out assert "| wheel " in captured.out assert "### Platform Information" in captured.out @pytest.mark.parametrize("depth", range(5)) def test_max_depth(depth: int) -> None: """Test that different dependency nesting depths can be requested.""" main(["--max-depth", str(depth), "depinfo"]) def test_too_deep(caplog) -> None: """Test that there is a maximum allowed depth.""" with pytest.raises(SystemExit) as exc: main(["--max-depth", str(5), "depinfo"]) assert exc.value.code == 2 assert any( msg == "The maximum depth must be >=0 and <5." for msg in caplog.messages ) dependency-info-2.2.0/tests/integration/test_compatibility.py000066400000000000000000000045551430614217500245450ustar00rootroot00000000000000# Copyright (c) 2022, Moritz E. Beber # # 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. """Test the deprecated compatibility functions.""" import pytest from depinfo import print_dependencies, show_versions def test_print_dependencies(capsys) -> None: """Expect all printed information in order.""" with pytest.deprecated_call(): print_dependencies("depinfo") captured = capsys.readouterr() lines = captured.out.split("\n") assert lines[1].startswith("Package Information") assert lines[2].startswith("-------------------") assert lines[3].startswith("depinfo") assert lines[5].startswith("Dependency Information") assert lines[6].startswith("----------------------") assert any(line.startswith("pip") for line in lines[7:]) assert any(line.startswith("setuptools") for line in lines[7:]) assert any(line.startswith("wheel") for line in lines[7:]) assert any(line.startswith("Build Tools Information") for line in lines[7:]) assert any(line.startswith("Platform Information") for line in lines[7:]) def test_show_versions(capsys) -> None: """Expect all printed information in order.""" with pytest.deprecated_call(): show_versions() captured = capsys.readouterr() lines = captured.out.split("\n") assert lines[1].startswith("Package Information") assert lines[2].startswith("-------------------") assert lines[3].startswith("depinfo") assert lines[5].startswith("Dependency Information") assert lines[6].startswith("----------------------") assert any(line.startswith("pip") for line in lines[7:]) assert any(line.startswith("setuptools") for line in lines[7:]) assert any(line.startswith("wheel") for line in lines[7:]) assert any(line.startswith("Build Tools Information") for line in lines[7:]) assert any(line.startswith("Platform Information") for line in lines[7:]) dependency-info-2.2.0/tests/unit/000077500000000000000000000000001430614217500167065ustar00rootroot00000000000000dependency-info-2.2.0/tests/unit/domain/000077500000000000000000000000001430614217500201555ustar00rootroot00000000000000dependency-info-2.2.0/tests/unit/domain/test_dependency_report.py000066400000000000000000000060651430614217500253060ustar00rootroot00000000000000# Copyright (c) 2022, Moritz E. Beber # # 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. """Test that the dependency report works as expected.""" from typing import Dict import pytest from depinfo.domain import DependencyReport, Package, Platform, Python @pytest.fixture(scope="module") def platform() -> Platform: """Provide a platform fixture.""" return Platform(name="Pi", version="3.1.4") @pytest.fixture(scope="module") def python() -> Python: """Provide a Python fixture.""" return Python(name="PyPy", version="4.2.0") @pytest.fixture(scope="module") def depinfo() -> Package: """Provide a package fixture.""" return Package.from_name("depinfo") @pytest.fixture(scope="module") def report(platform: Platform, python: Python, depinfo: Package) -> DependencyReport: """Provide a dependency report fixture.""" tools = ["pip", "setuptools"] packages = {depinfo.name: depinfo} for name in depinfo.requirements + tools: packages[name] = Package.from_name(name) return DependencyReport( root=depinfo, platform=platform, python=python, build_tools=[packages[name] for name in tools], packages=packages, ) @pytest.mark.parametrize( "attributes", [{"build_tools": [], "packages": {}}], ) def test_init( attributes: Dict[str, str], platform: Platform, python: Python, depinfo: Package ) -> None: """Test that the dependency report model can be initialized correctly.""" pkg = DependencyReport(root=depinfo, platform=platform, python=python, **attributes) for attr, value in attributes.items(): assert getattr(pkg, attr) == value def test_iter_requirements(report: DependencyReport, depinfo: Package) -> None: """Test that requirements can be iterated as expected.""" assert {pkg.name for _, pkg in report.iter_requirements()}.issuperset( {"importlib-metadata"} ) assert {pkg.name for pkg in report.build_tools}.issuperset({"pip", "setuptools"}) def test_iter_unique_requirements(report: DependencyReport) -> None: """Test that unique requirements can be iterated as expected.""" assert {name for name, _ in report.iter_unique_requirements()}.issuperset( {"importlib-metadata"} ) def test_from_root() -> None: """Test dependency report creation from a root name.""" report = DependencyReport.from_root("depinfo", ("pip", "setuptools")) assert {pkg.name for _, pkg in report.iter_requirements()}.issuperset( {"importlib-metadata"} ) assert {pkg.name for pkg in report.build_tools}.issuperset({"pip", "setuptools"}) dependency-info-2.2.0/tests/unit/domain/test_package.py000066400000000000000000000032611430614217500231630ustar00rootroot00000000000000# Copyright (c) 2022, Moritz E. Beber # # 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. """Test that package information is detected as expected.""" from typing import Dict import pytest from depinfo.domain import Package @pytest.mark.parametrize( "attributes", [ {"name": "cystalball", "version": None, "requirements": []}, {"name": "cystalball", "version": "4.2.0", "requirements": []}, {"name": "cystalball", "version": "4.2.0", "requirements": ["pip", "wheel"]}, ], ) def test_init(attributes: Dict[str, str]) -> None: """Test that the package model can be initialized correctly.""" pkg = Package(**attributes) for attr, value in attributes.items(): assert getattr(pkg, attr) == value def test_from_name() -> None: """Test the package factory with an existing package name.""" pkg = Package.from_name("depinfo") assert pkg.name == "depinfo" assert "importlib-metadata" in pkg.requirements def test_missing_name() -> None: """Test the package factory with a missing package name.""" pkg = Package.from_name("cystalball") assert pkg.name == "cystalball" assert pkg.version is None assert pkg.requirements == [] dependency-info-2.2.0/tests/unit/domain/test_platform.py000066400000000000000000000026171430614217500234200ustar00rootroot00000000000000# Copyright (c) 2022, Moritz E. Beber # # 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. """Test that platform information is detected as expected.""" import sys from typing import Dict import pytest from depinfo.domain import Platform @pytest.mark.parametrize("attributes", [{"name": "Linux", "version": "4.2"}]) def test_init(attributes: Dict[str, str]) -> None: """Test that the platform model can be initialized correctly.""" platform = Platform(**attributes) for attr, value in attributes.items(): assert getattr(platform, attr) == value def test_create() -> None: """Test that the platform is detected consistently.""" platform = Platform.create() os_name = sys.platform.title() if os_name == "Win32": # Just because it's fun for platform and sys to provide different values. os_name = "Windows" assert platform.name == os_name assert platform.version dependency-info-2.2.0/tests/unit/domain/test_python.py000066400000000000000000000023571430614217500231160ustar00rootroot00000000000000# Copyright (c) 2022, Moritz E. Beber # # 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. """Test that Python information is detected as expected.""" import sys from typing import Dict import pytest from depinfo.domain import Python @pytest.mark.parametrize("attributes", [{"name": "PyPy", "version": "4.0.0"}]) def test_init(attributes: Dict[str, str]) -> None: """Test that the Python model can be initialized correctly.""" python = Python(**attributes) for attr, value in attributes.items(): assert getattr(python, attr) == value def test_create() -> None: """Test that the Python version is detected consistently.""" python = Python.create() assert python.name assert python.version == sys.version.split(maxsplit=1)[0] dependency-info-2.2.0/tox.ini000066400000000000000000000041321430614217500161000ustar00rootroot00000000000000[tox] envlist = flake8, safety, mypy, install, py3{7,8,9,10,11} isolated_build = true [gh-actions] python = 3.7: install, flake8, mypy, safety, py37 3.8: install, mypy, safety, py38 3.9: install, mypy, safety, py39 3.10: install, mypy, safety, py310 3.11: install, mypy, safety, py311 [testenv] # Define base for all test environments. [testenv:flake8] skip_install = True deps= darglint flake8 flake8-bandit flake8-black flake8-bugbear flake8-builtins flake8-comprehensions flake8-docstrings flake8-eradicate flake8-isort flake8-pytest-style commands= flake8 {toxinidir}/src/depinfo {toxinidir}/tests {toxinidir}/setup.py [testenv:safety] deps= safety commands= safety check --full-report [testenv:mypy] deps= mypy commands= mypy {toxinidir}/src/depinfo [testenv:install] skip_install = True deps= build twine commands= pip check {toxinidir} python -m build {toxinidir} twine check {toxinidir}/dist/* [testenv:py3{7,8,9,10,11}] deps = pytest pytest-cov pytest-raises commands = pytest --cov=depinfo --cov-report=term {posargs} ################################################################################ # Testing tools configuration # ################################################################################ [pytest] testpaths = tests markers = raises [coverage:paths] source = src/depinfo */site-packages/depinfo [coverage:run] branch = true parallel = true omit = src/depinfo/_version.py [coverage:report] exclude_lines = # Have to re-enable the standard pragma pragma: no cover precision = 2 omit = src/depinfo/_version.py [flake8] max-line-length = 88 exclude = __init__.py # The following conflict with `black` which is the more pedantic. ignore = E203 W503 D202 # darglint strictness = long docstring_style = google [isort] skip = __init__.py profile = black indent = 4 lines_after_imports = 2 known_first_party = depinfo known_third_party = pytest setuptools versioneer