pax_global_header00006660000000000000000000000064145413753370014526gustar00rootroot0000000000000052 comment=8d88a2d72a3dbdb1d1443788c2e0142658b2b0ba distro-1.9.0/000077500000000000000000000000001454137533700130415ustar00rootroot00000000000000distro-1.9.0/.coveragerc000066400000000000000000000004231454137533700151610ustar00rootroot00000000000000[run] branch = True source = distro.py [paths] source = distro.py .tox/*/lib/python*/site-packages/distro.py .tox/pypy/site-packages/distro.py [report] exclude_lines = if __name__ == .__main__.: raise ImportError raise subprocess.CalledProcessErrordistro-1.9.0/.github/000077500000000000000000000000001454137533700144015ustar00rootroot00000000000000distro-1.9.0/.github/dependabot.yml000066400000000000000000000003341454137533700172310ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: "github-actions" commit-message: include: "scope" prefix: "Actions" directory: "/" labels: - "enhancement" schedule: interval: "weekly" distro-1.9.0/.github/stale.yml000066400000000000000000000005641454137533700162410ustar00rootroot00000000000000# See https://github.com/probot/stale for defaults, many of which are not set here. issues: daysUntilStale: 360 pulls: daysUntilStale: 60 markComment: > This pull request has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. daysUntilClose: 7 distro-1.9.0/.github/workflows/000077500000000000000000000000001454137533700164365ustar00rootroot00000000000000distro-1.9.0/.github/workflows/ci.yaml000066400000000000000000000032321454137533700177150ustar00rootroot00000000000000name: CI on: - push - pull_request jobs: lint: name: Lint runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v5 with: python-version: 3.x - name: Install tox run: python -m pip install tox - name: Run tox run: tox -e lint test: name: Python ${{ matrix.python }} runs-on: ${{ matrix.os }} strategy: matrix: os: - "ubuntu-latest" python: - "3.7" - "3.8" - "3.9" - "3.10" - "3.11" - "3.12" include: - os: "ubuntu-20.04" python: "3.6" - os: "ubuntu-20.04" python: "pypy-3.6" - os: "ubuntu-22.04" python: "pypy-3.10" - os: "macos-12" python: 3.12 steps: - uses: actions/checkout@v4 - name: Set up Python ${{ matrix.python }} uses: actions/setup-python@v5 with: python-version: ${{ matrix.python }} - name: Install tox run: python -m pip install tox - name: Run tox run: tox -e py - name: Upload coverage to Codecov uses: codecov/codecov-action@v3 with: files: .coverage windows: name: Windows runs-on: windows-latest steps: - uses: actions/checkout@v4 - uses: codecov/codecov-action@v3 - name: Set up Python uses: actions/setup-python@v5 with: python-version: 3.x - name: Install tox run: python -m pip install tox - name: Run tox run: tox -e py distro-1.9.0/.github/workflows/deploy.yml000066400000000000000000000013411454137533700204540ustar00rootroot00000000000000name: "Deploy to PyPI" on: workflow_dispatch: inputs: tag: description: "Git tag to deploy to PyPI" required: true jobs: deploy: name: "Deploy to PyPI" runs-on: ubuntu-latest environment: Deploy steps: - uses: actions/checkout@v4 with: ref: ${{ github.event.inputs.tag }} - uses: actions/setup-python@v5 with: python-version: 3.x - shell: bash run: | python -m pip install --disable-pip-version-check -U pip python -m pip install -U build twine python -m build python -m twine check dist/* python -m twine upload --username=__token__ --password=${{ secrets.PYPI_TOKEN }} dist/* distro-1.9.0/.gitignore000066400000000000000000000011521454137533700150300ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] # C extensions *.so # Distribution / packaging .Python /env/ /bin/ /build/ /develop-eggs/ /dist/ /eggs/ /lib/ /lib64/ /parts/ /sdist/ /var/ /*.egg-info/ .installed.cfg *.egg src/*.egg-info/ # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports /htmlcov/ /.tox/ .coverage .cache nosetests.xml coverage.xml # Translations *.mo # Mr Developer .mr.developer.cfg .project .pydevproject # Rope .ropeproject # Django stuff: *.log *.pot # Sphinx documentation /docs/_build/ *.iml *COMMIT_MSG # QuickBuild .qbcache/ distro-1.9.0/.pre-commit-config.yaml000066400000000000000000000007711454137533700173270ustar00rootroot00000000000000repos: - repo: https://github.com/psf/black rev: 22.3.0 hooks: - id: black args: ["--target-version", "py36"] - repo: https://github.com/PyCQA/flake8 rev: 6.1.0 hooks: - id: flake8 - repo: https://github.com/pycqa/isort rev: 5.12.0 hooks: - id: isort - repo: https://github.com/pre-commit/mirrors-mypy rev: v0.910 hooks: - id: mypy args: ["--strict"] additional_dependencies: [ "pytest==6.2.5", ] distro-1.9.0/.readthedocs.yaml000066400000000000000000000002341454137533700162670ustar00rootroot00000000000000version: 2 build: os: ubuntu-22.04 tools: python: "3.12" sphinx: configuration: docs/conf.py python: install: - method: pip path: .distro-1.9.0/CHANGELOG.md000066400000000000000000000275741454137533700146710ustar00rootroot00000000000000## 1.9.0 (2023.12.19) ENHANCEMENTS: * Refactor distro.info() method to return an InfoDict [[#360](https://github.com/python-distro/distro/pull/360)] * Ignore the file '/etc/board-release' [[#353](https://github.com/python-distro/distro/pull/353)] * Ignore the file '/etc/ec2_version' [[#359](https://github.com/python-distro/distro/pull/353)] RELEASE: * Run Python 3.6 on Ubuntu 20.04 for CI and bump isort [[#355](https://github.com/python-distro/distro/pull/355)] TESTS: * Test on modern versions of CPython and PyPy and macOS [[#362](https://github.com/python-distro/distro/pull/362)] * Add support for ALT Linux Server 10.1 distribution [[#354](https://github.com/python-distro/distro/pull/354)] * Add Debian Testing to the tests [[#356](https://github.com/python-distro/distro/pull/356)] * Update archlinux resource for tests [[#352](https://github.com/python-distro/distro/pull/352)] ## 1.8.0 (2022.10.10) BACKWARD COMPATIBILITY: * Replace `setup.py` with `build` [[#342](https://github.com/python-distro/distro/pull/342)] ENHANCEMENTS: * Lowered `LinuxDistribution._distro_release_info` method complexity [[#327](https://github.com/python-distro/distro/pull/327)] * Added official support for Buildroot distribution [[#329](https://github.com/python-distro/distro/pull/329)] * Added official support for Guix distribution [[#330](https://github.com/python-distro/distro/pull/330)] * Added support for `/etc/debian_version` [[#333](https://github.com/python-distro/distro/pull/333)] & [[#349](https://github.com/python-distro/distro/pull/349)] * Fixed a typography in CONTRIBUTING.md [[#340](https://github.com/python-distro/distro/pull/340)] * Improved README.md "Usage" code block [[#343](https://github.com/python-distro/distro/pull/343)] RELEASE: * Bumped black to v22.3.0 in pre-commit.ci configuration [[#331](https://github.com/python-distro/distro/pull/331)] * Enabled GitHub Dependabot to keep GitHub Actions up to date [[#335](https://github.com/python-distro/distro/pull/335)] ## 1.7.0 (2022.02.15) BACKWARD COMPATIBILITY: * Dropped support for EOL Pythons 2.7, 3.4 and 3.5 [[#281](https://github.com/python-distro/distro/pull/281)] * Dropped support for LSB and `uname` back-ends when `--root-dir` is specified [[#311](https://github.com/python-distro/distro/pull/311)] * Moved `distro.py` to `src/distro/distro.py` [[#315](https://github.com/python-distro/distro/pull/315)] ENHANCEMENTS: * Documented that `distro.version()` can return an empty string on rolling releases [[#312](https://github.com/python-distro/distro/pull/312)] * Documented support for Python 3.10 [[#316](https://github.com/python-distro/distro/pull/316)] * Added official support for Rocky Linux distribution [[#318](https://github.com/python-distro/distro/pull/318)] * Added a shebang to `distro.py` to allow standalone execution [[#313](https://github.com/python-distro/distro/pull/313)] * Added support for AIX platforms [[#311](https://github.com/python-distro/distro/pull/311)] * Added compliance for PEP-561 [[#315](https://github.com/python-distro/distro/pull/315)] BUG FIXES: * Fixed `include_uname` parameter oversight [[#305](https://github.com/python-distro/distro/pull/305)] * Fixed crash when `uname -rs` output is empty [[#304](https://github.com/python-distro/distro/pull/304)] * Fixed Amazon Linux identifier in `distro.id()` documentation [[#318](https://github.com/python-distro/distro/pull/318)] * Fixed OpenSuse >= 15 support [[#319](https://github.com/python-distro/distro/pull/319)] * Fixed encoding issues when opening distro release files [[#324](https://github.com/python-distro/distro/pull/324)] * Fixed `linux_distribution` regression introduced in [[#230](https://github.com/python-distro/distro/pull/230)] [[#325](https://github.com/python-distro/distro/pull/325)] ## 1.6.0 (2021.7.30) BACKWARDS COMPATIBILITY: * Deprecated the `distro.linux_distribution()` function. Use `distro.id()`, `distro.version()` and `distro.name()` instead [[#296](https://github.com/python-distro/distro/pull/296)] * Deprecated Python 2.7, 3.4 and 3.5 support. Further releases will only support Python 3.6+ ENHANCEMENTS: * Added type hints to `distro` module [[#269](https://github.com/python-distro/distro/pull/269)] * Added `__version__` for checking `distro` version [[#292](https://github.com/python-distro/distro/pull/292)] * Added support for arbitrary rootfs via the `root_dir` parameter [[#247](https://github.com/python-distro/distro/pull/247)] * Added the `--root-dir` option to CLI [[#161](https://github.com/python-distro/distro/issues/161)] * Added fallback to `/usr/lib/os-release` when `/etc/os-release` isn't available [[#262](https://github.com/python-distro/distro/pull/262)] BUG FIXES: * Fixed `subprocess.CalledProcessError` when running `lsb_release` [[#261](https://github.com/python-distro/distro/pull/261)] * Ignore `/etc/iredmail-release` file while parsing distribution [[#268](https://github.com/python-distro/distro/pull/268)] * Use a binary file for `/dev/null` to avoid `TextIOWrapper` overhead [[#271](https://github.com/python-distro/distro/pull/271)] RELEASE: * Moved repository from `nir0s/distro` to [`python-distro/distro`](https://github.com/python-distro/distro) on GitHub. ## 1.5.0 (2020.3.30) BACKWARD COMPATIBILITY: * Keep output as native string so we can compatible with python2 interface [[#248](https://github.com/python-distro/distro/pull/248)] ENHANCEMENTS: BUG FIXES: * Fix detection of RHEL 6 ComputeNode [[#255](https://github.com/python-distro/distro/issues/255)] * Fix Oracle 4/5 lsb_release id and names [[#250](https://github.com/python-distro/distro/pull/250)] * Ignore /etc/plesk-release file while parsing distribution [[#246](https://github.com/python-distro/distro/pull/246)] TESTS: * Test on MidnightBSD [[#254](https://github.com/python-distro/distro/issues/254)] RELEASE: * Remove build testing on Python 3.3 and add pypy 3.5 and Python 3.7 and 3.8 [[#244](https://github.com/python-distro/distro/pull/244)] * Fix Windows build due to Appveyor not supporting builds on Python 2.7 anymore [[#257](https://github.com/python-distro/distro/pull/257)] Additionally, The Python2.6 branch was fixed to support distro version 1.4.0. It is now passing all tests. Thanks [abadger](https://github.com/abadger)! ## 1.4.0 (2019.2.4) BACKWARD COMPATIBILITY: * Prefer the VERSION_CODENAME field of os-release to parsing it from VERSION [[#230](https://github.com/python-distro/distro/pull/230)] BUG FIXES: * Return _uname_info from the uname_info() method [[#233](https://github.com/python-distro/distro/pull/233)] * Fixed CloudLinux id discovery [[#234](https://github.com/python-distro/distro/pull/234)] * Update Oracle matching [[#224](https://github.com/python-distro/distro/pull/224)] DOCS: * Update Fedora package link [[#225](https://github.com/python-distro/distro/pull/225)] * Distro is the recommended replacement for platform.linux_distribution [[#220](https://github.com/python-distro/distro/pull/220)] RELEASE: * Use Markdown for long description in setup.py [[#219](https://github.com/python-distro/distro/pull/219)] Additionally, The Python2.6 branch was fixed and rebased on top of master. It is now passing all tests. Thanks [abadger](https://github.com/abadger)! ## 1.3.0 (2018.05.09) ENHANCEMENTS: * Added support for OpenBSD, FreeBSD, and NetBSD [[#207](https://github.com/python-distro/distro/issues/207)] TESTS: * Add test for Kali Linux Rolling [[#214](https://github.com/python-distro/distro/issues/214)] DOCS: * Update docs with regards to #207 [[#209](https://github.com/python-distro/distro/issues/209)] * Add Ansible reference implementation and fix arch-linux link [[#213](https://github.com/python-distro/distro/issues/213)] * Add facter reference implementation [[#213](https://github.com/python-distro/distro/issues/213)] ## 1.2.0 (2017.12.24) BACKWARD COMPATIBILITY: * Don't raise ImportError on non-linux platforms [[#202](https://github.com/python-distro/distro/issues/202)] ENHANCEMENTS: * Lazily load the LinuxDistribution data [[#201](https://github.com/python-distro/distro/issues/201)] BUG FIXES: * Stdout of shell should be decoded with sys.getfilesystemencoding() [[#203](https://github.com/python-distro/distro/issues/203)] TESTS: * Explicitly set Python versions on Travis for flake [[#204](https://github.com/python-distro/distro/issues/204)] ## 1.1.0 (2017.11.28) BACKWARD COMPATIBILITY: * Drop python3.3 support [[#199](https://github.com/python-distro/distro/issues/199)] * Remove Official Python26 support [[#195](https://github.com/python-distro/distro/issues/195)] TESTS: * Add MandrivaLinux test case [[#181](https://github.com/python-distro/distro/issues/181)] * Add test cases for CloudLinux 5, 6, and 7 [[#180](https://github.com/python-distro/distro/issues/180)] RELEASE: * Modify MANIFEST to include resources for tests and docs in source tarballs [[97c91a1](97c91a1)] ## 1.0.4 (2017.04.01) BUG FIXES: * Guess common \*-release files if /etc not readable [[#175](https://github.com/python-distro/distro/issues/175)] ## 1.0.3 (2017.03.19) ENHANCEMENTS: * Show keys for empty values when running distro from the CLI [[#160](https://github.com/python-distro/distro/issues/160)] * Add manual mapping for `redhatenterpriseserver` (previously only redhatenterpriseworkstation was mapped) [[#148](https://github.com/python-distro/distro/issues/148)] * Race condition in `_parse_distro_release_file` [[#163](https://github.com/python-distro/distro/issues/163)] TESTS: * Add RHEL5 test case [[#165](https://github.com/python-distro/distro/issues/165)] * Add OpenELEC test case [[#166](https://github.com/python-distro/distro/issues/166)] * Replace nose with pytest [[#158](https://github.com/python-distro/distro/issues/158)] RELEASE: * Update classifiers * Update supported Python versions (with py36) ## 1.0.2 (2017.01.12) TESTS: * Test on py33, py36 and py3 based flake8 RELEASE: * Add MANIFEST file (which also includes the LICENSE as part of Issue [[#139](https://github.com/python-distro/distro/issues/139)]) * Default to releasing using Twine [[#121](https://github.com/python-distro/distro/issues/121)] * Add setup.cfg file [[#145](https://github.com/python-distro/distro/issues/145)] * Update license in setup.py ## 1.0.1 (2016-11-03) ENHANCEMENTS: * Prettify distro -j's output and add more elaborate docs [[#147](https://github.com/python-distro/distro/issues/147)] * Decode output of `lsb_release` as utf-8 [[#144](https://github.com/python-distro/distro/issues/144)] * Logger now uses `message %s, string` form to not-evaulate log messages if unnecessary [[#145](https://github.com/python-distro/distro/issues/145)] TESTS: * Increase code-coverage [[#146](https://github.com/python-distro/distro/issues/146)] * Fix landscape code-quality warnings [[#145](https://github.com/python-distro/distro/issues/145)] RELEASE: * Add CONTRIBUTING.md ## 1.0.0 (2016-09-25) BACKWARD COMPATIBILITY: * raise exception when importing on non-supported platforms [[#129](https://github.com/python-distro/distro/issues/129)] ENHANCEMENTS: * Use `bytes` invariantly [[#135](https://github.com/python-distro/distro/issues/135)] * Some minor code adjustments plus a CLI [[#134](https://github.com/python-distro/distro/issues/134)] * Emit stderr if `lsb_release` fails BUG FIXES: * Fix some encoding related issues TESTS: * Add many test cases (e.g. Raspbian 8, CoreOS, Amazon Linux, Scientific Linux, Gentoo, Manjaro) * Completely redo the testing framework to make it easier to add tests * Test on pypy RELEASE: * Remove six as a dependency ## 0.6.0 (2016-04-21) This is the first release of `distro`. All previous work was done on `ld` and therefore unmentioned here. See the release log in GitHub if you want the entire log. BACKWARD COMPATIBILITY: * No longer a package. constants.py has been removed and distro is now a single module ENHANCEMENTS: * distro.info() now receives best and pretty flags * Removed get_ prefix from get_*_release_attr functions * Codename is now passed in distro.info() TESTS: * Added Linux Mint test case * Now testing on Python 3.4 DOCS: * Documentation fixes distro-1.9.0/CONTRIBUTING.md000066400000000000000000000042771454137533700153040ustar00rootroot00000000000000# General * Contributing to distro identification currently doesn't have any specific standards and rather depends on the specific implementation. * A 100% coverage is expected for each PR unless explicitly authorized by the reviewer. * Please try to maintain maximum code-health (via landscape.io). # Contributing distro specific tests Distro's tests are implemented via a standardized framework under `tests/test_distro.py` For each distribution, tests should be added in the relevant class according to which distribution file(s) exists on it, so, for example, tests should be added under `TestOSRelease` where `/etc/os-release` is available. The tests must be self-contained, meaning that the release files for the distribution should be maintained in the repository under `tests/resources/distros/distribution_name+distribution_version`. A tests method would like somewhat like this: ```python def test_centos7_os_release(self): desired_outcome = { 'id': 'centos', 'name': 'CentOS Linux', 'pretty_name': 'CentOS Linux 7 (Core)', 'version': '7', 'pretty_version': '7 (Core)', 'best_version': '7', 'like': 'rhel fedora', 'codename': 'Core' } self._test_outcome(desired_outcome) ``` The framework will automatically try to pick up the relevant file according to the method's name (`centos7` meaning the folder should be named `centos7` as well) and compare the `desired_outcome` with the parsed files found under the test dir. The exception to the rule is under the `TestDistroRelease` test class which should look somewhat like this: ```python def test_centos5_dist_release(self): desired_outcome = { 'id': 'centos', 'name': 'CentOS', 'pretty_name': 'CentOS 5.11 (Final)', 'version': '5.11', 'pretty_version': '5.11 (Final)', 'best_version': '5.11', 'codename': 'Final', 'major_version': '5', 'minor_version': '11' } self._test_outcome(desired_outcome, 'centos', '5') ``` Where the name of the method is not indicative of the lookup folder but rather the two last arguments in `_test_outcome`. A test case is mandatory under `TestOverall` for a PR to be complete. distro-1.9.0/CONTRIBUTORS.md000066400000000000000000000003021454137533700153130ustar00rootroot00000000000000We thank anyone who has contributed to this project, and welcome anyone to contribute further. For a list of contributors, please see https://github.com/python-distro/distro/graphs/contributorsdistro-1.9.0/LICENSE000066400000000000000000000260751454137533700140600ustar00rootroot00000000000000Apache 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 APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} 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 http://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. distro-1.9.0/MANIFEST.in000066400000000000000000000002171454137533700145770ustar00rootroot00000000000000include *.md include *.py include *.txt include LICENSE include CHANGES include Makefile graft tests include docs/* global-exclude *.py[co] distro-1.9.0/Makefile000066400000000000000000000047741454137533700145150ustar00rootroot00000000000000# Copyright 2015-2021 Nir Cohen # # 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 # # http://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. # Name of this package PACKAGENAME = distro # You can set these variables from the command line, and also # from the environment for the first two. SPHINXOPTS ?= -n -v SPHINXBUILD ?= sphinx-build SPHINXSOURCEDIR = docs SPHINXBUILDDIR = docs/_build .PHONY: help help: @echo 'Please use "make " where is one of' @echo " release - build a release and publish it" @echo " dev - prepare a development environment (includes tests)" @echo " instdev - prepare a development environment (no tests)" @echo " install - install into current Python environment" @echo " clobber - remove any build products" @echo " build - build the package" @echo " test - test from this directory using tox, including test coverage" @echo " publish - upload to PyPI" @echo " clean - remove any temporary build products" @echo " dry-run - perform all action required for a release without actually releasing" @$(SPHINXBUILD) -M help "$(SPHINXSOURCEDIR)" "$(SPHINXBUILDDIR)" $(SPHINXOPTS) $(O) .PHONY: release release: test clean build publish @echo "$@ done." .PHONY: test test: pip install 'tox>=1.9.0' tox @echo "$@ done." .PHONY: clean clean: rm -rf dist build $(PACKAGENAME).egg-info @echo "$@ done." .PHONY: build build: python -m build .PHONY: publish publish: twine upload -r pypi dist/$(PACKAGENAME)-* @echo "$@ done." .PHONY: dry-run dry-run: test clean build @echo "$@ done." .PHONY: dev dev: instdev test @echo "$@ done." .PHONY: instdev instdev: pip install -r dev-requirements.txt pip install -e . @echo "$@ done." .PHONY: install install: pip install . @echo "$@ done." .PHONY: clobber clobber: clean rm -rf $(SPHINXBUILDDIR) @echo "$@ done." # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). .PHONY: Makefile %: Makefile @$(SPHINXBUILD) -M $@ "$(SPHINXSOURCEDIR)" "$(SPHINXBUILDDIR)" $(SPHINXOPTS) $(O) distro-1.9.0/README.md000066400000000000000000000124301454137533700143200ustar00rootroot00000000000000Distro - an OS platform information API ======================================= [![CI Status](https://github.com/python-distro/distro/workflows/CI/badge.svg)](https://github.com/python-distro/distro/actions/workflows/ci.yaml) [![PyPI version](http://img.shields.io/pypi/v/distro.svg)](https://pypi.python.org/pypi/distro) [![Supported Python Versions](https://img.shields.io/pypi/pyversions/distro.svg)](https://img.shields.io/pypi/pyversions/distro.svg) [![Code Coverage](https://codecov.io/github/python-distro/distro/coverage.svg?branch=master)](https://codecov.io/github/python-distro/distro?branch=master) [![Is Wheel](https://img.shields.io/pypi/wheel/distro.svg?style=flat)](https://pypi.python.org/pypi/distro) [![Latest Github Release](https://readthedocs.org/projects/distro/badge/?version=stable)](http://distro.readthedocs.io/en/latest/) `distro` provides information about the OS distribution it runs on, such as a reliable machine-readable ID, or version information. It is the recommended replacement for Python's original [`platform.linux_distribution`](https://docs.python.org/3.7/library/platform.html#platform.linux_distribution) function (removed in Python 3.8). It also provides much more functionality which isn't necessarily Python bound, like a command-line interface. Distro currently supports Linux and BSD based systems but [Windows and OS X support](https://github.com/python-distro/distro/issues/177) is also planned. For Python 2.6 support, see https://github.com/python-distro/distro/tree/python2.6-support ## Installation Installation of the latest released version from PyPI: ```shell pip install distro ``` Installation of the latest development version: ```shell pip install https://github.com/python-distro/distro/archive/master.tar.gz ``` To use as a standalone script, download `distro.py` directly: ```shell curl -O https://raw.githubusercontent.com/python-distro/distro/master/src/distro/distro.py python distro.py ``` ``distro`` is safe to vendor within projects that do not wish to add dependencies. ```shell cd myproject curl -O https://raw.githubusercontent.com/python-distro/distro/master/src/distro/distro.py ``` ## Usage ```bash $ distro Name: Antergos Linux Version: 2015.10 (ISO-Rolling) Codename: ISO-Rolling $ distro -j { "codename": "ISO-Rolling", "id": "antergos", "like": "arch", "version": "16.9", "version_parts": { "build_number": "", "major": "16", "minor": "9" } } $ python >>> import distro >>> distro.name(pretty=True) 'CentOS Linux 8' >>> distro.id() 'centos' >>> distro.version(best=True) '8.4.2105' ``` ## Documentation On top of the aforementioned API, several more functions are available. For a complete description of the API, see the [latest API documentation](http://distro.readthedocs.org/en/latest/). ## Background An alternative implementation became necessary because Python 3.5 deprecated this function, and Python 3.8 removed it altogether. Its predecessor function [`platform.dist`](https://docs.python.org/3.7/library/platform.html#platform.dist) was already deprecated since Python 2.6 and removed in Python 3.8. Still, there are many cases in which access to that information is needed. See [Python issue 1322](https://bugs.python.org/issue1322) for more information. The `distro` package implements a robust and inclusive way of retrieving the information about a distribution based on new standards and old methods, namely from these data sources (from high to low precedence): * The os-release file `/etc/os-release` if present, with a fall-back on `/usr/lib/os-release` if needed. * The output of the `lsb_release` command, if available. * The distro release file (`/etc/*(-|_)(release|version)`), if present. * The `uname` command for BSD based distrubtions. ## Python and Distribution Support `distro` is supported and tested on Python 3.6+ and PyPy and on any distribution that provides one or more of the data sources covered. This package is tested with test data that mimics the exact behavior of the data sources of [a number of Linux distributions](https://github.com/python-distro/distro/tree/master/tests/resources/distros). ## Testing ```shell git clone git@github.com:python-distro/distro.git cd distro pip install tox tox ``` ## Contributions Pull requests are always welcome to deal with specific distributions or just for general merriment. See [CONTRIBUTIONS](https://github.com/python-distro/distro/blob/master/CONTRIBUTING.md) for contribution info. Reference implementations for supporting additional distributions and file formats can be found here: * https://github.com/saltstack/salt/blob/develop/salt/grains/core.py#L1172 * https://github.com/chef/ohai/blob/master/lib/ohai/plugins/linux/platform.rb * https://github.com/ansible/ansible/blob/devel/lib/ansible/module_utils/facts/system/distribution.py * https://github.com/puppetlabs/facter/blob/master/lib/src/facts/linux/os_linux.cc ## Package manager distributions * https://src.fedoraproject.org/rpms/python-distro * https://www.archlinux.org/packages/community/any/python-distro/ * https://launchpad.net/ubuntu/+source/python-distro * https://packages.debian.org/stable/python3-distro * https://packages.gentoo.org/packages/dev-python/distro * https://pkgs.org/download/python3-distro * https://slackbuilds.org/repository/14.2/python/python-distro/ distro-1.9.0/codecov.yml000066400000000000000000000002501454137533700152030ustar00rootroot00000000000000comment: false coverage: status: patch: default: target: '97' project: default: target: '97'distro-1.9.0/dev-requirements.txt000066400000000000000000000003431454137533700171010ustar00rootroot00000000000000pytest pytest-cov sphinx>=1.1 pre-commit==2.13.0; python_version > '3.5' black; python_version > '3.5' and platform_python_implementation != 'PyPy' mypy; python_version > '3.5' and platform_python_implementation != 'PyPy' builddistro-1.9.0/docs/000077500000000000000000000000001454137533700137715ustar00rootroot00000000000000distro-1.9.0/docs/conf.py000066400000000000000000000044441454137533700152760ustar00rootroot00000000000000# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- import datetime import os import sys # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath("..")) import distro # noqa: E402 # -- Project information ----------------------------------------------------- project = "distro" copyright = f"{datetime.date.today().year}, Nir Cohen, Andreas Maier" author = "Nir Cohen, Andreas Maier" # The short X.Y version. # Note: We use the full version in both cases. version = distro.__version__ # type: ignore # The full version, including alpha/beta/rc tags release = version # -- General configuration --------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ "sphinx.ext.autodoc", "sphinx.ext.intersphinx", "sphinx.ext.coverage", "sphinx.ext.viewcode", ] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See # https://www.sphinx-doc.org/en/master/usage/theming.html or a list of builtin # themes. html_theme = "classic" # -- Options for intersphinx extension ------------------------------------ # For documentation, see # https://www.sphinx-doc.org/en/master/usage/extensions/intersphinx.html # Defines the prefixes for intersphinx links and the targets they resolve to. # Use Python 3.7 as that is the last version to include # platform.linux_distribution() and platform.dist(). Example RST source for # 'py' prefix: # :py:func:`platform.dist` intersphinx_mapping = {"py": ("https://docs.python.org/3.7", None)} distro-1.9.0/docs/index.rst000066400000000000000000000430421454137533700156350ustar00rootroot00000000000000.. _distro official repo: https://github.com/python-distro/distro .. _distro issue tracker: https://github.com/python-distro/distro/issues .. _open issues on missing test data: https://github.com/python-distro/distro/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22> **distro** package (Linux Distribution) version |version| ********************************************************* Official distro repository: `distro official repo`_ Overview and motivation ======================= .. automodule:: distro If you want to jump into the API description right away, read about the `consolidated accessor functions`_. Compatibility ============= The ``distro`` package is supported on Python 3.6+ and PyPy, and on any Linux or BSD distribution that provides one or more of the `data sources`_ used by this package. This package is tested on Python 3.6+ and PyPy, with test data that mimics the exact behavior of the data sources of `a number of Linux distributions `_. If you want to add test data for more distributions, please create an issue in the `distro issue tracker`_ and provide the following information in the issue: * The os-release file `/etc/os-release` if present, with a fall-back on `/usr/lib/os-release` if needed. * The file names and content of the `/etc/*release` and `/etc/*version` files, if any. * The output of the command: `lsb_release -a`, if available. * The file names and content of any other files you are aware of that provide useful information about the distro. There are already some `open issues on missing test data`_. Data sources ============ The ``distro`` package implements a robust and inclusive way of retrieving the information about a Linux distribution based on new standards and old methods, namely from these data sources: * The `os-release file`_, if present. * The `lsb_release command output`_, if the lsb_release command is available. * The `distro release file`_, if present. * The ``uname`` command output, if present. Access to the information ========================= This package provides three ways to access the information about a Linux distribution: * `Consolidated accessor functions`_ These are module-global functions that take into account all data sources in a priority order, and that return information about the current Linux distribution. These functions should be the normal way to access the information. The precedence of data sources is applied for each information item separately. Therefore, it is possible that not all information items returned by these functions come from the same data source. For example, on a distribution that has an lsb_release command that returns the "Distributor ID" field but not the "Codename" field, and that has a distro release file that specifies a codename inside, the distro ID will come from the lsb_release command (because it has higher precedence), and the codename will come from the distro release file (because it is not provided by the lsb_release command). Examples: :func:`distro.id` for retrieving the distro ID, or :func:`distro.info` to get the machine-readable part of the information in a more aggregated way, or :func:`distro.linux_distribution` with an interface that is compatible to the original :py:func:`platform.linux_distribution` function, supporting a subset of its parameters. * `Single source accessor functions`_ These are module-global functions that take into account a single data source, and that return information about the current Linux distribution. They are useful for distributions that provide multiple inconsistent data sources, or for retrieving information items that are not provided by the consolidated accessor functions. Examples: :func:`distro.os_release_attr` for retrieving a single information item from the os-release data source, or :func:`distro.lsb_release_info` for retrieving all information items from the lsb_release command output data source. * `LinuxDistribution class`_ The :class:`distro.LinuxDistribution` class provides the main code of this package. This package contains a private module-global :class:`distro.LinuxDistribution` instance with default initialization arguments, that is used by the consolidated and single source accessor functions. A user-defined instance of the :class:`distro.LinuxDistribution` class allows specifying the path names of the os-release file and distro release file and whether the lsb_release command should be used or not. That is useful for example when the distribution information from a chrooted environment is to be retrieved, or when a distro has multiple distro release files and the default algorithm uses the wrong one. Consolidated accessor functions =============================== This section describes the consolidated accessor functions. See `access to the information`_ for a discussion of the different kinds of accessor functions. .. autofunction:: distro.linux_distribution .. autofunction:: distro.id .. autofunction:: distro.name .. autofunction:: distro.version .. autofunction:: distro.version_parts .. autofunction:: distro.major_version .. autofunction:: distro.minor_version .. autofunction:: distro.build_number .. autofunction:: distro.like .. autofunction:: distro.codename .. autofunction:: distro.info Single source accessor functions ================================ This section describes the single source accessor functions. See `access to the information`_ for a discussion of the different kinds of accessor functions. .. autofunction:: distro.os_release_info .. autofunction:: distro.lsb_release_info .. autofunction:: distro.distro_release_info .. autofunction:: distro.uname_info .. autofunction:: distro.os_release_attr .. autofunction:: distro.lsb_release_attr .. autofunction:: distro.distro_release_attr .. autofunction:: distro.uname_attr LinuxDistribution class ======================= This section describes the access via the :class:`distro.LinuxDistribution` class. See `access to the information`_ for a discussion of the different kinds of accessor functions. .. autoclass:: distro.LinuxDistribution :members: :undoc-members: Normalization tables ==================== These translation tables are used to normalize the parsed distro ID values into reliable IDs. See :func:`distro.id` for details. They are documented in order to show for which distros a normalization is currently defined. As a quick fix, these tables can also be extended by the user by appending new entries, should the need arise. If you have a need to get these tables extended, please make an according request in the `distro issue tracker`_. .. autodata:: distro.NORMALIZED_OS_ID .. autodata:: distro.NORMALIZED_LSB_ID .. autodata:: distro.NORMALIZED_DISTRO_ID Os-release file =============== The os-release file is looked up using the path name ``/etc/os-release``. Its optional additional location ``/usr/lib/os-release`` would be looked up for if the former couldn't be read. The os-release file is expected to be encoded in UTF-8. It is parsed using the standard Python :py:mod:`shlex` package, which treats it like a shell script. The attribute names found in the file are translated to lower case and then become the keys of the information items from the os-release file data source. These keys can be used to retrieve single items with the :func:`distro.os_release_attr` function, and they are also used as keys in the dictionary returned by :func:`distro.os_release_info`. The attribute values found in the file are processed using shell rules (e.g. for whitespace, escaping, and quoting) before they become the values of the information items from the os-release file data source. If the attribute "VERSION" is found in the file, the distro codename is extracted from its value if it can be found there. If a codename is found, it becomes an additional information item with key "codename". See the `os-release man page `_ for a list of possible attributes in the file. **Examples:** 1. The following os-release file content: .. sourcecode:: shell NAME='Ubuntu' VERSION="14.04.3 LTS, Trusty Tahr" ID=ubuntu ID_LIKE=debian PRETTY_NAME="Ubuntu 14.04.3 LTS" VERSION_ID="14.04" HOME_URL="http://www.ubuntu.com/" SUPPORT_URL="http://help.ubuntu.com/" BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/" results in these information items: =============================== ========================================== Key Value =============================== ========================================== name "Ubuntu" version "14.04.3 LTS, Trusty Tahr" id "ubuntu" id_like "debian" pretty_name "Ubuntu 14.04.3 LTS" version_id "14.04" home_url "http://www.ubuntu.com/" support_url "http://help.ubuntu.com/" bug_report_url "http://bugs.launchpad.net/ubuntu/" codename "Trusty Tahr" =============================== ========================================== 2. The following os-release file content: .. sourcecode:: shell NAME="Red Hat Enterprise Linux Server" VERSION="7.0 (Maipo)" ID="rhel" ID_LIKE="fedora" VERSION_ID="7.0" PRETTY_NAME="Red Hat Enterprise Linux Server 7.0 (Maipo)" ANSI_COLOR="0;31" CPE_NAME="cpe:/o:redhat:enterprise_linux:7.0:GA:server" HOME_URL="https://www.redhat.com/" BUG_REPORT_URL="https://bugzilla.redhat.com/" REDHAT_BUGZILLA_PRODUCT="Red Hat Enterprise Linux 7" REDHAT_BUGZILLA_PRODUCT_VERSION=7.0 REDHAT_SUPPORT_PRODUCT="Red Hat Enterprise Linux" REDHAT_SUPPORT_PRODUCT_VERSION=7.0 results in these information items: =============================== ========================================== Key Value =============================== ========================================== name "Red Hat Enterprise Linux Server" version "7.0 (Maipo)" id "rhel" id_like "fedora" version_id "7.0" pretty_name "Red Hat Enterprise Linux Server 7.0 (Maipo)" ansi_color "0;31" cpe_name "cpe:/o:redhat:enterprise_linux:7.0:GA:server" home_url "https://www.redhat.com/" bug_report_url "https://bugzilla.redhat.com/" redhat_bugzilla_product "Red Hat Enterprise Linux 7" redhat_bugzilla_product_version "7.0" redhat_support_product "Red Hat Enterprise Linux" redhat_support_product_version "7.0" codename "Maipo" =============================== ========================================== Lsb_release command output ========================== The lsb_release command is expected to be in the PATH, and is invoked as follows: .. sourcecode:: shell lsb_release -a The command output is expected to be encoded in UTF-8. Only lines in the command output with the following format will be used: ``: `` Where: * ```` is the name of the attribute, and * ```` is the attribute value. The attribute names are stripped from surrounding blanks, any remaining blanks are translated to underscores, they are translated to lower case, and then become the keys of the information items from the lsb_release command output data source. The attribute values are stripped from surrounding blanks, and then become the values of the information items from the lsb_release command output data source. See the `lsb_release man page `_ for a description of standard attributes returned by the lsb_release command. **Examples:** 1. The following lsb_release command output: .. sourcecode:: text No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 14.04.3 LTS Release: 14.04 Codename: trusty results in these information items: =============================== ========================================== Key Value =============================== ========================================== distributor_id "Ubuntu" description "Ubuntu 14.04.3 LTS" release "14.04" codename "trusty" =============================== ========================================== 2. The following lsb_release command output: .. sourcecode:: text LSB Version: n/a Distributor ID: SUSE LINUX Description: SUSE Linux Enterprise Server 12 SP1 Release: 12.1 Codename: n/a results in these information items: =============================== ========================================== Key Value =============================== ========================================== lsb_version "n/a" distributor_id "SUSE LINUX" description "SUSE Linux Enterprise Server 12 SP1" release "12.1" codename "n/a" =============================== ========================================== Distro release file =================== Unless specified with a particular path name when using the :class:`distro.LinuxDistribution` class, the distro release file is found by using the first match in the alphabetically sorted list of the files matching the following path name patterns: * ``/etc/*-release`` * ``/etc/*_release`` * ``/etc/*-version`` * ``/etc/*_version`` where the following special path names are excluded: * ``/etc/debian_version`` * ``/etc/system-release`` * ``/etc/os-release`` and where the first line within the file has the expected format. The algorithm to sort the files alphabetically is far from perfect, but the distro release file has the least priority as a data source, and it is expected that distributions provide one of the other data sources. The distro release file is expected to be encoded in UTF-8. Only its first line is used, and it is expected to have the following format: `` [[[release] ] ()]`` Where: * square brackets indicate optionality, * ```` is the distro name, * ```` is the distro version, and * ```` is the distro codename. The following information items can be found in a distro release file (shown with their keys and data types): * ``id`` (string): Distro ID, taken from the first part of the file name before the hyphen (``-``) or underscore (``_``). Note that the distro ID is not normalized or translated to lower case at this point; this happens only for the result of the :func:`distro.id` function. * ``name`` (string): Distro name, as found in the first line of the file. * ``version_id`` (string): Distro version, as found in the first line of the file. If not found, this information item will not exist. * ``codename`` (string): Distro codename, as found in the first line of the file. If not found, this information item will not exist. Note that the string in the codename field is not always really a codename. For example, openSUSE returns "x86_64". **Examples:** 1. The following distro release file ``/etc/centos-release``: .. sourcecode:: text CentOS Linux release 7.1.1503 (Core) results in these information items: =============================== ========================================== Key Value =============================== ========================================== id "centos" name "CentOS Linux" version_id "7.1.1503" codename "Core" =============================== ========================================== 2. The following distro release file ``/etc/oracle-release``: .. sourcecode:: text Oracle Linux Server release 7.1 results in these information items: =============================== ========================================== Key Value =============================== ========================================== id "oracle" name "Oracle Linux Server" version_id "7.1" =============================== ========================================== 3. The following distro release file ``/etc/SuSE-release``: .. sourcecode:: text openSUSE 42.1 (x86_64) results in these information items: =============================== ========================================== Key Value =============================== ========================================== id "SuSE" name "openSUSE" version_id "42.1" codename "x86_64" =============================== ========================================== distro-1.9.0/pyproject.toml000066400000000000000000000001211454137533700157470ustar00rootroot00000000000000[build-system] requires = ["setuptools"] build-backend = "setuptools.build_meta" distro-1.9.0/query_local_distro.py000077500000000000000000000027031454137533700173230ustar00rootroot00000000000000#!/usr/bin/env python # Copyright 2015,2016 Nir Cohen # # 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 # # http://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 pprint import pformat import distro def pprint(obj: object) -> None: for line in pformat(obj).split("\n"): print(4 * " " + line) print("os_release_info:") pprint(distro.os_release_info()) print("lsb_release_info:") pprint(distro.lsb_release_info()) print("distro_release_info:") pprint(distro.distro_release_info()) print(f"id: {distro.id()}") print(f"name: {distro.name()}") print(f"name_pretty: {distro.name(True)}") print(f"version: {distro.version()}") print(f"version_pretty: {distro.version(True)}") print(f"like: {distro.like()}") print(f"codename: {distro.codename()}") print(f"linux_distribution_full: {distro.linux_distribution()}") print(f"linux_distribution: {distro.linux_distribution(False)}") print(f"major_version: {distro.major_version()}") print(f"minor_version: {distro.minor_version()}") print(f"build_number: {distro.build_number()}") distro-1.9.0/setup.cfg000066400000000000000000000027321454137533700146660ustar00rootroot00000000000000[metadata] name = distro version = attr: distro.__version__ url = https://github.com/python-distro/distro author = Nir Cohen author_email = nir36g@gmail.com license = Apache License, Version 2.0 platforms = All description= Distro - an OS platform information API long_description = file: README.md long_description_content_type = text/markdown classifiers = Development Status :: 5 - Production/Stable Intended Audience :: Developers Intended Audience :: System Administrators License :: OSI Approved :: Apache Software License Operating System :: POSIX :: Linux Operating System :: POSIX :: BSD Operating System :: POSIX :: BSD :: FreeBSD Operating System :: POSIX :: BSD :: NetBSD Operating System :: POSIX :: BSD :: OpenBSD Programming Language :: Python :: 3 Programming Language :: Python :: 3 :: Only Programming Language :: Python :: 3.6 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 Programming Language :: Python :: 3.12 Topic :: Software Development :: Libraries :: Python Modules Topic :: System :: Operating System [options] package_dir = = src packages = distro python_requires = >=3.6 [options.package_data] * = py.typed [options.entry_points] console_scripts = distro = distro.distro:main [flake8] max-line-length = 88 [isort] profile = black distro-1.9.0/src/000077500000000000000000000000001454137533700136305ustar00rootroot00000000000000distro-1.9.0/src/distro/000077500000000000000000000000001454137533700151345ustar00rootroot00000000000000distro-1.9.0/src/distro/__init__.py000066400000000000000000000017251454137533700172520ustar00rootroot00000000000000from .distro import ( NORMALIZED_DISTRO_ID, NORMALIZED_LSB_ID, NORMALIZED_OS_ID, LinuxDistribution, __version__, build_number, codename, distro_release_attr, distro_release_info, id, info, like, linux_distribution, lsb_release_attr, lsb_release_info, major_version, minor_version, name, os_release_attr, os_release_info, uname_attr, uname_info, version, version_parts, ) __all__ = [ "NORMALIZED_DISTRO_ID", "NORMALIZED_LSB_ID", "NORMALIZED_OS_ID", "LinuxDistribution", "build_number", "codename", "distro_release_attr", "distro_release_info", "id", "info", "like", "linux_distribution", "lsb_release_attr", "lsb_release_info", "major_version", "minor_version", "name", "os_release_attr", "os_release_info", "uname_attr", "uname_info", "version", "version_parts", ] __version__ = __version__ distro-1.9.0/src/distro/__main__.py000066400000000000000000000001001454137533700172150ustar00rootroot00000000000000from .distro import main if __name__ == "__main__": main() distro-1.9.0/src/distro/distro.py000077500000000000000000001404261454137533700170240ustar00rootroot00000000000000#!/usr/bin/env python # Copyright 2015-2021 Nir Cohen # # 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 # # http://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. """ The ``distro`` package (``distro`` stands for Linux Distribution) provides information about the Linux distribution it runs on, such as a reliable machine-readable distro ID, or version information. It is the recommended replacement for Python's original :py:func:`platform.linux_distribution` function, but it provides much more functionality. An alternative implementation became necessary because Python 3.5 deprecated this function, and Python 3.8 removed it altogether. Its predecessor function :py:func:`platform.dist` was already deprecated since Python 2.6 and removed in Python 3.8. Still, there are many cases in which access to OS distribution information is needed. See `Python issue 1322 `_ for more information. """ import argparse import json import logging import os import re import shlex import subprocess import sys import warnings from typing import ( Any, Callable, Dict, Iterable, Optional, Sequence, TextIO, Tuple, Type, ) try: from typing import TypedDict except ImportError: # Python 3.7 TypedDict = dict __version__ = "1.9.0" class VersionDict(TypedDict): major: str minor: str build_number: str class InfoDict(TypedDict): id: str version: str version_parts: VersionDict like: str codename: str _UNIXCONFDIR = os.environ.get("UNIXCONFDIR", "/etc") _UNIXUSRLIBDIR = os.environ.get("UNIXUSRLIBDIR", "/usr/lib") _OS_RELEASE_BASENAME = "os-release" #: Translation table for normalizing the "ID" attribute defined in os-release #: files, for use by the :func:`distro.id` method. #: #: * Key: Value as defined in the os-release file, translated to lower case, #: with blanks translated to underscores. #: #: * Value: Normalized value. NORMALIZED_OS_ID = { "ol": "oracle", # Oracle Linux "opensuse-leap": "opensuse", # Newer versions of OpenSuSE report as opensuse-leap } #: Translation table for normalizing the "Distributor ID" attribute returned by #: the lsb_release command, for use by the :func:`distro.id` method. #: #: * Key: Value as returned by the lsb_release command, translated to lower #: case, with blanks translated to underscores. #: #: * Value: Normalized value. NORMALIZED_LSB_ID = { "enterpriseenterpriseas": "oracle", # Oracle Enterprise Linux 4 "enterpriseenterpriseserver": "oracle", # Oracle Linux 5 "redhatenterpriseworkstation": "rhel", # RHEL 6, 7 Workstation "redhatenterpriseserver": "rhel", # RHEL 6, 7 Server "redhatenterprisecomputenode": "rhel", # RHEL 6 ComputeNode } #: Translation table for normalizing the distro ID derived from the file name #: of distro release files, for use by the :func:`distro.id` method. #: #: * Key: Value as derived from the file name of a distro release file, #: translated to lower case, with blanks translated to underscores. #: #: * Value: Normalized value. NORMALIZED_DISTRO_ID = { "redhat": "rhel", # RHEL 6.x, 7.x } # Pattern for content of distro release file (reversed) _DISTRO_RELEASE_CONTENT_REVERSED_PATTERN = re.compile( r"(?:[^)]*\)(.*)\()? *(?:STL )?([\d.+\-a-z]*\d) *(?:esaeler *)?(.+)" ) # Pattern for base file name of distro release file _DISTRO_RELEASE_BASENAME_PATTERN = re.compile(r"(\w+)[-_](release|version)$") # Base file names to be looked up for if _UNIXCONFDIR is not readable. _DISTRO_RELEASE_BASENAMES = [ "SuSE-release", "altlinux-release", "arch-release", "base-release", "centos-release", "fedora-release", "gentoo-release", "mageia-release", "mandrake-release", "mandriva-release", "mandrivalinux-release", "manjaro-release", "oracle-release", "redhat-release", "rocky-release", "sl-release", "slackware-version", ] # Base file names to be ignored when searching for distro release file _DISTRO_RELEASE_IGNORE_BASENAMES = ( "debian_version", "lsb-release", "oem-release", _OS_RELEASE_BASENAME, "system-release", "plesk-release", "iredmail-release", "board-release", "ec2_version", ) def linux_distribution(full_distribution_name: bool = True) -> Tuple[str, str, str]: """ .. deprecated:: 1.6.0 :func:`distro.linux_distribution()` is deprecated. It should only be used as a compatibility shim with Python's :py:func:`platform.linux_distribution()`. Please use :func:`distro.id`, :func:`distro.version` and :func:`distro.name` instead. Return information about the current OS distribution as a tuple ``(id_name, version, codename)`` with items as follows: * ``id_name``: If *full_distribution_name* is false, the result of :func:`distro.id`. Otherwise, the result of :func:`distro.name`. * ``version``: The result of :func:`distro.version`. * ``codename``: The extra item (usually in parentheses) after the os-release version number, or the result of :func:`distro.codename`. The interface of this function is compatible with the original :py:func:`platform.linux_distribution` function, supporting a subset of its parameters. The data it returns may not exactly be the same, because it uses more data sources than the original function, and that may lead to different data if the OS distribution is not consistent across multiple data sources it provides (there are indeed such distributions ...). Another reason for differences is the fact that the :func:`distro.id` method normalizes the distro ID string to a reliable machine-readable value for a number of popular OS distributions. """ warnings.warn( "distro.linux_distribution() is deprecated. It should only be used as a " "compatibility shim with Python's platform.linux_distribution(). Please use " "distro.id(), distro.version() and distro.name() instead.", DeprecationWarning, stacklevel=2, ) return _distro.linux_distribution(full_distribution_name) def id() -> str: """ Return the distro ID of the current distribution, as a machine-readable string. For a number of OS distributions, the returned distro ID value is *reliable*, in the sense that it is documented and that it does not change across releases of the distribution. This package maintains the following reliable distro ID values: ============== ========================================= Distro ID Distribution ============== ========================================= "ubuntu" Ubuntu "debian" Debian "rhel" RedHat Enterprise Linux "centos" CentOS "fedora" Fedora "sles" SUSE Linux Enterprise Server "opensuse" openSUSE "amzn" Amazon Linux "arch" Arch Linux "buildroot" Buildroot "cloudlinux" CloudLinux OS "exherbo" Exherbo Linux "gentoo" GenToo Linux "ibm_powerkvm" IBM PowerKVM "kvmibm" KVM for IBM z Systems "linuxmint" Linux Mint "mageia" Mageia "mandriva" Mandriva Linux "parallels" Parallels "pidora" Pidora "raspbian" Raspbian "oracle" Oracle Linux (and Oracle Enterprise Linux) "scientific" Scientific Linux "slackware" Slackware "xenserver" XenServer "openbsd" OpenBSD "netbsd" NetBSD "freebsd" FreeBSD "midnightbsd" MidnightBSD "rocky" Rocky Linux "aix" AIX "guix" Guix System "altlinux" ALT Linux ============== ========================================= If you have a need to get distros for reliable IDs added into this set, or if you find that the :func:`distro.id` function returns a different distro ID for one of the listed distros, please create an issue in the `distro issue tracker`_. **Lookup hierarchy and transformations:** First, the ID is obtained from the following sources, in the specified order. The first available and non-empty value is used: * the value of the "ID" attribute of the os-release file, * the value of the "Distributor ID" attribute returned by the lsb_release command, * the first part of the file name of the distro release file, The so determined ID value then passes the following transformations, before it is returned by this method: * it is translated to lower case, * blanks (which should not be there anyway) are translated to underscores, * a normalization of the ID is performed, based upon `normalization tables`_. The purpose of this normalization is to ensure that the ID is as reliable as possible, even across incompatible changes in the OS distributions. A common reason for an incompatible change is the addition of an os-release file, or the addition of the lsb_release command, with ID values that differ from what was previously determined from the distro release file name. """ return _distro.id() def name(pretty: bool = False) -> str: """ Return the name of the current OS distribution, as a human-readable string. If *pretty* is false, the name is returned without version or codename. (e.g. "CentOS Linux") If *pretty* is true, the version and codename are appended. (e.g. "CentOS Linux 7.1.1503 (Core)") **Lookup hierarchy:** The name is obtained from the following sources, in the specified order. The first available and non-empty value is used: * If *pretty* is false: - the value of the "NAME" attribute of the os-release file, - the value of the "Distributor ID" attribute returned by the lsb_release command, - the value of the "" field of the distro release file. * If *pretty* is true: - the value of the "PRETTY_NAME" attribute of the os-release file, - the value of the "Description" attribute returned by the lsb_release command, - the value of the "" field of the distro release file, appended with the value of the pretty version ("" and "" fields) of the distro release file, if available. """ return _distro.name(pretty) def version(pretty: bool = False, best: bool = False) -> str: """ Return the version of the current OS distribution, as a human-readable string. If *pretty* is false, the version is returned without codename (e.g. "7.0"). If *pretty* is true, the codename in parenthesis is appended, if the codename is non-empty (e.g. "7.0 (Maipo)"). Some distributions provide version numbers with different precisions in the different sources of distribution information. Examining the different sources in a fixed priority order does not always yield the most precise version (e.g. for Debian 8.2, or CentOS 7.1). Some other distributions may not provide this kind of information. In these cases, an empty string would be returned. This behavior can be observed with rolling releases distributions (e.g. Arch Linux). The *best* parameter can be used to control the approach for the returned version: If *best* is false, the first non-empty version number in priority order of the examined sources is returned. If *best* is true, the most precise version number out of all examined sources is returned. **Lookup hierarchy:** In all cases, the version number is obtained from the following sources. If *best* is false, this order represents the priority order: * the value of the "VERSION_ID" attribute of the os-release file, * the value of the "Release" attribute returned by the lsb_release command, * the version number parsed from the "" field of the first line of the distro release file, * the version number parsed from the "PRETTY_NAME" attribute of the os-release file, if it follows the format of the distro release files. * the version number parsed from the "Description" attribute returned by the lsb_release command, if it follows the format of the distro release files. """ return _distro.version(pretty, best) def version_parts(best: bool = False) -> Tuple[str, str, str]: """ Return the version of the current OS distribution as a tuple ``(major, minor, build_number)`` with items as follows: * ``major``: The result of :func:`distro.major_version`. * ``minor``: The result of :func:`distro.minor_version`. * ``build_number``: The result of :func:`distro.build_number`. For a description of the *best* parameter, see the :func:`distro.version` method. """ return _distro.version_parts(best) def major_version(best: bool = False) -> str: """ Return the major version of the current OS distribution, as a string, if provided. Otherwise, the empty string is returned. The major version is the first part of the dot-separated version string. For a description of the *best* parameter, see the :func:`distro.version` method. """ return _distro.major_version(best) def minor_version(best: bool = False) -> str: """ Return the minor version of the current OS distribution, as a string, if provided. Otherwise, the empty string is returned. The minor version is the second part of the dot-separated version string. For a description of the *best* parameter, see the :func:`distro.version` method. """ return _distro.minor_version(best) def build_number(best: bool = False) -> str: """ Return the build number of the current OS distribution, as a string, if provided. Otherwise, the empty string is returned. The build number is the third part of the dot-separated version string. For a description of the *best* parameter, see the :func:`distro.version` method. """ return _distro.build_number(best) def like() -> str: """ Return a space-separated list of distro IDs of distributions that are closely related to the current OS distribution in regards to packaging and programming interfaces, for example distributions the current distribution is a derivative from. **Lookup hierarchy:** This information item is only provided by the os-release file. For details, see the description of the "ID_LIKE" attribute in the `os-release man page `_. """ return _distro.like() def codename() -> str: """ Return the codename for the release of the current OS distribution, as a string. If the distribution does not have a codename, an empty string is returned. Note that the returned codename is not always really a codename. For example, openSUSE returns "x86_64". This function does not handle such cases in any special way and just returns the string it finds, if any. **Lookup hierarchy:** * the codename within the "VERSION" attribute of the os-release file, if provided, * the value of the "Codename" attribute returned by the lsb_release command, * the value of the "" field of the distro release file. """ return _distro.codename() def info(pretty: bool = False, best: bool = False) -> InfoDict: """ Return certain machine-readable information items about the current OS distribution in a dictionary, as shown in the following example: .. sourcecode:: python { 'id': 'rhel', 'version': '7.0', 'version_parts': { 'major': '7', 'minor': '0', 'build_number': '' }, 'like': 'fedora', 'codename': 'Maipo' } The dictionary structure and keys are always the same, regardless of which information items are available in the underlying data sources. The values for the various keys are as follows: * ``id``: The result of :func:`distro.id`. * ``version``: The result of :func:`distro.version`. * ``version_parts -> major``: The result of :func:`distro.major_version`. * ``version_parts -> minor``: The result of :func:`distro.minor_version`. * ``version_parts -> build_number``: The result of :func:`distro.build_number`. * ``like``: The result of :func:`distro.like`. * ``codename``: The result of :func:`distro.codename`. For a description of the *pretty* and *best* parameters, see the :func:`distro.version` method. """ return _distro.info(pretty, best) def os_release_info() -> Dict[str, str]: """ Return a dictionary containing key-value pairs for the information items from the os-release file data source of the current OS distribution. See `os-release file`_ for details about these information items. """ return _distro.os_release_info() def lsb_release_info() -> Dict[str, str]: """ Return a dictionary containing key-value pairs for the information items from the lsb_release command data source of the current OS distribution. See `lsb_release command output`_ for details about these information items. """ return _distro.lsb_release_info() def distro_release_info() -> Dict[str, str]: """ Return a dictionary containing key-value pairs for the information items from the distro release file data source of the current OS distribution. See `distro release file`_ for details about these information items. """ return _distro.distro_release_info() def uname_info() -> Dict[str, str]: """ Return a dictionary containing key-value pairs for the information items from the distro release file data source of the current OS distribution. """ return _distro.uname_info() def os_release_attr(attribute: str) -> str: """ Return a single named information item from the os-release file data source of the current OS distribution. Parameters: * ``attribute`` (string): Key of the information item. Returns: * (string): Value of the information item, if the item exists. The empty string, if the item does not exist. See `os-release file`_ for details about these information items. """ return _distro.os_release_attr(attribute) def lsb_release_attr(attribute: str) -> str: """ Return a single named information item from the lsb_release command output data source of the current OS distribution. Parameters: * ``attribute`` (string): Key of the information item. Returns: * (string): Value of the information item, if the item exists. The empty string, if the item does not exist. See `lsb_release command output`_ for details about these information items. """ return _distro.lsb_release_attr(attribute) def distro_release_attr(attribute: str) -> str: """ Return a single named information item from the distro release file data source of the current OS distribution. Parameters: * ``attribute`` (string): Key of the information item. Returns: * (string): Value of the information item, if the item exists. The empty string, if the item does not exist. See `distro release file`_ for details about these information items. """ return _distro.distro_release_attr(attribute) def uname_attr(attribute: str) -> str: """ Return a single named information item from the distro release file data source of the current OS distribution. Parameters: * ``attribute`` (string): Key of the information item. Returns: * (string): Value of the information item, if the item exists. The empty string, if the item does not exist. """ return _distro.uname_attr(attribute) try: from functools import cached_property except ImportError: # Python < 3.8 class cached_property: # type: ignore """A version of @property which caches the value. On access, it calls the underlying function and sets the value in `__dict__` so future accesses will not re-call the property. """ def __init__(self, f: Callable[[Any], Any]) -> None: self._fname = f.__name__ self._f = f def __get__(self, obj: Any, owner: Type[Any]) -> Any: assert obj is not None, f"call {self._fname} on an instance" ret = obj.__dict__[self._fname] = self._f(obj) return ret class LinuxDistribution: """ Provides information about a OS distribution. This package creates a private module-global instance of this class with default initialization arguments, that is used by the `consolidated accessor functions`_ and `single source accessor functions`_. By using default initialization arguments, that module-global instance returns data about the current OS distribution (i.e. the distro this package runs on). Normally, it is not necessary to create additional instances of this class. However, in situations where control is needed over the exact data sources that are used, instances of this class can be created with a specific distro release file, or a specific os-release file, or without invoking the lsb_release command. """ def __init__( self, include_lsb: Optional[bool] = None, os_release_file: str = "", distro_release_file: str = "", include_uname: Optional[bool] = None, root_dir: Optional[str] = None, include_oslevel: Optional[bool] = None, ) -> None: """ The initialization method of this class gathers information from the available data sources, and stores that in private instance attributes. Subsequent access to the information items uses these private instance attributes, so that the data sources are read only once. Parameters: * ``include_lsb`` (bool): Controls whether the `lsb_release command output`_ is included as a data source. If the lsb_release command is not available in the program execution path, the data source for the lsb_release command will be empty. * ``os_release_file`` (string): The path name of the `os-release file`_ that is to be used as a data source. An empty string (the default) will cause the default path name to be used (see `os-release file`_ for details). If the specified or defaulted os-release file does not exist, the data source for the os-release file will be empty. * ``distro_release_file`` (string): The path name of the `distro release file`_ that is to be used as a data source. An empty string (the default) will cause a default search algorithm to be used (see `distro release file`_ for details). If the specified distro release file does not exist, or if no default distro release file can be found, the data source for the distro release file will be empty. * ``include_uname`` (bool): Controls whether uname command output is included as a data source. If the uname command is not available in the program execution path the data source for the uname command will be empty. * ``root_dir`` (string): The absolute path to the root directory to use to find distro-related information files. Note that ``include_*`` parameters must not be enabled in combination with ``root_dir``. * ``include_oslevel`` (bool): Controls whether (AIX) oslevel command output is included as a data source. If the oslevel command is not available in the program execution path the data source will be empty. Public instance attributes: * ``os_release_file`` (string): The path name of the `os-release file`_ that is actually used as a data source. The empty string if no distro release file is used as a data source. * ``distro_release_file`` (string): The path name of the `distro release file`_ that is actually used as a data source. The empty string if no distro release file is used as a data source. * ``include_lsb`` (bool): The result of the ``include_lsb`` parameter. This controls whether the lsb information will be loaded. * ``include_uname`` (bool): The result of the ``include_uname`` parameter. This controls whether the uname information will be loaded. * ``include_oslevel`` (bool): The result of the ``include_oslevel`` parameter. This controls whether (AIX) oslevel information will be loaded. * ``root_dir`` (string): The result of the ``root_dir`` parameter. The absolute path to the root directory to use to find distro-related information files. Raises: * :py:exc:`ValueError`: Initialization parameters combination is not supported. * :py:exc:`OSError`: Some I/O issue with an os-release file or distro release file. * :py:exc:`UnicodeError`: A data source has unexpected characters or uses an unexpected encoding. """ self.root_dir = root_dir self.etc_dir = os.path.join(root_dir, "etc") if root_dir else _UNIXCONFDIR self.usr_lib_dir = ( os.path.join(root_dir, "usr/lib") if root_dir else _UNIXUSRLIBDIR ) if os_release_file: self.os_release_file = os_release_file else: etc_dir_os_release_file = os.path.join(self.etc_dir, _OS_RELEASE_BASENAME) usr_lib_os_release_file = os.path.join( self.usr_lib_dir, _OS_RELEASE_BASENAME ) # NOTE: The idea is to respect order **and** have it set # at all times for API backwards compatibility. if os.path.isfile(etc_dir_os_release_file) or not os.path.isfile( usr_lib_os_release_file ): self.os_release_file = etc_dir_os_release_file else: self.os_release_file = usr_lib_os_release_file self.distro_release_file = distro_release_file or "" # updated later is_root_dir_defined = root_dir is not None if is_root_dir_defined and (include_lsb or include_uname or include_oslevel): raise ValueError( "Including subprocess data sources from specific root_dir is disallowed" " to prevent false information" ) self.include_lsb = ( include_lsb if include_lsb is not None else not is_root_dir_defined ) self.include_uname = ( include_uname if include_uname is not None else not is_root_dir_defined ) self.include_oslevel = ( include_oslevel if include_oslevel is not None else not is_root_dir_defined ) def __repr__(self) -> str: """Return repr of all info""" return ( "LinuxDistribution(" "os_release_file={self.os_release_file!r}, " "distro_release_file={self.distro_release_file!r}, " "include_lsb={self.include_lsb!r}, " "include_uname={self.include_uname!r}, " "include_oslevel={self.include_oslevel!r}, " "root_dir={self.root_dir!r}, " "_os_release_info={self._os_release_info!r}, " "_lsb_release_info={self._lsb_release_info!r}, " "_distro_release_info={self._distro_release_info!r}, " "_uname_info={self._uname_info!r}, " "_oslevel_info={self._oslevel_info!r})".format(self=self) ) def linux_distribution( self, full_distribution_name: bool = True ) -> Tuple[str, str, str]: """ Return information about the OS distribution that is compatible with Python's :func:`platform.linux_distribution`, supporting a subset of its parameters. For details, see :func:`distro.linux_distribution`. """ return ( self.name() if full_distribution_name else self.id(), self.version(), self._os_release_info.get("release_codename") or self.codename(), ) def id(self) -> str: """Return the distro ID of the OS distribution, as a string. For details, see :func:`distro.id`. """ def normalize(distro_id: str, table: Dict[str, str]) -> str: distro_id = distro_id.lower().replace(" ", "_") return table.get(distro_id, distro_id) distro_id = self.os_release_attr("id") if distro_id: return normalize(distro_id, NORMALIZED_OS_ID) distro_id = self.lsb_release_attr("distributor_id") if distro_id: return normalize(distro_id, NORMALIZED_LSB_ID) distro_id = self.distro_release_attr("id") if distro_id: return normalize(distro_id, NORMALIZED_DISTRO_ID) distro_id = self.uname_attr("id") if distro_id: return normalize(distro_id, NORMALIZED_DISTRO_ID) return "" def name(self, pretty: bool = False) -> str: """ Return the name of the OS distribution, as a string. For details, see :func:`distro.name`. """ name = ( self.os_release_attr("name") or self.lsb_release_attr("distributor_id") or self.distro_release_attr("name") or self.uname_attr("name") ) if pretty: name = self.os_release_attr("pretty_name") or self.lsb_release_attr( "description" ) if not name: name = self.distro_release_attr("name") or self.uname_attr("name") version = self.version(pretty=True) if version: name = f"{name} {version}" return name or "" def version(self, pretty: bool = False, best: bool = False) -> str: """ Return the version of the OS distribution, as a string. For details, see :func:`distro.version`. """ versions = [ self.os_release_attr("version_id"), self.lsb_release_attr("release"), self.distro_release_attr("version_id"), self._parse_distro_release_content(self.os_release_attr("pretty_name")).get( "version_id", "" ), self._parse_distro_release_content( self.lsb_release_attr("description") ).get("version_id", ""), self.uname_attr("release"), ] if self.uname_attr("id").startswith("aix"): # On AIX platforms, prefer oslevel command output. versions.insert(0, self.oslevel_info()) elif self.id() == "debian" or "debian" in self.like().split(): # On Debian-like, add debian_version file content to candidates list. versions.append(self._debian_version) version = "" if best: # This algorithm uses the last version in priority order that has # the best precision. If the versions are not in conflict, that # does not matter; otherwise, using the last one instead of the # first one might be considered a surprise. for v in versions: if v.count(".") > version.count(".") or version == "": version = v else: for v in versions: if v != "": version = v break if pretty and version and self.codename(): version = f"{version} ({self.codename()})" return version def version_parts(self, best: bool = False) -> Tuple[str, str, str]: """ Return the version of the OS distribution, as a tuple of version numbers. For details, see :func:`distro.version_parts`. """ version_str = self.version(best=best) if version_str: version_regex = re.compile(r"(\d+)\.?(\d+)?\.?(\d+)?") matches = version_regex.match(version_str) if matches: major, minor, build_number = matches.groups() return major, minor or "", build_number or "" return "", "", "" def major_version(self, best: bool = False) -> str: """ Return the major version number of the current distribution. For details, see :func:`distro.major_version`. """ return self.version_parts(best)[0] def minor_version(self, best: bool = False) -> str: """ Return the minor version number of the current distribution. For details, see :func:`distro.minor_version`. """ return self.version_parts(best)[1] def build_number(self, best: bool = False) -> str: """ Return the build number of the current distribution. For details, see :func:`distro.build_number`. """ return self.version_parts(best)[2] def like(self) -> str: """ Return the IDs of distributions that are like the OS distribution. For details, see :func:`distro.like`. """ return self.os_release_attr("id_like") or "" def codename(self) -> str: """ Return the codename of the OS distribution. For details, see :func:`distro.codename`. """ try: # Handle os_release specially since distros might purposefully set # this to empty string to have no codename return self._os_release_info["codename"] except KeyError: return ( self.lsb_release_attr("codename") or self.distro_release_attr("codename") or "" ) def info(self, pretty: bool = False, best: bool = False) -> InfoDict: """ Return certain machine-readable information about the OS distribution. For details, see :func:`distro.info`. """ return InfoDict( id=self.id(), version=self.version(pretty, best), version_parts=VersionDict( major=self.major_version(best), minor=self.minor_version(best), build_number=self.build_number(best), ), like=self.like(), codename=self.codename(), ) def os_release_info(self) -> Dict[str, str]: """ Return a dictionary containing key-value pairs for the information items from the os-release file data source of the OS distribution. For details, see :func:`distro.os_release_info`. """ return self._os_release_info def lsb_release_info(self) -> Dict[str, str]: """ Return a dictionary containing key-value pairs for the information items from the lsb_release command data source of the OS distribution. For details, see :func:`distro.lsb_release_info`. """ return self._lsb_release_info def distro_release_info(self) -> Dict[str, str]: """ Return a dictionary containing key-value pairs for the information items from the distro release file data source of the OS distribution. For details, see :func:`distro.distro_release_info`. """ return self._distro_release_info def uname_info(self) -> Dict[str, str]: """ Return a dictionary containing key-value pairs for the information items from the uname command data source of the OS distribution. For details, see :func:`distro.uname_info`. """ return self._uname_info def oslevel_info(self) -> str: """ Return AIX' oslevel command output. """ return self._oslevel_info def os_release_attr(self, attribute: str) -> str: """ Return a single named information item from the os-release file data source of the OS distribution. For details, see :func:`distro.os_release_attr`. """ return self._os_release_info.get(attribute, "") def lsb_release_attr(self, attribute: str) -> str: """ Return a single named information item from the lsb_release command output data source of the OS distribution. For details, see :func:`distro.lsb_release_attr`. """ return self._lsb_release_info.get(attribute, "") def distro_release_attr(self, attribute: str) -> str: """ Return a single named information item from the distro release file data source of the OS distribution. For details, see :func:`distro.distro_release_attr`. """ return self._distro_release_info.get(attribute, "") def uname_attr(self, attribute: str) -> str: """ Return a single named information item from the uname command output data source of the OS distribution. For details, see :func:`distro.uname_attr`. """ return self._uname_info.get(attribute, "") @cached_property def _os_release_info(self) -> Dict[str, str]: """ Get the information items from the specified os-release file. Returns: A dictionary containing all information items. """ if os.path.isfile(self.os_release_file): with open(self.os_release_file, encoding="utf-8") as release_file: return self._parse_os_release_content(release_file) return {} @staticmethod def _parse_os_release_content(lines: TextIO) -> Dict[str, str]: """ Parse the lines of an os-release file. Parameters: * lines: Iterable through the lines in the os-release file. Each line must be a unicode string or a UTF-8 encoded byte string. Returns: A dictionary containing all information items. """ props = {} lexer = shlex.shlex(lines, posix=True) lexer.whitespace_split = True tokens = list(lexer) for token in tokens: # At this point, all shell-like parsing has been done (i.e. # comments processed, quotes and backslash escape sequences # processed, multi-line values assembled, trailing newlines # stripped, etc.), so the tokens are now either: # * variable assignments: var=value # * commands or their arguments (not allowed in os-release) # Ignore any tokens that are not variable assignments if "=" in token: k, v = token.split("=", 1) props[k.lower()] = v if "version" in props: # extract release codename (if any) from version attribute match = re.search(r"\((\D+)\)|,\s*(\D+)", props["version"]) if match: release_codename = match.group(1) or match.group(2) props["codename"] = props["release_codename"] = release_codename if "version_codename" in props: # os-release added a version_codename field. Use that in # preference to anything else Note that some distros purposefully # do not have code names. They should be setting # version_codename="" props["codename"] = props["version_codename"] elif "ubuntu_codename" in props: # Same as above but a non-standard field name used on older Ubuntus props["codename"] = props["ubuntu_codename"] return props @cached_property def _lsb_release_info(self) -> Dict[str, str]: """ Get the information items from the lsb_release command output. Returns: A dictionary containing all information items. """ if not self.include_lsb: return {} try: cmd = ("lsb_release", "-a") stdout = subprocess.check_output(cmd, stderr=subprocess.DEVNULL) # Command not found or lsb_release returned error except (OSError, subprocess.CalledProcessError): return {} content = self._to_str(stdout).splitlines() return self._parse_lsb_release_content(content) @staticmethod def _parse_lsb_release_content(lines: Iterable[str]) -> Dict[str, str]: """ Parse the output of the lsb_release command. Parameters: * lines: Iterable through the lines of the lsb_release output. Each line must be a unicode string or a UTF-8 encoded byte string. Returns: A dictionary containing all information items. """ props = {} for line in lines: kv = line.strip("\n").split(":", 1) if len(kv) != 2: # Ignore lines without colon. continue k, v = kv props.update({k.replace(" ", "_").lower(): v.strip()}) return props @cached_property def _uname_info(self) -> Dict[str, str]: if not self.include_uname: return {} try: cmd = ("uname", "-rs") stdout = subprocess.check_output(cmd, stderr=subprocess.DEVNULL) except OSError: return {} content = self._to_str(stdout).splitlines() return self._parse_uname_content(content) @cached_property def _oslevel_info(self) -> str: if not self.include_oslevel: return "" try: stdout = subprocess.check_output("oslevel", stderr=subprocess.DEVNULL) except (OSError, subprocess.CalledProcessError): return "" return self._to_str(stdout).strip() @cached_property def _debian_version(self) -> str: try: with open( os.path.join(self.etc_dir, "debian_version"), encoding="ascii" ) as fp: return fp.readline().rstrip() except FileNotFoundError: return "" @staticmethod def _parse_uname_content(lines: Sequence[str]) -> Dict[str, str]: if not lines: return {} props = {} match = re.search(r"^([^\s]+)\s+([\d\.]+)", lines[0].strip()) if match: name, version = match.groups() # This is to prevent the Linux kernel version from # appearing as the 'best' version on otherwise # identifiable distributions. if name == "Linux": return {} props["id"] = name.lower() props["name"] = name props["release"] = version return props @staticmethod def _to_str(bytestring: bytes) -> str: encoding = sys.getfilesystemencoding() return bytestring.decode(encoding) @cached_property def _distro_release_info(self) -> Dict[str, str]: """ Get the information items from the specified distro release file. Returns: A dictionary containing all information items. """ if self.distro_release_file: # If it was specified, we use it and parse what we can, even if # its file name or content does not match the expected pattern. distro_info = self._parse_distro_release_file(self.distro_release_file) basename = os.path.basename(self.distro_release_file) # The file name pattern for user-specified distro release files # is somewhat more tolerant (compared to when searching for the # file), because we want to use what was specified as best as # possible. match = _DISTRO_RELEASE_BASENAME_PATTERN.match(basename) else: try: basenames = [ basename for basename in os.listdir(self.etc_dir) if basename not in _DISTRO_RELEASE_IGNORE_BASENAMES and os.path.isfile(os.path.join(self.etc_dir, basename)) ] # We sort for repeatability in cases where there are multiple # distro specific files; e.g. CentOS, Oracle, Enterprise all # containing `redhat-release` on top of their own. basenames.sort() except OSError: # This may occur when /etc is not readable but we can't be # sure about the *-release files. Check common entries of # /etc for information. If they turn out to not be there the # error is handled in `_parse_distro_release_file()`. basenames = _DISTRO_RELEASE_BASENAMES for basename in basenames: match = _DISTRO_RELEASE_BASENAME_PATTERN.match(basename) if match is None: continue filepath = os.path.join(self.etc_dir, basename) distro_info = self._parse_distro_release_file(filepath) # The name is always present if the pattern matches. if "name" not in distro_info: continue self.distro_release_file = filepath break else: # the loop didn't "break": no candidate. return {} if match is not None: distro_info["id"] = match.group(1) # CloudLinux < 7: manually enrich info with proper id. if "cloudlinux" in distro_info.get("name", "").lower(): distro_info["id"] = "cloudlinux" return distro_info def _parse_distro_release_file(self, filepath: str) -> Dict[str, str]: """ Parse a distro release file. Parameters: * filepath: Path name of the distro release file. Returns: A dictionary containing all information items. """ try: with open(filepath, encoding="utf-8") as fp: # Only parse the first line. For instance, on SLES there # are multiple lines. We don't want them... return self._parse_distro_release_content(fp.readline()) except OSError: # Ignore not being able to read a specific, seemingly version # related file. # See https://github.com/python-distro/distro/issues/162 return {} @staticmethod def _parse_distro_release_content(line: str) -> Dict[str, str]: """ Parse a line from a distro release file. Parameters: * line: Line from the distro release file. Must be a unicode string or a UTF-8 encoded byte string. Returns: A dictionary containing all information items. """ matches = _DISTRO_RELEASE_CONTENT_REVERSED_PATTERN.match(line.strip()[::-1]) distro_info = {} if matches: # regexp ensures non-None distro_info["name"] = matches.group(3)[::-1] if matches.group(2): distro_info["version_id"] = matches.group(2)[::-1] if matches.group(1): distro_info["codename"] = matches.group(1)[::-1] elif line: distro_info["name"] = line.strip() return distro_info _distro = LinuxDistribution() def main() -> None: logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) logger.addHandler(logging.StreamHandler(sys.stdout)) parser = argparse.ArgumentParser(description="OS distro info tool") parser.add_argument( "--json", "-j", help="Output in machine readable format", action="store_true" ) parser.add_argument( "--root-dir", "-r", type=str, dest="root_dir", help="Path to the root filesystem directory (defaults to /)", ) args = parser.parse_args() if args.root_dir: dist = LinuxDistribution( include_lsb=False, include_uname=False, include_oslevel=False, root_dir=args.root_dir, ) else: dist = _distro if args.json: logger.info(json.dumps(dist.info(), indent=4, sort_keys=True)) else: logger.info("Name: %s", dist.name(pretty=True)) distribution_version = dist.version(pretty=True) logger.info("Version: %s", distribution_version) distribution_codename = dist.codename() logger.info("Codename: %s", distribution_codename) if __name__ == "__main__": main() distro-1.9.0/src/distro/py.typed000066400000000000000000000000001454137533700166210ustar00rootroot00000000000000distro-1.9.0/tests/000077500000000000000000000000001454137533700142035ustar00rootroot00000000000000distro-1.9.0/tests/__init__.py000066400000000000000000000000001454137533700163020ustar00rootroot00000000000000distro-1.9.0/tests/resources/000077500000000000000000000000001454137533700162155ustar00rootroot00000000000000distro-1.9.0/tests/resources/cli/000077500000000000000000000000001454137533700167645ustar00rootroot00000000000000distro-1.9.0/tests/resources/cli/fedora30/000077500000000000000000000000001454137533700203675ustar00rootroot00000000000000distro-1.9.0/tests/resources/cli/fedora30/etc/000077500000000000000000000000001454137533700211425ustar00rootroot00000000000000distro-1.9.0/tests/resources/cli/fedora30/etc/fedora-release000066400000000000000000000000331454137533700237370ustar00rootroot00000000000000Fedora release 30 (Thirty) distro-1.9.0/tests/resources/cli/fedora30/etc/os-release000066400000000000000000000012521454137533700231240ustar00rootroot00000000000000NAME=Fedora VERSION="30 (Thirty)" ID=fedora VERSION_ID=30 VERSION_CODENAME="" PLATFORM_ID="platform:f30" PRETTY_NAME="Fedora 30 (Thirty)" ANSI_COLOR="0;34" LOGO=fedora-logo-icon CPE_NAME="cpe:/o:fedoraproject:fedora:30" HOME_URL="https://fedoraproject.org/" DOCUMENTATION_URL="https://docs.fedoraproject.org/en-US/fedora/30/system-administrators-guide/" SUPPORT_URL="https://fedoraproject.org/wiki/Communicating_and_getting_help" BUG_REPORT_URL="https://bugzilla.redhat.com/" REDHAT_BUGZILLA_PRODUCT="Fedora" REDHAT_BUGZILLA_PRODUCT_VERSION=30 REDHAT_SUPPORT_PRODUCT="Fedora" REDHAT_SUPPORT_PRODUCT_VERSION=30 PRIVACY_POLICY_URL="https://fedoraproject.org/wiki/Legal:PrivacyPolicy" distro-1.9.0/tests/resources/cli/fedora30/etc/redhat-release000066400000000000000000000000331454137533700237460ustar00rootroot00000000000000Fedora release 30 (Thirty) distro-1.9.0/tests/resources/cli/fedora30/etc/system-release000066400000000000000000000000331454137533700240230ustar00rootroot00000000000000Fedora release 30 (Thirty) distro-1.9.0/tests/resources/distros/000077500000000000000000000000001454137533700177045ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/__shared__/000077500000000000000000000000001454137533700217465ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/__shared__/bin/000077500000000000000000000000001454137533700225165ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/__shared__/bin/lsb_release000077500000000000000000000021211454137533700247200ustar00rootroot00000000000000#!/bin/bash # # lsb_release command for testing the ld module. # Only the -a option is supported. # # This version of the lsb_release command reads an lsb-release file. # # The lsb-release file has the usual format, e.g.: # DISTRIB_ID=Ubuntu # DISTRIB_RELEASE=14.04 # DISTRIB_CODENAME=trusty # DISTRIB_DESCRIPTION="Ubuntu 14.04.3 LTS" # Where each line is optional. If a line is missing, the default value # will be the empty string. # if [[ "$@" != "-a" ]]; then echo "Usage: lsb_release -a" exit 2 fi # Because the PATH is set to just this directory, we cannot use 'dirname' # or other external programs, but need to use built-in abilities of bash. LSB_FILE="${0%/*}/../etc/lsb-release" if [[ ! -f $LSB_FILE ]]; then echo "Error: LSB release file does not exist: $LSB_FILE" exit 1 fi source $LSB_FILE if [[ -n $LSB_VERSION ]]; then echo "LSB Version: $LSB_VERSION" else echo "No LSB modules are available." fi echo "Distributor ID: ${DISTRIB_ID:-}" echo "Description: ${DISTRIB_DESCRIPTION:-}" echo "Release: ${DISTRIB_RELEASE:-}" echo "Codename: ${DISTRIB_CODENAME:-}" exit 0 distro-1.9.0/tests/resources/distros/aix72/000077500000000000000000000000001454137533700206365ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/aix72/bin/000077500000000000000000000000001454137533700214065ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/aix72/bin/oslevel000077500000000000000000000000321454137533700230000ustar00rootroot00000000000000#!/bin/sh echo "7.2.0.0" distro-1.9.0/tests/resources/distros/aix72/bin/uname000077500000000000000000000000301454137533700224320ustar00rootroot00000000000000#!/bin/sh echo "AIX 2" distro-1.9.0/tests/resources/distros/altlinux10/000077500000000000000000000000001454137533700217055ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/altlinux10/etc/000077500000000000000000000000001454137533700224605ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/altlinux10/etc/altlinux-release000066400000000000000000000000361454137533700256600ustar00rootroot00000000000000ALT Server 10.1 (Mendelevium) distro-1.9.0/tests/resources/distros/altlinux10/etc/fedora-release000077700000000000000000000000001454137533700304552altlinux-releaseustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/altlinux10/etc/os-release000066400000000000000000000004031454137533700244370ustar00rootroot00000000000000NAME="ALT Server" VERSION="10.1" ID=altlinux VERSION_ID=10.1 PRETTY_NAME="ALT Server 10.1 (Mendelevium)" ANSI_COLOR="1;33" CPE_NAME="cpe:/o:alt:server:10.1" BUILD_ID="ALT Server 10.1" HOME_URL="https://basealt.ru/" BUG_REPORT_URL="https://bugs.altlinux.org/" distro-1.9.0/tests/resources/distros/altlinux10/etc/redhat-release000077700000000000000000000000001454137533700304642altlinux-releaseustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/altlinux10/etc/system-release000077700000000000000000000000001454137533700305412altlinux-releaseustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/amazon2014/000077500000000000000000000000001454137533700215005ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/amazon2014/etc/000077500000000000000000000000001454137533700222535ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/amazon2014/etc/system-release000066400000000000000000000000401454137533700251320ustar00rootroot00000000000000Amazon Linux AMI release 2014.03distro-1.9.0/tests/resources/distros/amazon2016/000077500000000000000000000000001454137533700215025ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/amazon2016/etc/000077500000000000000000000000001454137533700222555ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/amazon2016/etc/os-release000066400000000000000000000003651454137533700242430ustar00rootroot00000000000000NAME="Amazon Linux AMI" VERSION="2016.03" ID="amzn" ID_LIKE="rhel fedora" VERSION_ID="2016.03" PRETTY_NAME="Amazon Linux AMI 2016.03" ANSI_COLOR="0;33" CPE_NAME="cpe:/o:amazon:linux:2016.03:ga" HOME_URL="http://aws.amazon.com/amazon-linux-ami/" distro-1.9.0/tests/resources/distros/amazon2016/etc/system-release000066400000000000000000000000411454137533700251350ustar00rootroot00000000000000Amazon Linux AMI release 2016.03 distro-1.9.0/tests/resources/distros/arch/000077500000000000000000000000001454137533700206215ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/arch/etc/000077500000000000000000000000001454137533700213745ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/arch/etc/arch-release000066400000000000000000000000001454137533700236400ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/arch/etc/os-release000077700000000000000000000000001454137533700271252../usr/lib/os-releaseustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/arch/usr/000077500000000000000000000000001454137533700214325ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/arch/usr/lib/000077500000000000000000000000001454137533700222005ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/arch/usr/lib/os-release000066400000000000000000000005431454137533700241640ustar00rootroot00000000000000NAME="Arch Linux" PRETTY_NAME="Arch Linux" ID=arch BUILD_ID=rolling ANSI_COLOR="38;2;23;147;209" HOME_URL="https://archlinux.org/" DOCUMENTATION_URL="https://wiki.archlinux.org/" SUPPORT_URL="https://bbs.archlinux.org/" BUG_REPORT_URL="https://bugs.archlinux.org/" PRIVACY_POLICY_URL="https://terms.archlinux.org/docs/privacy-policy/" LOGO=archlinux-logo distro-1.9.0/tests/resources/distros/bttcb1/000077500000000000000000000000001454137533700210635ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/bttcb1/etc/000077500000000000000000000000001454137533700216365ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/bttcb1/etc/board-release000066400000000000000000000002541454137533700242670ustar00rootroot00000000000000# PLEASE DO NOT EDIT THIS FILE BOARD=h616 BOARD_NAME="BTT-CB1" DISTRIBUTION_CODENAME=bullseye VERSION=2.3.1 LINUXFAMILY=sun50iw9 ARCH=arm64 INITRD_ARCH=arm64 BRANCH=currentdistro-1.9.0/tests/resources/distros/bttcb1/etc/os-release000066400000000000000000000004021454137533700236140ustar00rootroot00000000000000PRETTY_NAME="BTT-CB1 2.3.1 Bullseye" NAME="Debian GNU/Linux" VERSION_ID="11" VERSION="11 (bullseye)" VERSION_CODENAME=bullseye ID=debian HOME_URL="https://www.debian.org/" SUPPORT_URL="https://www.debian.org/support" BUG_REPORT_URL="https://bugs.debian.org/"distro-1.9.0/tests/resources/distros/bttcb1/usr/000077500000000000000000000000001454137533700216745ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/bttcb1/usr/lib/000077500000000000000000000000001454137533700224425ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/bttcb1/usr/lib/os-release000066400000000000000000000004121454137533700244210ustar00rootroot00000000000000PRETTY_NAME="Debian GNU/Linux 11 (bullseye)" NAME="Debian GNU/Linux" VERSION_ID="11" VERSION="11 (bullseye)" VERSION_CODENAME=bullseye ID=debian HOME_URL="https://www.debian.org/" SUPPORT_URL="https://www.debian.org/support" BUG_REPORT_URL="https://bugs.debian.org/"distro-1.9.0/tests/resources/distros/buildroot/000077500000000000000000000000001454137533700217075ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/buildroot/etc/000077500000000000000000000000001454137533700224625ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/buildroot/etc/os-release000066400000000000000000000001371454137533700244450ustar00rootroot00000000000000NAME=Buildroot VERSION=2022.02 ID=buildroot VERSION_ID=2022.02 PRETTY_NAME="Buildroot 2022.02" distro-1.9.0/tests/resources/distros/centos5/000077500000000000000000000000001454137533700212645ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/centos5/etc/000077500000000000000000000000001454137533700220375ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/centos5/etc/centos-release000066400000000000000000000000341454137533700246700ustar00rootroot00000000000000CentOS release 5.11 (Final) distro-1.9.0/tests/resources/distros/centos5/etc/redhat-release000077700000000000000000000000001454137533700274762centos-releaseustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/centos5/etc/system-release000077700000000000000000000000001454137533700275532centos-releaseustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/centos7/000077500000000000000000000000001454137533700212665ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/centos7/etc/000077500000000000000000000000001454137533700220415ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/centos7/etc/centos-release000066400000000000000000000000461454137533700246750ustar00rootroot00000000000000CentOS Linux release 7.1.1503 (Core) distro-1.9.0/tests/resources/distros/centos7/etc/os-release000066400000000000000000000006111454137533700240210ustar00rootroot00000000000000NAME="CentOS Linux" VERSION="7 (Core)" ID="centos" ID_LIKE="rhel fedora" VERSION_ID="7" PRETTY_NAME="CentOS Linux 7 (Core)" ANSI_COLOR="0;31" CPE_NAME="cpe:/o:centos:centos:7" HOME_URL="https://www.centos.org/" BUG_REPORT_URL="https://bugs.centos.org/" CENTOS_MANTISBT_PROJECT="CentOS-7" CENTOS_MANTISBT_PROJECT_VERSION="7" REDHAT_SUPPORT_PRODUCT="centos" REDHAT_SUPPORT_PRODUCT_VERSION="7" distro-1.9.0/tests/resources/distros/centos7/etc/redhat-release000077700000000000000000000000001454137533700275002centos-releaseustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/centos7/etc/system-release000077700000000000000000000000001454137533700275552centos-releaseustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/cloudlinux5/000077500000000000000000000000001454137533700221575ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/cloudlinux5/etc/000077500000000000000000000000001454137533700227325ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/cloudlinux5/etc/redhat-release000066400000000000000000000000621454137533700255400ustar00rootroot00000000000000CloudLinux Server release 5.11 (Vladislav Volkov) distro-1.9.0/tests/resources/distros/cloudlinux6/000077500000000000000000000000001454137533700221605ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/cloudlinux6/etc/000077500000000000000000000000001454137533700227335ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/cloudlinux6/etc/redhat-release000066400000000000000000000000551454137533700255430ustar00rootroot00000000000000CloudLinux Server release 6.8 (Oleg Makarov) distro-1.9.0/tests/resources/distros/cloudlinux7/000077500000000000000000000000001454137533700221615ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/cloudlinux7/etc/000077500000000000000000000000001454137533700227345ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/cloudlinux7/etc/os-release000066400000000000000000000004741454137533700247230ustar00rootroot00000000000000NAME="CloudLinux" VERSION="7.3 (Yury Malyshev)" ID="cloudlinux" ID_LIKE="rhel fedora centos" VERSION_ID="7.3" PRETTY_NAME="CloudLinux 7.3 (Yury Malyshev)" ANSI_COLOR="0:31" CPE_NAME="cpe:/o:cloudlinux:cloudlinux:7.3:GA:server" HOME_URL="https://www.cloudlinux.com/" BUG_REPORT_URL="https://helpdesk.cloudlinux.com/" distro-1.9.0/tests/resources/distros/cloudlinux7/etc/redhat-release000066400000000000000000000000471454137533700255450ustar00rootroot00000000000000CloudLinux release 7.3 (Yury Malyshev) distro-1.9.0/tests/resources/distros/coreos/000077500000000000000000000000001454137533700211765ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/coreos/etc/000077500000000000000000000000001454137533700217515ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/coreos/etc/oem-release000066400000000000000000000002241454137533700240700ustar00rootroot00000000000000ID=digitalocean VERSION_ID=0.0.4 NAME="DigitalOcean" HOME_URL="https://www.digitalocean.com/" BUG_REPORT_URL="https://github.com/coreos/bugs/issues"distro-1.9.0/tests/resources/distros/coreos/etc/os-release000066400000000000000000000003311454137533700237300ustar00rootroot00000000000000NAME=CoreOS ID=coreos VERSION=899.15.0 VERSION_ID=899.15.0 BUILD_ID=2016-04-05-1035 PRETTY_NAME="CoreOS 899.15.0" ANSI_COLOR="1;32" HOME_URL="https://coreos.com/" BUG_REPORT_URL="https://github.com/coreos/bugs/issues"distro-1.9.0/tests/resources/distros/debian10/000077500000000000000000000000001454137533700212675ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/debian10/bin/000077500000000000000000000000001454137533700220375ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/debian10/bin/lsb_release000066400000000000000000000006661454137533700242520ustar00rootroot00000000000000#!/bin/bash # # lsb_release command for testing the ld module. # Only the -a option is supported. # # This version of the lsb_release command works without a corresponding # etc/lsb-release file. # if [[ "$@" != "-a" ]]; then echo "Usage: lsb_release -a" exit 2 fi echo "No LSB modules are available." echo "Distributor ID: Debian" echo "Description: Debian GNU/Linux 10 (buster)" echo "Release: 10" echo "Codename: buster" exit 0 distro-1.9.0/tests/resources/distros/debian10/etc/000077500000000000000000000000001454137533700220425ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/debian10/etc/debian_version000066400000000000000000000000061454137533700247500ustar00rootroot0000000000000010.11 distro-1.9.0/tests/resources/distros/debian10/etc/os-release000066400000000000000000000004051454137533700240230ustar00rootroot00000000000000PRETTY_NAME="Debian GNU/Linux 10 (buster)" NAME="Debian GNU/Linux" VERSION_ID="10" VERSION="10 (buster)" VERSION_CODENAME=buster ID=debian HOME_URL="https://www.debian.org/" SUPPORT_URL="https://www.debian.org/support" BUG_REPORT_URL="https://bugs.debian.org/" distro-1.9.0/tests/resources/distros/debian8/000077500000000000000000000000001454137533700212165ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/debian8/bin/000077500000000000000000000000001454137533700217665ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/debian8/bin/lsb_release000077500000000000000000000006701454137533700241770ustar00rootroot00000000000000#!/bin/bash # # lsb_release command for testing the ld module. # Only the -a option is supported. # # This version of the lsb_release command works without a corresponding # etc/lsb-release file. # if [[ "$@" != "-a" ]]; then echo "Usage: lsb_release -a" exit 2 fi echo "No LSB modules are available." echo "Distributor ID: Debian" echo "Description: Debian GNU/Linux 8.2 (jessie)" echo "Release: 8.2" echo "Codename: jessie" exit 0 distro-1.9.0/tests/resources/distros/debian8/etc/000077500000000000000000000000001454137533700217715ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/debian8/etc/debian_version000066400000000000000000000000031454137533700246740ustar00rootroot000000000000008.2distro-1.9.0/tests/resources/distros/debian8/etc/os-release000066400000000000000000000003511454137533700237520ustar00rootroot00000000000000PRETTY_NAME="Debian GNU/Linux 8 (jessie)" NAME="Debian GNU/Linux" VERSION_ID="8" VERSION="8 (jessie)" ID=debian HOME_URL="http://www.debian.org/" SUPPORT_URL="http://www.debian.org/support/" BUG_REPORT_URL="https://bugs.debian.org/" distro-1.9.0/tests/resources/distros/debiantesting/000077500000000000000000000000001454137533700225245ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/debiantesting/bin/000077500000000000000000000000001454137533700232745ustar00rootroot00000000000000distro-1.9.0/tests/resources/distros/debiantesting/bin/lsb_release000077500000000000000000000006451454137533700255070ustar00rootroot00000000000000#!/bin/bash # # lsb_release command for testing the ld module. # Only the -a option is supported. # # This version of the lsb_release command works without a corresponding # etc/lsb-release file. # if [[ "$@" != "-a" ]]; then echo "Usage: lsb_release -a" exit 2 fi cat < None: try: import distro # NOQA except ImportError as ex: assert "Unsupported platform" in str(ex) @pytest.mark.skipif(not IS_LINUX, reason="Irrelevant on non-linux") class TestCli: def _parse(self, command: str) -> None: sys.argv = command.split() distro.main() def _run(self, command: List[str]) -> str: r = subprocess.run( command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8", ) return r.stdout def test_cli_for_coverage_yuch(self) -> None: self._parse("distro") self._parse("distro -j") def test_cli_can_parse_root_dir_args(self) -> None: root_dir = os.path.join(RESOURCES, "cli", "fedora30") self._parse(f"distro --root-dir {root_dir}") def test_cli(self) -> None: command = [sys.executable, "-m", "distro"] desired_output = f"Name: {distro.name(pretty=True)}" distro_version = distro.version(pretty=True) distro_codename = distro.codename() desired_output += f"\nVersion: {distro_version}" desired_output += f"\nCodename: {distro_codename}" desired_output += "\n" assert self._run(command) == desired_output def test_cli_json(self) -> None: command = [sys.executable, "-m", "distro", "-j"] assert ast.literal_eval(self._run(command)) == distro.info() def test_cli_with_root_dir(self) -> None: root_dir = os.path.join(RESOURCES, "cli", "fedora30") command = [sys.executable, "-m", "distro", "--root-dir", root_dir] desired_output = "Name: Fedora 30 (Thirty)\nVersion: 30\nCodename: \n" assert desired_output == self._run(command) def test_cli_with_root_dir_as_json(self) -> None: root_dir = os.path.join(RESOURCES, "cli", "fedora30") command = [sys.executable, "-m", "distro", "-j", "--root-dir", root_dir] desired_output = { "codename": "", "id": "fedora", "like": "", "version": "30", "version_parts": {"build_number": "", "major": "30", "minor": ""}, } results = json.loads(self._run(command)) assert desired_output == results @pytest.mark.skipif(not IS_LINUX, reason="Irrelevant on non-linux") class DistroTestCase: """A base class for any testcase classes that test the distributions represented in the `DISTROS` subtree. """ def setup_method(self, test_method: FunctionType) -> None: # The environment stays the same across all testcases, so we # save and restore the PATH env var in each test case that # changes it: self._saved_path = os.environ["PATH"] self._saved_UNIXCONFDIR = distro._UNIXCONFDIR self._saved_UNIXUSRLIBDIR = distro._UNIXUSRLIBDIR def teardown_method(self, test_method: FunctionType) -> None: os.environ["PATH"] = self._saved_path distro._UNIXCONFDIR = self._saved_UNIXCONFDIR distro._UNIXUSRLIBDIR = self._saved_UNIXUSRLIBDIR def _setup_for_distro(self, distro_root: str) -> None: distro_bin = os.path.join(distro_root, "bin") # We don't want to pick up a possibly present lsb_release in the # distro that runs this test, so we use a PATH with only one entry: os.environ["PATH"] = distro_bin distro._UNIXCONFDIR = os.path.join(distro_root, RELATIVE_UNIXCONFDIR) distro._UNIXUSRLIBDIR = os.path.join(distro_root, RELATIVE_UNIXUSRLIBDIR) @pytest.mark.skipif(not IS_LINUX, reason="Irrelevant on non-linux") class TestOSRelease: def setup_method(self, test_method: FunctionType) -> None: dist = test_method.__name__.split("_")[1] self.distro = distro.LinuxDistribution( include_lsb=False, distro_release_file="path-to-non-existing-file", root_dir=os.path.join(DISTROS_DIR, dist), ) def _test_outcome(self, outcome: Dict[str, str]) -> None: assert self.distro.id() == outcome.get("id", "") assert self.distro.name() == outcome.get("name", "") assert self.distro.name(pretty=True) == outcome.get("pretty_name", "") assert self.distro.version() == outcome.get("version", "") assert self.distro.version(pretty=True) == outcome.get("pretty_version", "") assert self.distro.version(best=True) == outcome.get("best_version", "") assert self.distro.like() == outcome.get("like", "") assert self.distro.codename() == outcome.get("codename", "") def test_arch_os_release(self) -> None: desired_outcome = { "id": "arch", "name": "Arch Linux", "pretty_name": "Arch Linux", } self._test_outcome(desired_outcome) def test_buildroot_os_release(self) -> None: desired_outcome = { "id": "buildroot", "name": "Buildroot", "pretty_name": "Buildroot 2022.02", "version": "2022.02", "pretty_version": "2022.02", "best_version": "2022.02", } self._test_outcome(desired_outcome) def test_kali_os_release(self) -> None: desired_outcome = { "id": "kali", "name": "Kali GNU/Linux", "pretty_name": "Kali GNU/Linux Rolling", "version": "2017.1", "pretty_version": "2017.1", "best_version": "2017.1", "like": "debian", } self._test_outcome(desired_outcome) def test_centos7_os_release(self) -> None: desired_outcome = { "id": "centos", "name": "CentOS Linux", "pretty_name": "CentOS Linux 7 (Core)", "version": "7", "pretty_version": "7 (Core)", "best_version": "7", "like": "rhel fedora", "codename": "Core", } self._test_outcome(desired_outcome) def test_coreos_os_release(self) -> None: desired_outcome = { "id": "coreos", "name": "CoreOS", "pretty_name": "CoreOS 899.15.0", "version": "899.15.0", "pretty_version": "899.15.0", "best_version": "899.15.0", } self._test_outcome(desired_outcome) def test_debian8_os_release(self) -> None: desired_outcome = { "id": "debian", "name": "Debian GNU/Linux", "pretty_name": "Debian GNU/Linux 8 (jessie)", "version": "8", "pretty_version": "8 (jessie)", "best_version": "8.2", "codename": "jessie", } self._test_outcome(desired_outcome) def test_debian10_os_release(self) -> None: desired_outcome = { "id": "debian", "name": "Debian GNU/Linux", "pretty_name": "Debian GNU/Linux 10 (buster)", "version": "10", "pretty_version": "10 (buster)", "best_version": "10.11", "codename": "buster", } self._test_outcome(desired_outcome) def test_debiantesting_os_release(self) -> None: desired_outcome = { "id": "debian", "name": "Debian GNU/Linux", "pretty_name": "Debian GNU/Linux bookworm/sid", "version": "bookworm/sid", "pretty_version": "bookworm/sid (bookworm)", "best_version": "bookworm/sid", "codename": "bookworm", } self._test_outcome(desired_outcome) def test_fedora19_os_release(self) -> None: desired_outcome = { "id": "fedora", "name": "Fedora", "pretty_name": "Fedora 19 (Schrödinger’s Cat)", "version": "19", "pretty_version": "19 (Schrödinger’s Cat)", "best_version": "19", "codename": "Schrödinger’s Cat", } self._test_outcome(desired_outcome) def test_fedora23_os_release(self) -> None: desired_outcome = { "id": "fedora", "name": "Fedora", "pretty_name": "Fedora 23 (Twenty Three)", "version": "23", "pretty_version": "23 (Twenty Three)", "best_version": "23", "codename": "Twenty Three", } self._test_outcome(desired_outcome) def test_fedora30_os_release(self) -> None: # Fedora 21 and above no longer have code names but the metadata in # os-release was only changed in a detectable way in Fedora 30+. The # piece in parenthesis in the pretty_name field contains the VARIANT # and differs depending on the variant which was installed. desired_outcome = { "id": "fedora", "name": "Fedora", "pretty_name": "Fedora 30 (Thirty)", "version": "30", "pretty_version": "30", "best_version": "30", "codename": "", } self._test_outcome(desired_outcome) def test_guix_os_release(self) -> None: desired_outcome = { "id": "guix", "name": "Guix System", "pretty_name": "Guix System", } self._test_outcome(desired_outcome) def test_kvmibm1_os_release(self) -> None: desired_outcome = { "id": "kvmibm", "name": "KVM for IBM z Systems", "pretty_name": "KVM for IBM z Systems 1.1.1 (Z)", "version": "1.1.1", "pretty_version": "1.1.1 (Z)", "best_version": "1.1.1", "like": "rhel fedora", "codename": "Z", } self._test_outcome(desired_outcome) def test_linuxmint17_os_release(self) -> None: # Note: LinuxMint 17 actually *does* have Ubuntu 14.04 data in its # os-release file. See discussion in GitHub issue #78. desired_outcome = { "id": "ubuntu", "name": "Ubuntu", "pretty_name": "Ubuntu 14.04.3 LTS", "version": "14.04", "pretty_version": "14.04 (Trusty Tahr)", "best_version": "14.04.3", "like": "debian", "codename": "Trusty Tahr", } self._test_outcome(desired_outcome) def test_mageia5_os_release(self) -> None: desired_outcome = { "id": "mageia", "name": "Mageia", "pretty_name": "Mageia 5", "version": "5", "pretty_version": "5", "best_version": "5", "like": "mandriva fedora", } self._test_outcome(desired_outcome) def test_manjaro1512_os_release(self) -> None: self._test_outcome( {"id": "manjaro", "name": "Manjaro Linux", "pretty_name": "Manjaro Linux"} ) def test_opensuse42_os_release(self) -> None: desired_outcome = { "id": "opensuse", "name": "openSUSE Leap", "pretty_name": "openSUSE Leap 42.1 (x86_64)", "version": "42.1", "pretty_version": "42.1", "best_version": "42.1", "like": "suse", } self._test_outcome(desired_outcome) def test_opensuse15_os_release(self) -> None: desired_outcome = { "id": "opensuse", "name": "openSUSE Leap", "pretty_name": "openSUSE Leap 15.2", "version": "15.2", "pretty_version": "15.2", "best_version": "15.2", "like": "suse opensuse", } self._test_outcome(desired_outcome) def test_raspbian7_os_release(self) -> None: desired_outcome = { "id": "raspbian", "name": "Raspbian GNU/Linux", "pretty_name": "Raspbian GNU/Linux 7 (wheezy)", "version": "7", "pretty_version": "7 (wheezy)", "best_version": "7.1", "like": "debian", "codename": "wheezy", } self._test_outcome(desired_outcome) def test_raspbian8_os_release(self) -> None: desired_outcome = { "id": "raspbian", "name": "Raspbian GNU/Linux", "pretty_name": "Raspbian GNU/Linux 8 (jessie)", "version": "8", "pretty_version": "8 (jessie)", "best_version": "8.0", "like": "debian", "codename": "jessie", } self._test_outcome(desired_outcome) def test_rhel7_os_release(self) -> None: desired_outcome = { "id": "rhel", "name": "Red Hat Enterprise Linux Server", "pretty_name": "Red Hat Enterprise Linux Server 7.0 (Maipo)", "version": "7.0", "pretty_version": "7.0 (Maipo)", "best_version": "7.0", "like": "fedora", "codename": "Maipo", } self._test_outcome(desired_outcome) def test_rocky_os_release(self) -> None: desired_outcome = { "id": "rocky", "name": "Rocky Linux", "pretty_name": "Rocky Linux 8.4 (Green Obsidian)", "version": "8.4", "pretty_version": "8.4 (Green Obsidian)", "best_version": "8.4", "like": "rhel centos fedora", "codename": "Green Obsidian", } self._test_outcome(desired_outcome) def test_slackware14_os_release(self) -> None: desired_outcome = { "id": "slackware", "name": "Slackware", "pretty_name": "Slackware 14.1", "version": "14.1", "pretty_version": "14.1", "best_version": "14.1", } self._test_outcome(desired_outcome) def test_sles12_os_release(self) -> None: desired_outcome = { "id": "sles", "name": "SLES", "pretty_name": "SUSE Linux Enterprise Server 12 SP1", "version": "12.1", "pretty_version": "12.1", "best_version": "12.1", } self._test_outcome(desired_outcome) def test_ubuntu14_os_release(self) -> None: desired_outcome = { "id": "ubuntu", "name": "Ubuntu", "pretty_name": "Ubuntu 14.04.3 LTS", "version": "14.04", "pretty_version": "14.04 (Trusty Tahr)", "best_version": "14.04.3", "like": "debian", "codename": "Trusty Tahr", } self._test_outcome(desired_outcome) def test_ubuntu16_os_release(self) -> None: desired_outcome = { "id": "ubuntu", "name": "Ubuntu", "pretty_name": "Ubuntu 16.04.1 LTS", "version": "16.04", "pretty_version": "16.04 (xenial)", "best_version": "16.04.1", "like": "debian", "codename": "xenial", } self._test_outcome(desired_outcome) def test_amazon2016_os_release(self) -> None: desired_outcome = { "id": "amzn", "name": "Amazon Linux AMI", "pretty_name": "Amazon Linux AMI 2016.03", "version": "2016.03", "pretty_version": "2016.03", "best_version": "2016.03", "like": "rhel fedora", } self._test_outcome(desired_outcome) def test_scientific7_os_release(self) -> None: desired_outcome = { "id": "rhel", "name": "Scientific Linux", "pretty_name": "Scientific Linux 7.2 (Nitrogen)", "version": "7.2", "pretty_version": "7.2 (Nitrogen)", "best_version": "7.2", "like": "fedora", "codename": "Nitrogen", } self._test_outcome(desired_outcome) def test_gentoo_os_release(self) -> None: desired_outcome = { "id": "gentoo", "name": "Gentoo", "pretty_name": "Gentoo/Linux", } self._test_outcome(desired_outcome) def test_openelec6_os_release(self) -> None: desired_outcome = { "id": "openelec", "name": "OpenELEC", "pretty_name": "OpenELEC (official) - Version: 6.0.3", "version": "6.0", "pretty_version": "6.0", "best_version": "6.0.3", } self._test_outcome(desired_outcome) def test_cloudlinux7_os_release(self) -> None: desired_outcome = { "id": "cloudlinux", "codename": "Yury Malyshev", "name": "CloudLinux", "pretty_name": "CloudLinux 7.3 (Yury Malyshev)", "like": "rhel fedora centos", "version": "7.3", "pretty_version": "7.3 (Yury Malyshev)", "best_version": "7.3", "major_version": "7", "minor_version": "3", } self._test_outcome(desired_outcome) def test_altlinux10_os_release(self) -> None: desired_outcome = { "id": "altlinux", "name": "ALT Server", "pretty_name": "ALT Server 10.1 (Mendelevium)", "version": "10.1", "pretty_version": "10.1", "best_version": "10.1", "major_version": "10", "minor_version": "1", } self._test_outcome(desired_outcome) def test_bttcb1_os_release(self) -> None: desired_outcome = { "id": "debian", "codename": "bullseye", "name": "Debian GNU/Linux", "pretty_name": "BTT-CB1 2.3.1 Bullseye", "like": "", "version": "11", "pretty_version": "11 (bullseye)", "best_version": "11", "major_version": "11", "minor_version": "0", } self._test_outcome(desired_outcome) class TestWithRootDir(TestOSRelease): """Test that a LinuxDistribution can be created using an arbitrary root_dir on all OSes. """ def setup_method(self, test_method: FunctionType) -> None: dist = test_method.__name__.split("_")[1] root_dir = os.path.join(DISTROS_DIR, dist) self.distro = distro.LinuxDistribution( include_lsb=False, include_uname=False, include_oslevel=False, os_release_file="", distro_release_file="path-to-non-existing-file", root_dir=root_dir, ) @pytest.mark.skipif(not IS_LINUX, reason="Irrelevant on non-linux") class TestLSBRelease(DistroTestCase): def setup_method(self, test_method: FunctionType) -> None: super().setup_method(test_method) dist = test_method.__name__.split("_")[1] self._setup_for_distro(os.path.join(DISTROS_DIR, dist)) self.distro = distro.LinuxDistribution( os_release_file="path-to-non-existing-file", distro_release_file="path-to-non-existing-file", ) def _test_outcome(self, outcome: Dict[str, str]) -> None: assert self.distro.id() == outcome.get("id", "") assert self.distro.name() == outcome.get("name", "") assert self.distro.name(pretty=True) == outcome.get("pretty_name", "") assert self.distro.version() == outcome.get("version", "") assert self.distro.version(pretty=True) == outcome.get("pretty_version", "") assert self.distro.version(best=True) == outcome.get("best_version", "") assert self.distro.like() == outcome.get("like", "") assert self.distro.codename() == outcome.get("codename", "") def test_linuxmint17_lsb_release(self) -> None: desired_outcome = { "id": "linuxmint", "name": "LinuxMint", "pretty_name": "Linux Mint 17.3 Rosa", "version": "17.3", "pretty_version": "17.3 (rosa)", "best_version": "17.3", "codename": "rosa", } self._test_outcome(desired_outcome) def test_manjaro1512_lsb_release(self) -> None: self._test_outcome( { "id": "manjarolinux", "name": "ManjaroLinux", "pretty_name": "Manjaro Linux", "version": "15.12", "pretty_version": "15.12 (Capella)", "best_version": "15.12", "codename": "Capella", } ) # @pytest.mark.xfail # def test_openelec6_lsb_release(self) -> None: # # TODO: This should be fixed as part of #109 when dealing # # with distro inconsistencies # desired_outcome = { # 'id': 'openelec', # 'name': 'OpenELEC', # 'pretty_name': 'OpenELEC (official) - Version: 6.0.3', # 'version': '6.0.3', # 'pretty_version': '6.0.3', # 'best_version': '6.0.3', # } # self._test_outcome(desired_outcome) def test_openbsd62_uname(self) -> None: self._test_outcome( { "id": "openbsd", "name": "OpenBSD", "version": "6.2", "pretty_name": "OpenBSD 6.2", "pretty_version": "6.2", "best_version": "6.2", } ) def test_netbsd711_uname(self) -> None: self._test_outcome( { "id": "netbsd", "name": "NetBSD", "version": "7.1.1", "pretty_name": "NetBSD 7.1.1", "pretty_version": "7.1.1", "best_version": "7.1.1", } ) def test_freebsd111_uname(self) -> None: self._test_outcome( { "id": "freebsd", "name": "FreeBSD", "version": "11.1", "pretty_name": "FreeBSD 11.1", "pretty_version": "11.1", "best_version": "11.1", } ) def test_midnightbsd12_uname(self) -> None: self._test_outcome( { "id": "midnightbsd", "name": "MidnightBSD", "version": "1.2", "pretty_name": "MidnightBSD 1.2", "pretty_version": "1.2", "best_version": "1.2", } ) def test_ubuntu14normal_lsb_release(self) -> None: self._setup_for_distro(os.path.join(TESTDISTROS, "lsb", "ubuntu14_normal")) self.distro = distro.LinuxDistribution( os_release_file="path-to-non-existing-file", distro_release_file="path-to-non-existing-file", ) desired_outcome = { "id": "ubuntu", "name": "Ubuntu", "pretty_name": "Ubuntu 14.04.3 LTS", "version": "14.04", "pretty_version": "14.04 (trusty)", "best_version": "14.04.3", "codename": "trusty", } self._test_outcome(desired_outcome) def test_ubuntu14nomodules_lsb_release(self) -> None: self._setup_for_distro(os.path.join(TESTDISTROS, "lsb", "ubuntu14_nomodules")) self.distro = distro.LinuxDistribution( os_release_file="path-to-non-existing-file", distro_release_file="path-to-non-existing-file", ) desired_outcome = { "id": "ubuntu", "name": "Ubuntu", "pretty_name": "Ubuntu 14.04.3 LTS", "version": "14.04", "pretty_version": "14.04 (trusty)", "best_version": "14.04.3", "codename": "trusty", } self._test_outcome(desired_outcome) def test_trailingblanks_lsb_release(self) -> None: self._setup_for_distro( os.path.join(TESTDISTROS, "lsb", "ubuntu14_trailingblanks") ) self.distro = distro.LinuxDistribution( os_release_file="path-to-non-existing-file", distro_release_file="path-to-non-existing-file", ) desired_outcome = { "id": "ubuntu", "name": "Ubuntu", "pretty_name": "Ubuntu 14.04.3 LTS", "version": "14.04", "pretty_version": "14.04 (trusty)", "best_version": "14.04.3", "codename": "trusty", } self._test_outcome(desired_outcome) @pytest.mark.parametrize("errnum", ("001", "002", "126", "130", "255")) def test_lsb_release_error_level(self, errnum: str) -> None: self._setup_for_distro(os.path.join(TESTDISTROS, "lsb", f"lsb_rc{errnum}")) lsb_release_info = distro.LinuxDistribution( os_release_file="path-to-non-existing-file", distro_release_file="path-to-non-existing-file", )._lsb_release_info assert lsb_release_info == {} @pytest.mark.skipif(not IS_LINUX, reason="Irrelevant on non-linux") class TestSpecialRelease(DistroTestCase): def _test_outcome(self, outcome: Dict[str, str]) -> None: assert self.distro.id() == outcome.get("id", "") assert self.distro.name() == outcome.get("name", "") assert self.distro.name(pretty=True) == outcome.get("pretty_name", "") assert self.distro.version() == outcome.get("version", "") assert self.distro.version(pretty=True) == outcome.get("pretty_version", "") assert self.distro.version(best=True) == outcome.get("best_version", "") assert self.distro.like() == outcome.get("like", "") assert self.distro.codename() == outcome.get("codename", "") assert self.distro.major_version() == outcome.get("major_version", "") assert self.distro.minor_version() == outcome.get("minor_version", "") assert self.distro.build_number() == outcome.get("build_number", "") def test_empty_release(self) -> None: distro_release = os.path.join(SPECIAL, "empty-release") self.distro = distro.LinuxDistribution( include_lsb=False, os_release_file="path-to-non-existing-file", distro_release_file=distro_release, ) desired_outcome = {"id": "empty"} self._test_outcome(desired_outcome) def test_dontincludeuname(self) -> None: self._setup_for_distro(os.path.join(TESTDISTROS, "distro", "dontincludeuname")) self.distro = distro.LinuxDistribution(include_uname=False) assert self.distro.uname_attr("id") == "" assert self.distro.uname_attr("name") == "" assert self.distro.uname_attr("release") == "" def test_unknowndistro_release(self) -> None: self._setup_for_distro(os.path.join(TESTDISTROS, "distro", "unknowndistro")) self.distro = distro.LinuxDistribution() desired_outcome = { "id": "unknowndistro", "name": "Unknown Distro", "pretty_name": "Unknown Distro 1.0 (Unknown Codename)", "version": "1.0", "pretty_version": "1.0 (Unknown Codename)", "best_version": "1.0", "codename": "Unknown Codename", "major_version": "1", "minor_version": "0", } self._test_outcome(desired_outcome) def test_bad_uname(self) -> None: self._setup_for_distro(os.path.join(TESTDISTROS, "distro", "baduname")) self.distro = distro.LinuxDistribution() assert self.distro.uname_attr("id") == "" assert self.distro.uname_attr("name") == "" assert self.distro.uname_attr("release") == "" def test_empty_uname(self) -> None: self._setup_for_distro(os.path.join(TESTDISTROS, "distro", "emptyuname")) self.distro = distro.LinuxDistribution() assert self.distro.uname_attr("id") == "" assert self.distro.uname_attr("name") == "" assert self.distro.uname_attr("release") == "" def test_usrlibosreleaseonly(self) -> None: self._setup_for_distro( os.path.join(TESTDISTROS, "distro", "usrlibosreleaseonly") ) self.distro = distro.LinuxDistribution() desired_outcome = { "id": "usrlibosreleaseonly", "name": "usr_lib_os-release_only", "pretty_name": "/usr/lib/os-release only", } self._test_outcome(desired_outcome) @pytest.mark.skipif(not IS_LINUX, reason="Irrelevant on non-linux") class TestDistroRelease: def _test_outcome( self, outcome: Dict[str, str], distro_name: str = "", version: str = "", release_file_id: str = "", release_file_suffix: str = "release", ) -> None: release_file_id = release_file_id or distro_name distro_release = os.path.join( DISTROS_DIR, distro_name + version, "etc", f"{release_file_id}-{release_file_suffix}", ) self.distro = distro.LinuxDistribution( include_lsb=False, os_release_file="path-to-non-existing-file", distro_release_file=distro_release, ) assert self.distro.id() == outcome.get("id", "") assert self.distro.name() == outcome.get("name", "") assert self.distro.name(pretty=True) == outcome.get("pretty_name", "") assert self.distro.version() == outcome.get("version", "") assert self.distro.version(pretty=True) == outcome.get("pretty_version", "") assert self.distro.version(best=True) == outcome.get("best_version", "") assert self.distro.like() == outcome.get("like", "") assert self.distro.codename() == outcome.get("codename", "") assert self.distro.major_version() == outcome.get("major_version", "") assert self.distro.minor_version() == outcome.get("minor_version", "") assert self.distro.build_number() == outcome.get("build_number", "") def test_arch_dist_release(self) -> None: desired_outcome = {"id": "arch"} self._test_outcome(desired_outcome, "arch") def test_centos5_dist_release(self) -> None: desired_outcome = { "id": "centos", "name": "CentOS", "pretty_name": "CentOS 5.11 (Final)", "version": "5.11", "pretty_version": "5.11 (Final)", "best_version": "5.11", "codename": "Final", "major_version": "5", "minor_version": "11", } self._test_outcome(desired_outcome, "centos", "5") def test_centos7_dist_release(self) -> None: desired_outcome = { "id": "centos", "name": "CentOS Linux", "pretty_name": "CentOS Linux 7.1.1503 (Core)", "version": "7.1.1503", "pretty_version": "7.1.1503 (Core)", "best_version": "7.1.1503", "codename": "Core", "major_version": "7", "minor_version": "1", "build_number": "1503", } self._test_outcome(desired_outcome, "centos", "7") def test_fedora19_dist_release(self) -> None: desired_outcome = { "id": "fedora", "name": "Fedora", "pretty_name": "Fedora 19 (Schrödinger’s Cat)", "version": "19", "pretty_version": "19 (Schrödinger’s Cat)", "best_version": "19", "codename": "Schrödinger’s Cat", "major_version": "19", } self._test_outcome(desired_outcome, "fedora", "19") def test_fedora23_dist_release(self) -> None: desired_outcome = { "id": "fedora", "name": "Fedora", "pretty_name": "Fedora 23 (Twenty Three)", "version": "23", "pretty_version": "23 (Twenty Three)", "best_version": "23", "codename": "Twenty Three", "major_version": "23", } self._test_outcome(desired_outcome, "fedora", "23") def test_fedora30_dist_release(self) -> None: desired_outcome = { "id": "fedora", "name": "Fedora", "pretty_name": "Fedora 30 (Thirty)", "version": "30", "pretty_version": "30 (Thirty)", "best_version": "30", "codename": "Thirty", "major_version": "30", } self._test_outcome(desired_outcome, "fedora", "30") def test_gentoo_dist_release(self) -> None: desired_outcome = { "id": "gentoo", "name": "Gentoo Base System", "pretty_name": "Gentoo Base System 2.2", "version": "2.2", "pretty_version": "2.2", "best_version": "2.2", "major_version": "2", "minor_version": "2", } self._test_outcome(desired_outcome, "gentoo") def test_kvmibm1_dist_release(self) -> None: desired_outcome = { "id": "base", "name": "KVM for IBM z Systems", "pretty_name": "KVM for IBM z Systems 1.1.1 (Z)", "version": "1.1.1", "pretty_version": "1.1.1 (Z)", "best_version": "1.1.1", "codename": "Z", "major_version": "1", "minor_version": "1", "build_number": "1", } self._test_outcome(desired_outcome, "kvmibm", "1", "base") def test_mageia5_dist_release(self) -> None: desired_outcome = { "id": "mageia", "name": "Mageia", "pretty_name": "Mageia 5 (Official)", "version": "5", "pretty_version": "5 (Official)", "best_version": "5", "codename": "Official", "major_version": "5", } self._test_outcome(desired_outcome, "mageia", "5") def test_manjaro1512_dist_release(self) -> None: self._test_outcome( { "id": "manjaro", "name": "Manjaro Linux", "pretty_name": "Manjaro Linux", "version": "", "codename": "", }, "manjaro", "1512", ) def test_opensuse42_dist_release(self) -> None: desired_outcome = { "id": "suse", "name": "openSUSE", "pretty_name": "openSUSE 42.1 (x86_64)", "version": "42.1", "pretty_version": "42.1 (x86_64)", "best_version": "42.1", "codename": "x86_64", "major_version": "42", "minor_version": "1", } self._test_outcome(desired_outcome, "opensuse", "42", "SuSE") def test_oracle7_dist_release(self) -> None: desired_outcome = { "id": "oracle", "name": "Oracle Linux Server", "pretty_name": "Oracle Linux Server 7.5", "version": "7.5", "pretty_version": "7.5", "best_version": "7.5", "major_version": "7", "minor_version": "5", } self._test_outcome(desired_outcome, "oracle", "7") def test_rhel6_dist_release(self) -> None: desired_outcome = { "id": "rhel", "name": "Red Hat Enterprise Linux Server", "pretty_name": "Red Hat Enterprise Linux Server 6.5 (Santiago)", "version": "6.5", "pretty_version": "6.5 (Santiago)", "best_version": "6.5", "codename": "Santiago", "major_version": "6", "minor_version": "5", } self._test_outcome(desired_outcome, "rhel", "6", "redhat") def test_rhel7_dist_release(self) -> None: desired_outcome = { "id": "rhel", "name": "Red Hat Enterprise Linux Server", "pretty_name": "Red Hat Enterprise Linux Server 7.0 (Maipo)", "version": "7.0", "pretty_version": "7.0 (Maipo)", "best_version": "7.0", "codename": "Maipo", "major_version": "7", "minor_version": "0", } self._test_outcome(desired_outcome, "rhel", "7", "redhat") def test_slackware14_dist_release(self) -> None: desired_outcome = { "id": "slackware", "name": "Slackware", "pretty_name": "Slackware 14.1", "version": "14.1", "pretty_version": "14.1", "best_version": "14.1", "major_version": "14", "minor_version": "1", } self._test_outcome( desired_outcome, "slackware", "14", release_file_suffix="version" ) def test_sles12_dist_release(self) -> None: desired_outcome = { "id": "suse", "name": "SUSE Linux Enterprise Server", "pretty_name": "SUSE Linux Enterprise Server 12 (s390x)", "version": "12", "pretty_version": "12 (s390x)", "best_version": "12", "major_version": "12", "codename": "s390x", } self._test_outcome(desired_outcome, "sles", "12", "SuSE") def test_cloudlinux5_dist_release(self) -> None: # Uses redhat-release only to get information. # The id of 'rhel' can only be fixed with issue #109. desired_outcome = { "id": "cloudlinux", "codename": "Vladislav Volkov", "name": "CloudLinux Server", "pretty_name": "CloudLinux Server 5.11 (Vladislav Volkov)", "version": "5.11", "pretty_version": "5.11 (Vladislav Volkov)", "best_version": "5.11", "major_version": "5", "minor_version": "11", } self._test_outcome(desired_outcome, "cloudlinux", "5", "redhat") def test_cloudlinux6_dist_release(self) -> None: # Same as above, only has redhat-release. desired_outcome = { "id": "cloudlinux", "codename": "Oleg Makarov", "name": "CloudLinux Server", "pretty_name": "CloudLinux Server 6.8 (Oleg Makarov)", "version": "6.8", "pretty_version": "6.8 (Oleg Makarov)", "best_version": "6.8", "major_version": "6", "minor_version": "8", } self._test_outcome(desired_outcome, "cloudlinux", "6", "redhat") def test_cloudlinux7_dist_release(self) -> None: desired_outcome = { "id": "cloudlinux", "codename": "Yury Malyshev", "name": "CloudLinux", "pretty_name": "CloudLinux 7.3 (Yury Malyshev)", "version": "7.3", "pretty_version": "7.3 (Yury Malyshev)", "best_version": "7.3", "major_version": "7", "minor_version": "3", } self._test_outcome(desired_outcome, "cloudlinux", "7", "redhat") def test_altlinux10_dist_release(self) -> None: desired_outcome = { "id": "altlinux", "name": "ALT Server", "codename": "Mendelevium", "pretty_name": "ALT Server 10.1 (Mendelevium)", "version": "10.1", "pretty_version": "10.1 (Mendelevium)", "best_version": "10.1", "major_version": "10", "minor_version": "1", } self._test_outcome(desired_outcome, "altlinux", "10") @pytest.mark.skipif(not IS_LINUX, reason="Irrelevant on non-linux") class TestOverall(DistroTestCase): """Test a LinuxDistribution object created with default arguments. The direct accessor functions on that object are tested (e.g. `id()`); they implement the precedence between the different sources of information. In addition, because the distro release file is searched when not specified, the information resulting from the distro release file is also tested. The LSB and os-release sources are not tested again, because their test is already done in TestLSBRelease and TestOSRelease, and their algorithm does not depend on whether or not the file is specified. TODO: This class should have testcases for all distros that are claimed to be reliably maintained w.r.t. to their ID (see `id()`). Testcases for the following distros are still missing: * `gentoo` - GenToo Linux * `ibm_powerkvm` - IBM PowerKVM * `parallels` - Parallels * `pidora` - Pidora (Fedora remix for Raspberry Pi) * `raspbian` - Raspbian * `scientific` - Scientific Linux * `xenserver` - XenServer """ def setup_method(self, test_method: FunctionType) -> None: super().setup_method(test_method) dist = test_method.__name__.split("_")[1] self._setup_for_distro(os.path.join(DISTROS_DIR, dist)) self.distro = distro.LinuxDistribution() def _test_outcome(self, outcome: Dict[str, str]) -> None: assert self.distro.id() == outcome.get("id", "") assert self.distro.name() == outcome.get("name", "") assert self.distro.name(pretty=True) == outcome.get("pretty_name", "") assert self.distro.version() == outcome.get("version", "") assert self.distro.version(pretty=True) == outcome.get("pretty_version", "") assert self.distro.version(best=True) == outcome.get("best_version", "") assert self.distro.like() == outcome.get("like", "") assert self.distro.codename() == outcome.get("codename", "") assert self.distro.major_version() == outcome.get("major_version", "") assert self.distro.minor_version() == outcome.get("minor_version", "") assert self.distro.build_number() == outcome.get("build_number", "") def _test_non_existing_release_file(self) -> None: # Test the info from the searched distro release file # does not have one. assert self.distro.distro_release_file == "" assert len(self.distro.distro_release_info()) == 0 def _test_release_file_info( self, filename: str, outcome: Dict[str, str] ) -> Dict[str, str]: # Test the info from the searched distro release file assert os.path.basename(self.distro.distro_release_file) == filename distro_info = self.distro.distro_release_info() for key, value in outcome.items(): assert distro_info[key] == value return distro_info def test_arch_release(self) -> None: desired_outcome = { "id": "arch", "name": "Arch Linux", "pretty_name": "Arch Linux", } self._test_outcome(desired_outcome) # Test the info from the searched distro release file # Does not have one; The empty /etc/arch-release file is not # considered a valid distro release file: self._test_non_existing_release_file() def test_aix72_release(self) -> None: desired_outcome = { "id": "aix", "name": "AIX", "pretty_name": "AIX 7.2.0.0", "version": "7.2.0.0", "pretty_version": "7.2.0.0", "best_version": "7.2.0.0", "major_version": "7", "minor_version": "2", "build_number": "0", } self._test_outcome(desired_outcome) def test_centos5_release(self) -> None: desired_outcome = { "id": "centos", "name": "CentOS", "pretty_name": "CentOS 5.11 (Final)", "version": "5.11", "pretty_version": "5.11 (Final)", "best_version": "5.11", "codename": "Final", "major_version": "5", "minor_version": "11", } self._test_outcome(desired_outcome) desired_info = { "id": "centos", "name": "CentOS", "version_id": "5.11", "codename": "Final", } self._test_release_file_info("centos-release", desired_info) def test_centos7_release(self) -> None: desired_outcome = { "id": "centos", "name": "CentOS Linux", "pretty_name": "CentOS Linux 7 (Core)", "version": "7", "pretty_version": "7 (Core)", "best_version": "7.1.1503", "like": "rhel fedora", "codename": "Core", "major_version": "7", } self._test_outcome(desired_outcome) desired_info = { "id": "centos", "name": "CentOS Linux", "version_id": "7.1.1503", "codename": "Core", } self._test_release_file_info("centos-release", desired_info) def test_coreos_release(self) -> None: desired_outcome = { "id": "coreos", "name": "CoreOS", "pretty_name": "CoreOS 899.15.0", "version": "899.15.0", "pretty_version": "899.15.0", "best_version": "899.15.0", "major_version": "899", "minor_version": "15", "build_number": "0", } self._test_outcome(desired_outcome) self._test_non_existing_release_file() def test_debian8_release(self) -> None: desired_outcome = { "id": "debian", "name": "Debian GNU/Linux", "pretty_name": "Debian GNU/Linux 8 (jessie)", "version": "8", "pretty_version": "8 (jessie)", "best_version": "8.2", "codename": "jessie", "major_version": "8", } self._test_outcome(desired_outcome) self._test_non_existing_release_file() def test_debian10_release(self) -> None: desired_outcome = { "id": "debian", "name": "Debian GNU/Linux", "pretty_name": "Debian GNU/Linux 10 (buster)", "version": "10", "pretty_version": "10 (buster)", "best_version": "10.11", "codename": "buster", "major_version": "10", } self._test_outcome(desired_outcome) self._test_non_existing_release_file() def test_debiantesting_release(self) -> None: desired_outcome = { "id": "debian", "name": "Debian GNU/Linux", "pretty_name": "Debian GNU/Linux bookworm/sid", "version": "bookworm/sid", "pretty_version": "bookworm/sid (bookworm)", "best_version": "bookworm/sid", "codename": "bookworm", "major_version": "", } self._test_outcome(desired_outcome) self._test_non_existing_release_file() def test_exherbo_release(self) -> None: desired_outcome = { "id": "exherbo", "name": "Exherbo", "pretty_name": "Exherbo Linux", } self._test_outcome(desired_outcome) def test_fedora19_release(self) -> None: desired_outcome = { "id": "fedora", "name": "Fedora", "pretty_name": "Fedora 19 (Schrödinger’s Cat)", "version": "19", "pretty_version": "19 (Schrödinger’s Cat)", "best_version": "19", "codename": "Schrödinger’s Cat", "major_version": "19", } self._test_outcome(desired_outcome) desired_info = { "id": "fedora", "name": "Fedora", "version_id": "19", "codename": "Schrödinger’s Cat", } self._test_release_file_info("fedora-release", desired_info) def test_fedora23_release(self) -> None: desired_outcome = { "id": "fedora", "name": "Fedora", "pretty_name": "Fedora 23 (Twenty Three)", "version": "23", "pretty_version": "23 (Twenty Three)", "best_version": "23", "codename": "Twenty Three", "major_version": "23", } self._test_outcome(desired_outcome) desired_info = { "id": "fedora", "name": "Fedora", "version_id": "23", "codename": "Twenty Three", } self._test_release_file_info("fedora-release", desired_info) def test_fedora30_release(self) -> None: desired_outcome = { "id": "fedora", "name": "Fedora", "pretty_name": "Fedora 30 (Thirty)", "version": "30", "pretty_version": "30", "best_version": "30", "codename": "", "major_version": "30", } self._test_outcome(desired_outcome) desired_info = { "id": "fedora", "name": "Fedora", "version_id": "30", "codename": "Thirty", } self._test_release_file_info("fedora-release", desired_info) def test_kvmibm1_release(self) -> None: desired_outcome = { "id": "kvmibm", "name": "KVM for IBM z Systems", "pretty_name": "KVM for IBM z Systems 1.1.1 (Z)", "version": "1.1.1", "pretty_version": "1.1.1 (Z)", "best_version": "1.1.1", "like": "rhel fedora", "codename": "Z", "major_version": "1", "minor_version": "1", "build_number": "1", } self._test_outcome(desired_outcome) desired_info = { "id": "base", "name": "KVM for IBM z Systems", "version_id": "1.1.1", "codename": "Z", } self._test_release_file_info("base-release", desired_info) def test_linuxmint17_release(self) -> None: desired_outcome = { "id": "ubuntu", "name": "Ubuntu", "pretty_name": "Ubuntu 14.04.3 LTS", "version": "14.04", "pretty_version": "14.04 (Trusty Tahr)", "best_version": "14.04.3", "like": "debian", "codename": "Trusty Tahr", "major_version": "14", "minor_version": "04", } self._test_outcome(desired_outcome) self._test_non_existing_release_file() def test_mageia5_release(self) -> None: desired_outcome = { "id": "mageia", "name": "Mageia", "pretty_name": "Mageia 5", "version": "5", "pretty_version": "5 (thornicroft)", "best_version": "5", "like": "mandriva fedora", # TODO: Codename differs between distro release and lsb_release. "codename": "thornicroft", "major_version": "5", } self._test_outcome(desired_outcome) desired_info = { "id": "mageia", "name": "Mageia", "version_id": "5", "codename": "Official", } self._test_release_file_info("mageia-release", desired_info) def test_manjaro1512_release(self) -> None: self._test_outcome( { "id": "manjaro", "name": "Manjaro Linux", "pretty_name": "Manjaro Linux", "version": "15.12", "pretty_version": "15.12 (Capella)", "best_version": "15.12", "major_version": "15", "minor_version": "12", "codename": "Capella", } ) self._test_release_file_info( "manjaro-release", {"id": "manjaro", "name": "Manjaro Linux"} ) def test_opensuse42_release(self) -> None: desired_outcome = { "id": "opensuse", "name": "openSUSE Leap", "pretty_name": "openSUSE Leap 42.1 (x86_64)", "version": "42.1", "pretty_version": "42.1 (x86_64)", "best_version": "42.1", "like": "suse", "codename": "x86_64", "major_version": "42", "minor_version": "1", } self._test_outcome(desired_outcome) desired_info = { "id": "SuSE", "name": "openSUSE", "version_id": "42.1", "codename": "x86_64", } self._test_release_file_info("SuSE-release", desired_info) def test_opensuse15_release(self) -> None: desired_outcome = { "id": "opensuse", "name": "openSUSE Leap", "pretty_name": "openSUSE Leap 15.2", "version": "15.2", "pretty_version": "15.2", "best_version": "15.2", "like": "suse opensuse", "major_version": "15", "minor_version": "2", } self._test_outcome(desired_outcome) def test_oracle7_release(self) -> None: desired_outcome = { "id": "oracle", "name": "Oracle Linux Server", "pretty_name": "Oracle Linux Server 7.5", "version": "7.5", "pretty_version": "7.5", "best_version": "7.5", "major_version": "7", "minor_version": "5", } self._test_outcome(desired_outcome) desired_info = { "id": "oracle", "name": "Oracle Linux Server", "version_id": "7.5", } distro_info = self._test_release_file_info("oracle-release", desired_info) assert "codename" not in distro_info def test_raspbian7_release(self) -> None: desired_outcome = { "id": "raspbian", "name": "Raspbian GNU/Linux", "pretty_name": "Raspbian GNU/Linux 7 (wheezy)", "version": "7", "pretty_version": "7 (wheezy)", "best_version": "7.1", "like": "debian", "codename": "wheezy", "major_version": "7", } self._test_outcome(desired_outcome) self._test_non_existing_release_file() def test_raspbian8_release(self) -> None: desired_outcome = { "id": "raspbian", "name": "Raspbian GNU/Linux", "pretty_name": "Raspbian GNU/Linux 8 (jessie)", "version": "8", "pretty_version": "8 (jessie)", "best_version": "8.0", "like": "debian", "codename": "jessie", "major_version": "8", } self._test_outcome(desired_outcome) self._test_non_existing_release_file() def test_rhel5_release(self) -> None: desired_outcome = { "id": "rhel", "name": "Red Hat Enterprise Linux Server", "pretty_name": "Red Hat Enterprise Linux Server 5.11 (Tikanga)", "version": "5.11", "pretty_version": "5.11 (Tikanga)", "best_version": "5.11", "codename": "Tikanga", "major_version": "5", "minor_version": "11", } self._test_outcome(desired_outcome) desired_info = { "id": "redhat", "name": "Red Hat Enterprise Linux Server", "version_id": "5.11", "codename": "Tikanga", } self._test_release_file_info("redhat-release", desired_info) def test_rhel6_release(self) -> None: desired_outcome = { "id": "rhel", "name": "Red Hat Enterprise Linux Server", "pretty_name": "Red Hat Enterprise Linux Server 6.5 (Santiago)", "version": "6.5", "pretty_version": "6.5 (Santiago)", "best_version": "6.5", "codename": "Santiago", "major_version": "6", "minor_version": "5", } self._test_outcome(desired_outcome) desired_info = { "id": "redhat", "name": "Red Hat Enterprise Linux Server", "version_id": "6.5", "codename": "Santiago", } self._test_release_file_info("redhat-release", desired_info) def test_rhel7_release(self) -> None: desired_outcome = { "id": "rhel", "name": "Red Hat Enterprise Linux Server", "pretty_name": "Red Hat Enterprise Linux Server 7.0 (Maipo)", "version": "7.0", "pretty_version": "7.0 (Maipo)", "best_version": "7.0", "like": "fedora", "codename": "Maipo", "major_version": "7", "minor_version": "0", } self._test_outcome(desired_outcome) desired_info = { "id": "redhat", "name": "Red Hat Enterprise Linux Server", "version_id": "7.0", "codename": "Maipo", } self._test_release_file_info("redhat-release", desired_info) def test_rocky_release(self) -> None: desired_outcome = { "id": "rocky", "name": "Rocky Linux", "pretty_name": "Rocky Linux 8.4 (Green Obsidian)", "version": "8.4", "pretty_version": "8.4 (Green Obsidian)", "best_version": "8.4", "like": "rhel centos fedora", "codename": "Green Obsidian", "major_version": "8", "minor_version": "4", } self._test_outcome(desired_outcome) desired_info = { "id": "centos", "name": "Rocky Linux", "version_id": "8.4", "codename": "Green Obsidian", } self._test_release_file_info("centos-release", desired_info) def test_slackware14_release(self) -> None: desired_outcome = { "id": "slackware", "name": "Slackware", "pretty_name": "Slackware 14.1", "version": "14.1", "pretty_version": "14.1", "best_version": "14.1", "major_version": "14", "minor_version": "1", } self._test_outcome(desired_outcome) desired_info = {"id": "slackware", "name": "Slackware", "version_id": "14.1"} distro_info = self._test_release_file_info("slackware-version", desired_info) assert "codename" not in distro_info def test_sles12_release(self) -> None: desired_outcome = { "id": "sles", "name": "SLES", "pretty_name": "SUSE Linux Enterprise Server 12 SP1", "version": "12.1", "pretty_version": "12.1 (n/a)", "best_version": "12.1", "codename": "n/a", "major_version": "12", "minor_version": "1", } self._test_outcome(desired_outcome) desired_info = { "id": "SuSE", "name": "SUSE Linux Enterprise Server", "version_id": "12", "codename": "s390x", } self._test_release_file_info("SuSE-release", desired_info) def test_ubuntu14_release(self) -> None: desired_outcome = { "id": "ubuntu", "name": "Ubuntu", "pretty_name": "Ubuntu 14.04.3 LTS", "version": "14.04", "pretty_version": "14.04 (Trusty Tahr)", "best_version": "14.04.3", "like": "debian", "codename": "Trusty Tahr", "major_version": "14", "minor_version": "04", } self._test_outcome(desired_outcome) # Test the info from the searched distro release file # Does not have one; /etc/debian_version is not considered a distro # release file: self._test_non_existing_release_file() def test_ubuntu16_release(self) -> None: desired_outcome = { "id": "ubuntu", "name": "Ubuntu", "pretty_name": "Ubuntu 16.04.1 LTS", "version": "16.04", "pretty_version": "16.04 (xenial)", "best_version": "16.04.1", "like": "debian", "codename": "xenial", "major_version": "16", "minor_version": "04", } self._test_outcome(desired_outcome) # Test the info from the searched distro release file # Does not have one; /etc/debian_version is not considered a distro # release file: self._test_non_existing_release_file() def test_amazon2016_release(self) -> None: desired_outcome = { "id": "amzn", "name": "Amazon Linux AMI", "pretty_name": "Amazon Linux AMI 2016.03", "version": "2016.03", "pretty_version": "2016.03", "best_version": "2016.03", "like": "rhel fedora", "major_version": "2016", "minor_version": "03", } self._test_outcome(desired_outcome) def test_amazon2014_release(self) -> None: # Amazon Linux 2014 only contains a system-release file. # distro doesn't currently handle it. self._test_outcome({}) def test_scientific6_release(self) -> None: desired_outcome = { "id": "rhel", "name": "Scientific Linux", "pretty_name": "Scientific Linux 6.4 (Carbon)", "version": "6.4", "pretty_version": "6.4 (Carbon)", "best_version": "6.4", "codename": "Carbon", "major_version": "6", "minor_version": "4", } self._test_outcome(desired_outcome) desired_info = { "id": "redhat", "name": "Scientific Linux", "version_id": "6.4", "codename": "Carbon", } self._test_release_file_info("redhat-release", desired_info) def test_scientific7_release(self) -> None: desired_outcome = { "id": "rhel", "name": "Scientific Linux", "pretty_name": "Scientific Linux 7.2 (Nitrogen)", "version": "7.2", "pretty_version": "7.2 (Nitrogen)", "best_version": "7.2", "like": "fedora", "codename": "Nitrogen", "major_version": "7", "minor_version": "2", } self._test_outcome(desired_outcome) desired_info = { "id": "redhat", "name": "Scientific Linux", "version_id": "7.2", "codename": "Nitrogen", } self._test_release_file_info("redhat-release", desired_info) def test_gentoo_release(self) -> None: desired_outcome = { "id": "gentoo", "name": "Gentoo", "pretty_name": "Gentoo/Linux", "version": "2.2", "pretty_version": "2.2", "best_version": "2.2", "major_version": "2", "minor_version": "2", } self._test_outcome(desired_outcome) desired_info = { "id": "gentoo", "name": "Gentoo Base System", "version_id": "2.2", } self._test_release_file_info("gentoo-release", desired_info) def test_openelec6_release(self) -> None: desired_outcome = { "id": "openelec", "name": "OpenELEC", "pretty_name": "OpenELEC (official) - Version: 6.0.3", "version": "6.0", "pretty_version": "6.0", "best_version": "6.0.3", "major_version": "6", "minor_version": "0", } self._test_outcome(desired_outcome) def test_mandriva2011_release(self) -> None: desired_outcome = { "id": "mandrivalinux", "name": "MandrivaLinux", "pretty_name": "Mandriva Linux 2011.0", "version": "2011.0", "pretty_version": "2011.0 (turtle)", "best_version": "2011.0", "major_version": "2011", "minor_version": "0", "codename": "turtle", } self._test_outcome(desired_outcome) desired_info = { "id": "mandrake", "name": "Mandriva Linux", "version_id": "2011.0", } self._test_release_file_info("mandrake-release", desired_info) def test_cloudlinux5_release(self) -> None: # Uses redhat-release only to get information. # The id of 'rhel' can only be fixed with issue #109. desired_outcome = { "id": "cloudlinux", "codename": "Vladislav Volkov", "name": "CloudLinux Server", "pretty_name": "CloudLinux Server 5.11 (Vladislav Volkov)", "version": "5.11", "pretty_version": "5.11 (Vladislav Volkov)", "best_version": "5.11", "major_version": "5", "minor_version": "11", } self._test_outcome(desired_outcome) def test_cloudlinux6_release(self) -> None: # Same as above, only has redhat-release. desired_outcome = { "id": "cloudlinux", "codename": "Oleg Makarov", "name": "CloudLinux Server", "pretty_name": "CloudLinux Server 6.8 (Oleg Makarov)", "version": "6.8", "pretty_version": "6.8 (Oleg Makarov)", "best_version": "6.8", "major_version": "6", "minor_version": "8", } self._test_outcome(desired_outcome) def test_cloudlinux7_release(self) -> None: desired_outcome = { "id": "cloudlinux", "codename": "Yury Malyshev", "name": "CloudLinux", "pretty_name": "CloudLinux 7.3 (Yury Malyshev)", "like": "rhel fedora centos", "version": "7.3", "pretty_version": "7.3 (Yury Malyshev)", "best_version": "7.3", "major_version": "7", "minor_version": "3", } self._test_outcome(desired_outcome) def test_altlinux10_release(self) -> None: desired_outcome = { "id": "altlinux", "name": "ALT Server", "codename": "Mendelevium", "pretty_name": "ALT Server 10.1 (Mendelevium)", "version": "10.1", "pretty_version": "10.1 (Mendelevium)", "best_version": "10.1", "major_version": "10", "minor_version": "1", } self._test_outcome(desired_outcome) desired_info = { "id": "altlinux", "name": "ALT Server", "version_id": "10.1", "codename": "Mendelevium", } self._test_release_file_info("altlinux-release", desired_info) def _bad_os_listdir(path: str = ".") -> NoReturn: """This function is used by TestOverallWithEtcNotReadable to simulate a folder that cannot be called with os.listdir() but files are still readable. Forces distro to guess which *-release files are available.""" raise OSError() @pytest.mark.skipif(not IS_LINUX, reason="Irrelevant on non-linux") class TestOverallWithEtcNotReadable(TestOverall): def setup_method(self, test_method: FunctionType) -> None: self._old_listdir = os.listdir # Incompatible types in assignment (expression has type # "Callable[[str], NoReturn]", variable has type overloaded function) os.listdir = _bad_os_listdir # type: ignore[assignment] super().setup_method(test_method) def teardown_method(self, test_method: FunctionType) -> None: super().teardown_method(test_method) if os.listdir is _bad_os_listdir: os.listdir = self._old_listdir @pytest.mark.skipif(not IS_LINUX, reason="Irrelevant on non-linux") class TestGetAttr(DistroTestCase): """Test the consistency between the results of `{source}_release_attr()` and `{source}_release_info()` for all distros in `DISTROS`. """ def _test_attr(self, info_method: str, attr_method: str) -> None: for dist in DISTROS: self._setup_for_distro(os.path.join(DISTROS_DIR, dist)) _distro = distro.LinuxDistribution() info = getattr(_distro, info_method)() for key in info.keys(): try: assert info[key] == getattr(_distro, attr_method)(key) except AssertionError: print(f"distro: {dist}, key: {key}") def test_os_release_attr(self) -> None: self._test_attr("os_release_info", "os_release_attr") def test_lsb_release_attr(self) -> None: self._test_attr("lsb_release_info", "lsb_release_attr") def test_distro_release_attr(self) -> None: self._test_attr("distro_release_info", "distro_release_attr") @pytest.mark.skipif(not IS_LINUX, reason="Irrelevant on non-linux") class TestInfo(DistroTestCase): def setup_method(self, test_method: FunctionType) -> None: super().setup_method(test_method) self.ubuntu14_os_release = os.path.join( DISTROS_DIR, "ubuntu14", "etc", "os-release" ) self.fedora30_os_release = os.path.join( DISTROS_DIR, "fedora30", "etc", "os-release" ) def test_info(self) -> None: _distro = distro.LinuxDistribution( include_lsb=False, os_release_file=self.ubuntu14_os_release, distro_release_file="path-to-non-existing-file", ) desired_info = { "id": "ubuntu", "version": "14.04", "like": "debian", "version_parts": {"major": "14", "minor": "04", "build_number": ""}, "codename": "Trusty Tahr", } info = _distro.info() assert info == desired_info desired_info_diff: Dict[str, Any] = {"version": "14.04 (Trusty Tahr)"} desired_info.update(desired_info_diff) info = _distro.info(pretty=True) assert info == desired_info desired_info_diff = { "version": "14.04.3", "version_parts": {"major": "14", "minor": "04", "build_number": "3"}, } desired_info.update(desired_info_diff) info = _distro.info(best=True) assert info == desired_info desired_info_diff = {"version": "14.04.3 (Trusty Tahr)"} desired_info.update(desired_info_diff) info = _distro.info(pretty=True, best=True) assert info == desired_info def test_none(self) -> None: def _test_none(info: distro.InfoDict) -> None: assert info["id"] == "" assert info["version"] == "" assert info["like"] == "" assert info["version_parts"]["major"] == "" assert info["version_parts"]["minor"] == "" assert info["version_parts"]["build_number"] == "" assert info["codename"] == "" _distro = distro.LinuxDistribution( include_lsb=False, os_release_file="path-to-non-existing-file", distro_release_file="path-to-non-existing-file", ) info = _distro.info() _test_none(info) info = _distro.info(best=True) _test_none(info) info = _distro.info(pretty=True) _test_none(info) info = _distro.info(pretty=True, best=True) _test_none(info) def test_linux_distribution(self) -> None: _distro = distro.LinuxDistribution( include_lsb=False, os_release_file=self.ubuntu14_os_release ) i = _distro.linux_distribution() assert i == ("Ubuntu", "14.04", "Trusty Tahr") _distro = distro.LinuxDistribution( include_lsb=False, os_release_file=self.fedora30_os_release ) i = _distro.linux_distribution() assert i == ("Fedora", "30", "Thirty") def test_linux_distribution_full_false(self) -> None: _distro = distro.LinuxDistribution( include_lsb=False, os_release_file=self.ubuntu14_os_release ) i = _distro.linux_distribution(full_distribution_name=False) assert i == ("ubuntu", "14.04", "Trusty Tahr") def test_all(self) -> None: """Test info() by comparing its results with the results of specific consolidated accessor functions. """ def _test_all( info: distro.InfoDict, best: bool = False, pretty: bool = False ) -> None: assert info["id"] == _distro.id() assert info["version"] == _distro.version(pretty=pretty, best=best) assert info["version_parts"]["major"] == _distro.major_version(best=best) assert info["version_parts"]["minor"] == _distro.minor_version(best=best) assert info["version_parts"]["build_number"] == _distro.build_number( best=best ) assert info["like"] == _distro.like() assert info["codename"] == _distro.codename() assert len(info["version_parts"]) == 3 assert len(info) == 5 for dist in DISTROS: self._setup_for_distro(os.path.join(DISTROS_DIR, dist)) _distro = distro.LinuxDistribution() info = _distro.info() _test_all(info) info = _distro.info(best=True) _test_all(info, best=True) info = _distro.info(pretty=True) _test_all(info, pretty=True) info = _distro.info(pretty=True, best=True) _test_all(info, pretty=True, best=True) @pytest.mark.skipif(not IS_LINUX, reason="Irrelevant on non-linux") class TestOSReleaseParsing: """Test the parsing of os-release files.""" def setup_method(self, test_method: FunctionType) -> None: self.distro = distro.LinuxDistribution(include_lsb=False) def _get_props(self, input: str) -> Dict[str, str]: return self.distro._parse_os_release_content(io.StringIO(input)) def _test_zero_length_props(self, input: str) -> None: props = self._get_props(input) assert len(props) == 0 def _test_empty_value(self, input: str) -> None: props = self._get_props(input) assert props.get("key", None) == "" def _test_parsed_value(self, input: str) -> None: props = self._get_props(input) assert props.get("key", None) == "value" def test_kv_01_empty_file(self) -> None: self._test_zero_length_props("") def test_kv_02_empty_line(self) -> None: self._test_zero_length_props("\n") def test_kv_03_empty_line_with_crlf(self) -> None: self._test_zero_length_props("\r\n") def test_kv_04_empty_line_with_just_cr(self) -> None: self._test_zero_length_props("\r") def test_kv_05_comment(self) -> None: self._test_zero_length_props("# KEY=value\n") def test_kv_06_empty_value(self) -> None: self._test_empty_value("KEY=\n") def test_kv_07_empty_value_single_quoted(self) -> None: self._test_empty_value("KEY=''\n") def test_kv_08_empty_value_double_quoted(self) -> None: self._test_empty_value('KEY=""\n') def test_kv_09_word(self) -> None: self._test_parsed_value("KEY=value\n") def test_kv_10_word_no_newline(self) -> None: self._test_parsed_value("KEY=value") def test_kv_11_word_with_crlf(self) -> None: self._test_parsed_value("KEY=value\r\n") def test_kv_12_word_with_just_cr(self) -> None: self._test_parsed_value("KEY=value\r") def test_kv_13_word_with_multi_blanks(self) -> None: self._test_empty_value("KEY= cmd \n") # Note: Without quotes, this assigns the empty string, and 'cmd' is # a separate token that is being ignored (it would be a command # in the shell). def test_kv_14_unquoted_words(self) -> None: self._test_parsed_value("KEY=value cmd\n") def test_kv_15_double_quoted_words(self) -> None: props = self._get_props('KEY="a simple value" cmd\n') assert props.get("key", None) == "a simple value" def test_kv_16_double_quoted_words_with_multi_blanks(self) -> None: props = self._get_props('KEY=" a simple value "\n') assert props.get("key", None) == " a simple value " def test_kv_17_double_quoted_word_with_single_quote(self) -> None: props = self._get_props('KEY="it\'s value"\n') assert props.get("key", None) == "it's value" def test_kv_18_double_quoted_word_with_double_quote(self) -> None: props = self._get_props('KEY="a \\"bold\\" move"\n') assert props.get("key", None) == 'a "bold" move' def test_kv_19_single_quoted_words(self) -> None: props = self._get_props("KEY='a simple value'\n") assert props.get("key", None) == "a simple value" def test_kv_20_single_quoted_words_with_multi_blanks(self) -> None: props = self._get_props("KEY=' a simple value '\n") assert props.get("key", None) == " a simple value " def test_kv_21_single_quoted_word_with_double_quote(self) -> None: props = self._get_props("KEY='a \"bold\" move'\n") assert props.get("key", None) == 'a "bold" move' def test_kv_22_quoted_unicode_wordchar(self) -> None: # "wordchar" means it is in the shlex.wordchars variable. props = self._get_props('KEY="wordchar: \u00CA (E accent grave)"\n') assert props.get("key", None) == "wordchar: \u00CA (E accent grave)" def test_kv_23_quoted_unicode_non_wordchar(self) -> None: # "non-wordchar" means it is not in the shlex.wordchars variable. props = self._get_props( 'KEY="non-wordchar: \u00A1 (inverted exclamation mark)"\n' ) assert ( props.get("key", None) == "non-wordchar: \u00A1 (inverted exclamation mark)" ) def test_kv_24_double_quoted_entire_single_quoted_word(self) -> None: props = self._get_props("KEY=\"'value'\"\n") assert props.get("key", None) == "'value'" def test_kv_25_single_quoted_entire_double_quoted_word(self) -> None: props = self._get_props("KEY='\"value\"'\n") assert props.get("key", None) == '"value"' def test_kv_26_double_quoted_multiline(self) -> None: props = self.distro._parse_os_release_content( io.StringIO('KEY="a multi\n' 'line value"\n') ) assert props.get("key", None) == "a multi\nline value" # TODO: Find out why the result is not 'a multi line value' def test_kv_27_double_quoted_multiline_2(self) -> None: props = self._get_props("KEY=' a simple value '\n") props = self.distro._parse_os_release_content( io.StringIO('KEY="a multi\n' 'line=value"\n') ) assert props.get("key", None) == "a multi\nline=value" # TODO: Find out why the result is not 'a multi line=value' def test_kv_28_double_quoted_word_with_equal(self) -> None: props = self._get_props('KEY="var=value"\n') assert props.get("key", None) == "var=value" def test_kv_29_single_quoted_word_with_equal(self) -> None: props = self._get_props("KEY='var=value'\n") assert props.get("key", None) == "var=value" def test_kx_01(self) -> None: props = self.distro._parse_os_release_content( io.StringIO("KEY1=value1\n" 'KEY2="value 2"\n') ) assert props.get("key1", None) == "value1" assert props.get("key2", None) == "value 2" def test_kx_02(self) -> None: props = self.distro._parse_os_release_content( io.StringIO("# KEY1=value1\n" 'KEY2="value 2"\n') ) assert props.get("key1", None) is None assert props.get("key2", None) == "value 2" @pytest.mark.skipif(not IS_LINUX, reason="Irrelevant on non-linux") class TestGlobal: """Test the global module-level functions, and default values of their arguments. """ def setup_method(self, test_method: FunctionType) -> None: pass def test_global(self) -> None: # Because the module-level functions use the module-global # LinuxDistribution instance, it would influence the tested # code too much if we mocked that in order to use the distro # specific release files. Instead, we let the functions use # the release files of the distro this test runs on, and # compare the result of the global functions with the result # of the methods on the global LinuxDistribution object. def _test_consistency( function: str, kwargs: Optional[Dict[str, Any]] = None ) -> None: kwargs = kwargs or {} method_result = getattr(MODULE_DISTRO, function)(**kwargs) function_result = getattr(distro, function)(**kwargs) assert method_result == function_result kwargs = {"full_distribution_name": True} with pytest.deprecated_call(): _test_consistency("linux_distribution", kwargs) kwargs = {"full_distribution_name": False} with pytest.deprecated_call(): _test_consistency("linux_distribution", kwargs) kwargs = {"pretty": False} _test_consistency("name", kwargs) _test_consistency("version", kwargs) _test_consistency("info", kwargs) kwargs = {"pretty": True} _test_consistency("name", kwargs) _test_consistency("version", kwargs) _test_consistency("info", kwargs) kwargs = {"best": False} _test_consistency("version", kwargs) _test_consistency("version_parts", kwargs) _test_consistency("major_version", kwargs) _test_consistency("minor_version", kwargs) _test_consistency("build_number", kwargs) _test_consistency("info", kwargs) kwargs = {"best": True} _test_consistency("version", kwargs) _test_consistency("version_parts", kwargs) _test_consistency("major_version", kwargs) _test_consistency("minor_version", kwargs) _test_consistency("build_number", kwargs) _test_consistency("info", kwargs) _test_consistency("id") _test_consistency("like") _test_consistency("codename") _test_consistency("info") _test_consistency("os_release_info") _test_consistency("lsb_release_info") _test_consistency("distro_release_info") _test_consistency("uname_info") os_release_keys = [ "name", "version", "id", "id_like", "pretty_name", "version_id", "codename", ] for key in os_release_keys: _test_consistency("os_release_attr", {"attribute": key}) lsb_release_keys = ["distributor_id", "description", "release", "codename"] for key in lsb_release_keys: _test_consistency("lsb_release_attr", {"attribute": key}) distro_release_keys = ["id", "name", "version_id", "codename"] for key in distro_release_keys: _test_consistency("distro_release_attr", {"attribute": key}) uname_keys = ["id", "name", "release"] for key in uname_keys: _test_consistency("uname_attr", {"attribute": key}) @pytest.mark.skipif(not IS_LINUX, reason="Irrelevant on non-linux") class TestRepr: """Test the __repr__() method.""" def test_repr(self) -> None: # We test that the class name and the names of all instance attributes # show up in the repr() string. repr_str = repr(distro._distro) assert "LinuxDistribution" in repr_str for attr in MODULE_DISTRO.__dict__.keys(): if attr in ("root_dir", "etc_dir", "usr_lib_dir", "_debian_version"): continue assert f"{attr}=" in repr_str distro-1.9.0/tox.ini000066400000000000000000000016371454137533700143630ustar00rootroot00000000000000# Copyright 2015-2021 Nir Cohen # # 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 # # http://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. [tox] minversion = 1.9 envlist = lint, py{36,37,38,39,310,311,312,py3} isolated_build = true skip_missing_interpreters = true [testenv] deps = pytest pytest-cov commands = pytest --cov-report term-missing --cov distro {posargs} [testenv:lint] deps = pre-commit commands = pre-commit run --all-files --show-diff-on-failure skip_install = true