├── .coveragerc ├── pytest.ini ├── setup.py ├── .github └── workflows │ └── tests.yml ├── README.md ├── test_luddite.py ├── LICENSE └── luddite.py /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | branch = True 3 | 4 | [report] 5 | exclude_lines = 6 | if __name__ == "__main__": 7 | -------------------------------------------------------------------------------- /pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | addopts = 3 | --verbose 4 | --cov=luddite --cov-report=html --cov-report=term --no-cov-on-fail 5 | --ignore=setup.py 6 | --disable-socket 7 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | setup( 4 | name="luddite", 5 | version="1.0.4", 6 | author="Wim Glenn", 7 | author_email="hey@wimglenn.com", 8 | url="https://github.com/jumptrading/luddite", 9 | py_modules=["luddite"], 10 | description="Checks for out-of-date package versions", 11 | long_description=open("README.md").read(), 12 | classifiers=[ 13 | "Programming Language :: Python :: 2", 14 | "Programming Language :: Python :: 3", 15 | "Intended Audience :: Developers", 16 | "Topic :: Software Development :: Libraries", 17 | "Topic :: Utilities", 18 | ], 19 | entry_points={"console_scripts": ["luddite=luddite:main"]}, 20 | install_requires=[ 21 | "packaging", 22 | 'colorama; platform_system == "Windows"', 23 | 'futures; python_version < "3.2"', 24 | ], 25 | extras_require={ 26 | # https://hynek.me/articles/conditional-python-dependencies/ 27 | "dev": [ 28 | "pytest >= 3.6.3", 29 | "pytest-cov", 30 | "pytest-mock", 31 | "pytest-socket", 32 | ], 33 | }, 34 | options={"bdist_wheel": {"universal": True}}, 35 | ) 36 | -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: tests 2 | 3 | on: 4 | push: 5 | branches: [master] 6 | pull_request: 7 | branches: [master] 8 | workflow_dispatch: 9 | 10 | jobs: 11 | tests-3x: 12 | name: Python ${{ matrix.py-version }} 13 | runs-on: ubuntu-latest 14 | 15 | strategy: 16 | matrix: 17 | py-version: 18 | - "3.8" 19 | - "3.9" 20 | - "3.10" 21 | - "3.11" 22 | - "3.12" 23 | - "3.13" 24 | 25 | steps: 26 | - uses: actions/checkout@v4 27 | - uses: actions/setup-python@v5 28 | with: 29 | python-version: ${{ matrix.py-version }} 30 | - name: Install dependencies 31 | run: pip install -e .[dev] 32 | - name: Run tests for ${{ matrix.py-version }} 33 | run: pytest 34 | - name: Upload coverage to Codecov 35 | uses: codecov/codecov-action@v5 36 | 37 | tests-27: 38 | name: Python 2.7 on ubuntu-20.04 39 | runs-on: ubuntu-20.04 40 | container: 41 | image: python:2.7-buster 42 | 43 | steps: 44 | - uses: actions/checkout@v4 45 | - name: Install dependencies 46 | run: pip install -e .[dev] 47 | - name: Run tests for 2.7 48 | run: pytest 49 | - name: Upload coverage to Codecov 50 | uses: codecov/codecov-action@v5 51 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # luddite 2 | 3 | [![actions](https://github.com/jumptrading/luddite/actions/workflows/tests.yml/badge.svg)](https://github.com/jumptrading/luddite/actions/workflows/tests.yml/) 4 | [![codecov](https://codecov.io/gh/jumptrading/luddite/branch/master/graph/badge.svg)](https://codecov.io/gh/jumptrading/luddite) 5 | [![pypi](https://img.shields.io/pypi/v/luddite.svg)](https://pypi.org/project/luddite/) 6 | ![pyversions](https://img.shields.io/pypi/pyversions/luddite.svg) 7 | 8 | `luddite` checks if pinned versions in your `requirements.txt` file have 9 | newer versions in the package index. It's great to be near the cutting 10 | edge, but not so close that you get cut! This tool will help you keep 11 | things up to date manually. 12 | 13 | There are [many ways to specify requirements][1], but luddite's only 14 | interested in one: we're looking for `package==version` pins. Parsing 15 | won't break on lines that aren't fitting this format, but you'll have 16 | to check them manually. 17 | 18 | `luddite` works on both Python 2 and Python 3. 19 | 20 | ### Installation 21 | 22 | ```bash 23 | pip install luddite 24 | ``` 25 | 26 | ### Usage 27 | 28 | ```bash 29 | luddite /path/to/requirements.txt 30 | ``` 31 | 32 | If you are in the same directory as the `requirements.txt` file, you can 33 | just type `luddite`. 34 | 35 | ### Example output 36 | 37 | ![image](https://user-images.githubusercontent.com/6615374/43939075-feec4530-9c2c-11e8-9770-6f7f762c72e4.png) 38 | 39 | [1]: https://pip.pypa.io/en/stable/reference/requirements-file-format/ 40 | -------------------------------------------------------------------------------- /test_luddite.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | from __future__ import unicode_literals 3 | 4 | import json 5 | import sys 6 | from subprocess import CalledProcessError 7 | 8 | import pytest 9 | 10 | import luddite 11 | 12 | 13 | def test_version_out_of_date(mocker): 14 | line = luddite.RequirementsLine("crappy==1.2.1") 15 | worker = mocker.Mock(return_value=("1.2.1", "1.2.3")) 16 | assert line.process(worker) == "fail" 17 | 18 | 19 | def test_version_up_to_date(mocker): 20 | line = luddite.RequirementsLine("happy==1.2.3") 21 | worker = mocker.Mock(return_value=("1.2.1", "1.2.3")) 22 | assert line.process(worker) == "pass" 23 | 24 | 25 | def test_version_nearly_out_of_date(mocker): 26 | line = luddite.RequirementsLine("prerelease==0.9") 27 | worker = mocker.Mock(return_value=("0.9", "1.0a1")) 28 | assert line.process(worker) == "warn" 29 | 30 | 31 | def test_version_missing_from_index(mocker): 32 | line = luddite.RequirementsLine("where==1.2") 33 | worker = mocker.Mock(return_value=("1.1", "1.3")) 34 | assert line.process(worker) == "gone" 35 | 36 | 37 | def test_empty_line(mocker): 38 | line = luddite.RequirementsLine("") 39 | worker = mocker.Mock(side_effect=Exception) 40 | assert line.process(worker) == "noop" 41 | 42 | 43 | def test_comment_line(mocker): 44 | line = luddite.RequirementsLine("# py==1.2") 45 | worker = mocker.Mock(side_effect=Exception) 46 | assert line.process(worker) == "noop" 47 | 48 | 49 | def test_index_line(mocker): 50 | line = luddite.RequirementsLine("--index-url https://pypi.org/simple") 51 | worker = mocker.Mock(side_effect=Exception) 52 | assert line.process(worker) == "noop" 53 | 54 | 55 | def test_req_line_with_inline_comment(mocker): 56 | line = luddite.RequirementsLine("johnnydep==0.3 # what a cool app!") 57 | worker = mocker.Mock(return_value=("0.3",)) 58 | assert line.process(worker) == "pass" 59 | 60 | 61 | def test_extra_whitespace_ok(mocker): 62 | line = luddite.RequirementsLine(" johnnydep == 0.3 \n") 63 | worker = mocker.Mock(return_value=("0.3",)) 64 | assert line.process(worker) == "pass" 65 | 66 | 67 | def test_line_not_proper_req(mocker): 68 | line = luddite.RequirementsLine("what the fuck") 69 | worker = mocker.Mock(side_effect=Exception) 70 | assert line.process(worker) == "skip" 71 | 72 | 73 | def test_index_lookup_failed(mocker): 74 | line = luddite.RequirementsLine("notexist==1.0") 75 | worker = mocker.Mock(side_effect=Exception) 76 | assert line.process(worker) == "oops" 77 | 78 | 79 | def test_package_unpinned(mocker): 80 | line = luddite.RequirementsLine("dist>=1.0") 81 | worker = mocker.Mock(side_effect=Exception) 82 | assert line.process(worker) == "free" 83 | 84 | 85 | def test_multiple_constraints(mocker): 86 | line = luddite.RequirementsLine("dist>=1.5,<2.0") 87 | worker = mocker.Mock(side_effect=Exception) 88 | assert line.process(worker) == "free" 89 | 90 | 91 | def test_parse_reqs_file(tmpdir): 92 | reqs = tmpdir.join("reqs.txt") 93 | reqs.write("abc==1.0\ndef==2.0") 94 | file = luddite.RequirementsFile(reqs) 95 | assert file.index is None 96 | assert [line.text for line in file.lines] == ["abc==1.0\n", "def==2.0"] 97 | 98 | 99 | def test_parse_reqs_file_with_index(tmpdir): 100 | reqs = tmpdir.join("reqs.txt") 101 | reqs.write("--index http://myindex\nabc==1.0\ndef==2.0") 102 | file = luddite.RequirementsFile(reqs) 103 | assert file.index == "http://myindex" 104 | 105 | 106 | def test_parse_reqs_file_with_two_indices(tmpdir): 107 | reqs = tmpdir.join("reqs.txt") 108 | reqs.write( 109 | "-i http://myindex\n" 110 | "--index-url=http://anotherindexwtf\n" 111 | "abc==1.0\n" 112 | "def==2.0" 113 | ) 114 | file = luddite.RequirementsFile(reqs) 115 | with pytest.raises(luddite.MultipleIndicesError): 116 | file.index 117 | 118 | 119 | def test_cprint(mocker, capsys): 120 | mocker.patch("luddite.sys.stdout.isatty", return_value=True) 121 | luddite.cprint("submarine", color="yellow") 122 | assert capsys.readouterr().out == "\x1b[33msubmarine\x1b[0m\n" 123 | 124 | 125 | def test_get_charset(mocker): 126 | headers = mocker.MagicMock() 127 | headers.get_content_charset.return_value = "test" 128 | assert luddite.get_charset(headers) == "test" 129 | 130 | 131 | @pytest.mark.skipif(sys.version_info >= (3,), reason="Python 2 only") 132 | def test_get_charset_in_header_directly(mocker): 133 | headers = mocker.MagicMock() 134 | headers.get_content_charset.side_effect = AttributeError 135 | headers.getparam.return_value = "test" 136 | assert luddite.get_charset(headers) == "test" 137 | 138 | 139 | @pytest.mark.skipif(sys.version_info >= (3,), reason="Python 2 only") 140 | def test_get_charset_in_content_type(mocker): 141 | headers = mocker.MagicMock() 142 | headers.get_content_charset.side_effect = AttributeError 143 | headers.getparam.return_value = None 144 | headers.getheader.return_value = "application/json; charset=test" 145 | assert luddite.get_charset(headers) == "test" 146 | 147 | 148 | def test_json_get_fails(mocker): 149 | mock_response = mocker.MagicMock() 150 | mock_response.code = 500 151 | mock_response.read.return_value = b"boom" 152 | mocker.patch("luddite.urlopen", return_value=mock_response) 153 | with pytest.raises(luddite.LudditeError, match="Unexpected response code 500") as cm: 154 | luddite.json_get("http://example.org") 155 | assert cm.value.response_data == b"boom" 156 | 157 | 158 | def test_autodetect_index_url(mocker, tmpdir): 159 | reqs = tmpdir.join("requirements.txt") 160 | reqs.write("whatever") 161 | mocker.patch("luddite.subprocess.check_output", return_value=b"https://test-index/") 162 | mocker.patch("luddite.guess_index_type", return_value="pypi") 163 | lud = luddite.Luddite(reqs) 164 | assert lud.index == "https://test-index/" 165 | assert lud.get_versions is luddite.get_versions_pypi 166 | 167 | 168 | def test_autodetect_index_url_failed(mocker, tmpdir, monkeypatch): 169 | monkeypatch.delenv("PIP_INDEX_URL", raising=False) 170 | monkeypatch.delenv("LUDDITE_DEFAULT_INDEX", raising=False) 171 | reqs = tmpdir.join("requirements.txt") 172 | reqs.write("whatever") 173 | mocker.patch("luddite.subprocess.check_output", side_effect=CalledProcessError(1, "wtf")) 174 | mocker.patch("luddite.guess_index_type", return_value="devpi") 175 | lud = luddite.Luddite(reqs) 176 | assert lud.index == luddite.DEFAULT_INDEX == "https://pypi.org/pypi/" 177 | assert lud.get_versions is luddite.get_versions_devpi 178 | 179 | 180 | def test_guess_index_type_pypi(mocker): 181 | mock_response = mocker.MagicMock() 182 | mock_response.code = 200 183 | mock_response.headers = {} 184 | mocker.patch("luddite.urlopen", return_value=mock_response) 185 | assert luddite.guess_index_type("http://test-index/") == "pypi" 186 | 187 | 188 | def test_guess_index_type_devpi(mocker): 189 | mock_response = mocker.MagicMock() 190 | mock_response.code = 200 191 | mock_response.headers = { 192 | "Content-type": "awesomesauce", 193 | "X-Devpi-Server-Version": "4.0.0\r\n", 194 | } 195 | mocker.patch("luddite.urlopen", return_value=mock_response) 196 | assert luddite.guess_index_type("http://test-index/") == "devpi" 197 | 198 | 199 | def test_guess_index_fails(mocker): 200 | mock_response = mocker.MagicMock() 201 | mock_response.code = 403 202 | mocker.patch("luddite.urlopen", return_value=mock_response) 203 | with pytest.raises(luddite.LudditeError): 204 | luddite.guess_index_type("http://test-index/") 205 | 206 | 207 | def test_get_version_devpi(mocker): 208 | mock_response = mocker.MagicMock() 209 | mock_response.code = 200 210 | mock_response.read.return_value = b'{"result": {"0.1": null, "0.2": null}}' 211 | mocker.patch("luddite.urlopen", return_value=mock_response) 212 | mocker.patch("luddite.get_charset", return_value="utf-8") 213 | v = luddite.get_version_devpi("dist", "http://myindex/+simple/") 214 | assert v == "0.2" 215 | 216 | 217 | def test_get_version_pypi(mocker): 218 | mock_response = mocker.MagicMock() 219 | mock_response.code = 200 220 | mock_response.read.return_value = b'{"info": {"version": "0.3"}}' 221 | mocker.patch("luddite.urlopen", return_value=mock_response) 222 | mocker.patch("luddite.get_charset", return_value="utf-8") 223 | v = luddite.get_version_pypi("dist", "http://myindex/+simple/") 224 | assert v == "0.3" 225 | 226 | 227 | def test_integration(tmpdir, capsys, mocker, monkeypatch): 228 | mock_response = mocker.MagicMock() 229 | mock_response.code = 200 230 | mock_response.headers.get_content_charset.return_value = "utf-8" 231 | releases = { 232 | "releases": { 233 | "1.0": [{"yanked": False}], 234 | "1.1": [{"yanked": False}], 235 | "1.4": [{"yanked": False}], 236 | } 237 | } 238 | mock_response.read.return_value = json.dumps(releases).encode() 239 | mocker.patch("luddite.urlopen", return_value=mock_response) 240 | mocker.patch("sys.argv", "luddite -i http://index-from-cmdline".split()) 241 | 242 | tmpdir.join("requirements.txt").write( 243 | """ 244 | --index-url http://index-from-file 245 | 246 | # dist0==1.0 247 | dist1==1.1 248 | dist2==1.2 # some comment 249 | 250 | dist3 251 | 252 | what the feck 253 | 254 | dist4==1.4 255 | distextra[x,y]==1.2.3 256 | """ 257 | ) 258 | 259 | monkeypatch.chdir(tmpdir) 260 | luddite.main() 261 | 262 | out, err = capsys.readouterr() 263 | assert err == "" 264 | assert ( 265 | out 266 | == """ using index: http://index-from-cmdline 267 | ---requirements.txt------------------------------------------------------------- 268 | 269 | --index-url http://index-from-file 270 | 271 | # dist0==1.0 272 | dist1==1.1 ✖ dist1 1.1 (index has 1.4) 273 | dist2==1.2 # some comment ! dist2 1.2 is not in the index (from versions: 1.0, 1.1, 1.4) 274 | 275 | dist3 ! dist3 appears unpinned? 276 | 277 | what the feck ? skipped a line: what the feck 278 | 279 | dist4==1.4 ✔ dist4 is up to date @ 1.4 280 | distextra[x,y]==1.2.3 ! distextra 1.2.3 is not in the index (from versions: 1.0, 1.1, 1.4) 281 | """ 282 | ) 283 | 284 | 285 | def test_yanked_versions_skipped(mocker): 286 | mock_response = mocker.MagicMock() 287 | mock_response.code = 200 288 | releases = { 289 | "releases": { 290 | "1.1": [{}], 291 | "1.4": [{"yanked": False}], 292 | "1.3": [{"yanked": True}], 293 | "1.2": [{"yanked": False}], 294 | } 295 | } 296 | mock_response.read.return_value = json.dumps(releases).encode() 297 | mocker.patch("luddite.urlopen", return_value=mock_response) 298 | mocker.patch("luddite.get_charset", return_value="utf-8") 299 | vs = luddite.get_versions_pypi("dist", "http://myindex/+simple/") 300 | assert vs == ("1.1", "1.2", "1.4") 301 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2018 Jump Trading 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /luddite.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | from __future__ import print_function 4 | from __future__ import unicode_literals 5 | 6 | import argparse 7 | import json 8 | import os 9 | import subprocess 10 | import sys 11 | from concurrent.futures import ThreadPoolExecutor 12 | 13 | from packaging.requirements import InvalidRequirement 14 | from packaging.requirements import Requirement 15 | from packaging.version import InvalidVersion 16 | from packaging.version import Version 17 | 18 | try: 19 | from urllib2 import Request, urlopen 20 | except ImportError: 21 | from urllib.request import Request, urlopen 22 | else: 23 | import cgi 24 | import codecs 25 | 26 | sys.stdout = codecs.getwriter("utf8")(sys.stdout) 27 | 28 | 29 | __version__ = "1.0.4" 30 | 31 | 32 | DEFAULT_FNAME = "requirements.txt" 33 | DEFAULT_PIP_INDEX = os.environ.get("PIP_INDEX_URL", "https://pypi.org/pypi/") 34 | DEFAULT_INDEX = os.environ.get("LUDDITE_DEFAULT_INDEX", DEFAULT_PIP_INDEX) 35 | 36 | ANSI_COLORS = { 37 | None: "\x1b[0m", # actually black but whatevs 38 | "red": "\x1b[31m", 39 | "green": "\x1b[32m", 40 | "yellow": "\x1b[33m", 41 | "magenta": "\x1b[35m", 42 | } 43 | if sys.platform == "win32": 44 | import colorama 45 | colorama.init(autoreset=True) 46 | 47 | 48 | class LudditeError(Exception): 49 | """base for exceptions explicitly raised by this module""" 50 | 51 | 52 | class MultipleIndicesError(LudditeError): 53 | """could not parse index url from the requirements.txt""" 54 | 55 | 56 | def cprint(value, **kwargs): 57 | color = ANSI_COLORS[kwargs.pop("color", None)] 58 | reset = ANSI_COLORS[None] 59 | if sys.stdout.isatty(): 60 | print("{}{}{}".format(color, value, reset), **kwargs) 61 | else: 62 | print(value, **kwargs) 63 | 64 | 65 | def get_charset(headers, default="utf-8"): 66 | # this is annoying. 67 | try: 68 | charset = headers.get_content_charset(default) 69 | except AttributeError: 70 | # Python 2 71 | charset = headers.getparam("charset") 72 | if charset is None: 73 | ct_header = headers.getheader("Content-Type") 74 | content_type, params = cgi.parse_header(ct_header) 75 | charset = params.get("charset", default) 76 | return charset 77 | 78 | 79 | def json_get(url, headers=(("Accept", "application/json"),)): 80 | request = Request(url=url, headers=dict(headers)) 81 | response = urlopen(request) 82 | code = response.code 83 | if code != 200: 84 | err = LudditeError("Unexpected response code {}".format(code)) 85 | err.response_data = response.read() 86 | raise err 87 | raw_data = response.read() 88 | response_encoding = get_charset(response.headers) 89 | decoded_data = raw_data.decode(response_encoding) 90 | data = json.loads(decoded_data) 91 | return data 92 | 93 | 94 | def get_data_pypi(name, index=DEFAULT_INDEX): 95 | uri = "{}/{}/json".format(index.rstrip("/"), name.split("[")[0]) 96 | data = json_get(uri) 97 | return data 98 | 99 | 100 | def _safe_version(v): 101 | try: 102 | return Version(v) 103 | except InvalidVersion: 104 | pass 105 | 106 | 107 | def get_versions_pypi(name, index=DEFAULT_INDEX): 108 | data = get_data_pypi(name, index) 109 | versions = [] 110 | for raw_version, details in data["releases"].items(): 111 | version = _safe_version(raw_version) 112 | if version is not None: 113 | if any(not d.get("yanked", False) for d in details): 114 | versions.append((version, raw_version)) 115 | versions.sort() 116 | return tuple(v for (_, v) in versions) 117 | 118 | 119 | def get_version_pypi(name, index=DEFAULT_INDEX): 120 | latest = get_data_pypi(name, index)["info"]["version"] 121 | return latest 122 | 123 | 124 | def strip_suffixes(s, *suffixes): 125 | """Removes the suffix, if it's there, otherwise returns input string unchanged""" 126 | for suffix in suffixes: 127 | if s.endswith(suffix): 128 | s = s[: len(s) - len(suffix)] 129 | return s 130 | 131 | 132 | def get_data_devpi(name, index): 133 | index = strip_suffixes(index, "+simple/", "+simple") 134 | uri = "{}/{}".format(index.rstrip("/"), name.split("[")[0]) 135 | data = json_get(uri) 136 | return data 137 | 138 | 139 | def get_versions_devpi(name, index): 140 | data = get_data_devpi(name, index) 141 | versions = [] 142 | for raw_version, details in data["result"].items(): 143 | version = _safe_version(raw_version) 144 | if version is not None: 145 | versions.append((version, raw_version)) 146 | versions.sort() 147 | return tuple(v for (_, v) in versions) 148 | 149 | 150 | def get_version_devpi(name, index): 151 | latest = get_versions_devpi(name, index)[-1] 152 | return latest 153 | 154 | 155 | def get_index_url(default=DEFAULT_INDEX): 156 | args = [sys.executable] + "-m pip config get global.index-url".split() 157 | with open(os.devnull, "w") as shh: 158 | try: 159 | output = subprocess.check_output(args, stderr=shh) 160 | except subprocess.CalledProcessError: 161 | # this is not working for older versions pip < 10.0.0 162 | return default 163 | else: 164 | return output.decode().strip() or default 165 | 166 | 167 | def guess_index_type(index_url): 168 | index_url = strip_suffixes(index_url, "+simple/", "+simple") 169 | try: 170 | request = Request(index_url, method="HEAD") 171 | except TypeError: 172 | # Python 2 173 | request = Request(index_url) 174 | request.get_method = lambda: "HEAD" 175 | response = urlopen(request) 176 | if response.code != 200: 177 | err = LudditeError("Unexpected response code {}".format(response.code)) 178 | err.response_data = response.read() 179 | raise err 180 | for header_name in response.headers: 181 | if header_name.lower().startswith("x-devpi"): 182 | return "devpi" 183 | return "pypi" 184 | 185 | 186 | def choose_worker(index_url): 187 | choices = {"pypi": get_versions_pypi, "devpi": get_versions_devpi} 188 | index_type = guess_index_type(index_url) 189 | func = choices.get(index_type, get_versions_pypi) 190 | return func 191 | 192 | 193 | result_map = { 194 | # string template: color 195 | "noop": ("", None), 196 | "skip": ("? skipped a line: {stripped}", "magenta"), 197 | "pass": ("✔ {req.name} is up to date @ {latest}", "green"), 198 | "warn": ("! {req.name} {version} will be outdated soon (index has {latest})", "yellow"), 199 | "gone": ("! {req.name} {version} is not in the index {from_versions}", "yellow"), 200 | "free": ("! {req.name} appears unpinned?", "yellow"), 201 | "fail": ("✖ {req.name} {version} (index has {latest_non_pre})", "red"), 202 | "oops": ("💩 couldn't get {req.name}, sorry ({error})", "magenta"), 203 | } 204 | 205 | 206 | class RequirementsLine(object): 207 | def __init__(self, text, line_number=None): 208 | self.text = text 209 | self.line_number = line_number 210 | line, _sep, _comment = text.partition(" #") 211 | line = line.strip() 212 | self.stripped = "" if line.startswith("#") else line 213 | self.req = None 214 | self.version = None 215 | self.from_versions = "" 216 | if self.stripped: 217 | try: 218 | self.req = Requirement(self.stripped) 219 | except (InvalidRequirement, ValueError): 220 | pass 221 | else: 222 | if len(self.req.specifier) == 1: 223 | spec = str(self.req.specifier) 224 | if spec.startswith("=="): 225 | _, self.version = spec.split("==", 1) 226 | self.error = None 227 | self.latest = None 228 | self.latest_non_pre = None 229 | 230 | def is_index(self): 231 | parts = self.stripped.split() 232 | for pre in "-i", "--index", "--index-url": 233 | if pre in parts: 234 | return parts[parts.index(pre) + 1] 235 | for pre in "--index=", "--index-url=": 236 | for part in parts: 237 | if part.startswith(pre): 238 | return part[len(pre):] 239 | 240 | def process(self, worker, index=None): 241 | if not self.stripped or self.is_index(): 242 | return "noop" 243 | if self.req is None: 244 | return "skip" 245 | if self.version is None: 246 | return "free" 247 | try: 248 | index_versions = worker(self.req.name, index=index) 249 | except Exception as e: 250 | self.error = e 251 | return "oops" 252 | else: 253 | versions_str = ", ".join(index_versions) 254 | self.from_versions = "(from versions: {})".format(versions_str) 255 | if self.version not in index_versions: 256 | return "gone" 257 | self.latest = index_versions[-1] 258 | self.latest_non_pre = max( 259 | index_versions, key=lambda v: (not Version(v).is_prerelease, Version(v)) 260 | ) 261 | if self.version == self.latest: 262 | return "pass" 263 | elif self.version == self.latest_non_pre: 264 | return "warn" 265 | else: 266 | return "fail" 267 | 268 | 269 | class RequirementsFile(object): 270 | def __init__(self, fname): 271 | self.fname = fname 272 | self.lines = self.parse() 273 | self.width = max(len(line.text) for line in self.lines) 274 | 275 | def parse(self): 276 | with open(str(self.fname)) as f: 277 | return [RequirementsLine(text=t, line_number=n) for n, t in enumerate(f, 1)] 278 | 279 | @property 280 | def index(self): 281 | index_url = None 282 | index_urls = list(filter(None, [x.is_index() for x in self.lines])) 283 | if len(index_urls) > 1: 284 | raise MultipleIndicesError 285 | elif index_urls: 286 | [index_url] = index_urls 287 | return index_url 288 | 289 | 290 | class Luddite(object): 291 | def __init__(self, fname=DEFAULT_FNAME, index=None): 292 | self.req_file = RequirementsFile(fname) 293 | self.index = index or self.req_file.index or get_index_url() 294 | self.get_versions = choose_worker(self.index) 295 | 296 | def run(self, n_threads=4): 297 | print(" using index: {}".format(self.index)) 298 | print("---" + "{:-<77}".format(self.req_file.fname)) 299 | with ThreadPoolExecutor(max_workers=n_threads) as executor: 300 | futures = [ 301 | executor.submit(line.process, worker=self.get_versions, index=self.index) 302 | for line in self.req_file.lines 303 | ] 304 | for line, future in zip(self.req_file.lines, futures): 305 | result = future.result() 306 | template, color = result_map[result] 307 | line_out = line.text.rstrip("\r\n") 308 | if result == "noop": 309 | print(line_out) 310 | continue 311 | pad = self.req_file.width - len(line_out) + 2 312 | print(line_out, end=" " * pad) 313 | cprint(template.format(**vars(line)), color=color) 314 | 315 | 316 | def main(): 317 | version_str = "%(prog)s v{}".format(__version__) 318 | parser = argparse.ArgumentParser(description="Luddite checks for out-of-date package versions") 319 | parser.add_argument("fname", nargs="?", default=DEFAULT_FNAME, metavar="") 320 | parser.add_argument("-i", "--index-url", metavar="") 321 | parser.add_argument("-n", "--n-threads", type=int, default=4, metavar="") 322 | parser.add_argument("-v", "--version", action="version", version=version_str) 323 | args = parser.parse_args() 324 | luddite = Luddite(fname=args.fname, index=args.index_url) 325 | luddite.run(n_threads=args.n_threads) 326 | 327 | 328 | if __name__ == "__main__": 329 | main() 330 | --------------------------------------------------------------------------------