├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── setup.py └── vendy ├── __init__.py ├── __main__.py └── third_party ├── __init__.py └── pip ├── LICENSE ├── __init__.py └── from_pip.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | 53 | # Translations 54 | *.mo 55 | *.pot 56 | 57 | # Django stuff: 58 | *.log 59 | local_settings.py 60 | db.sqlite3 61 | db.sqlite3-journal 62 | 63 | # Flask stuff: 64 | instance/ 65 | .webassets-cache 66 | 67 | # Scrapy stuff: 68 | .scrapy 69 | 70 | # Sphinx documentation 71 | docs/_build/ 72 | 73 | # PyBuilder 74 | target/ 75 | 76 | # Jupyter Notebook 77 | .ipynb_checkpoints 78 | 79 | # IPython 80 | profile_default/ 81 | ipython_config.py 82 | 83 | # pyenv 84 | .python-version 85 | 86 | # pipenv 87 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 88 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 89 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 90 | # install all needed dependencies. 91 | #Pipfile.lock 92 | 93 | # celery beat schedule file 94 | celerybeat-schedule 95 | 96 | # SageMath parsed files 97 | *.sage.py 98 | 99 | # Environments 100 | .env 101 | .venv 102 | env/ 103 | venv/ 104 | ENV/ 105 | env.bak/ 106 | venv.bak/ 107 | 108 | # Spyder project settings 109 | .spyderproject 110 | .spyproject 111 | 112 | # Rope project settings 113 | .ropeproject 114 | 115 | # mkdocs documentation 116 | /site 117 | 118 | # mypy 119 | .mypy_cache/ 120 | .dmypy.json 121 | dmypy.json 122 | 123 | # Pyre type checker 124 | .pyre/ 125 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to Contribute 2 | 3 | We'd love to accept your patches and contributions to this project. There are 4 | just a few small guidelines you need to follow. 5 | 6 | ## Contributor License Agreement 7 | 8 | Contributions to this project must be accompanied by a Contributor License 9 | Agreement. You (or your employer) retain the copyright to your contribution; 10 | this simply gives us permission to use and redistribute your contributions as 11 | part of the project. Head over to to see 12 | your current agreements on file or to sign a new one. 13 | 14 | You generally only need to submit a CLA once, so if you've already submitted one 15 | (even if it was for a different project), you probably don't need to do it 16 | again. 17 | 18 | ## Code reviews 19 | 20 | All submissions, including submissions by project members, require review. We 21 | use GitHub pull requests for this purpose. Consult 22 | [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more 23 | information on using pull requests. 24 | 25 | ## Community Guidelines 26 | 27 | This project follows [Google's Open Source Community 28 | Guidelines](https://opensource.google.com/conduct/). 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Vendy is a tool for vendoring third-party packages into your project. 2 | 3 | ## Disclaimer: 4 | This is not an officially supported Google product. 5 | 6 | ## Example: 7 | 8 | In a `pyproject.toml` file in the root of your package, define the target 9 | directory (should be in the same directory as the `pyproject.toml` file), and 10 | the packages to vendor: 11 | 12 | ```toml 13 | [tool.vendy] 14 | target = 'my_project' 15 | packages = [ 16 | "sampleproject==1.2.0", 17 | ] 18 | ``` 19 | 20 | On the command line: 21 | 22 | ``` 23 | $ python -m vendy 24 | [vendy] Using vendor dir: /private/tmp/my_project/my_project/_vendor 25 | [vendy] Cleaning /private/tmp/my_project/my_project/_vendor 26 | [vendy] Installing vendored libraries 27 | Collecting sampleproject==1.3.0 28 | Using cached https://files.pythonhosted.org/packages/a1/fd/3564a5176430eac106c27eff4de50b58fc916f5083782062cea3141acfaa/sampleproject-1.3.0-py2.py3-none-any.whl 29 | Installing collected packages: sampleproject 30 | Successfully installed sampleproject-1.3.0 31 | [vendy] Detected vendored libraries: bin, my_data, sample 32 | [vendy] Rewriting all imports related to vendored libs 33 | [vendy] Downloading licenses 34 | Collecting sampleproject==1.3.0 35 | Using cached https://files.pythonhosted.org/packages/a6/aa/0090d487d204f5de30035c00f6c71b53ec7f613138d8653eebac50f47f45/sampleproject-1.3.0.tar.gz 36 | Saved ./my_project/_vendor/__tmp__/sampleproject-1.3.0.tar.gz 37 | Successfully downloaded sampleproject 38 | [vendy] Extracting sampleproject-1.3.0/LICENSE.txt into my_project/_vendor/sampleproject.LICENSE.txt 39 | [vendy] Revendoring complete 40 | ``` 41 | 42 | Result: 43 | 44 | ``` 45 | $ tree 46 | . 47 | ├── my_project 48 | │   ├── __init__.py 49 | │   └── _vendor 50 | │   ├── bin 51 | │   │   └── sample 52 | │   ├── my_data 53 | │   │   └── data_file 54 | │   ├── sample 55 | │   │   ├── __init__.py 56 | │   │   └── package_data.dat 57 | │   └── sampleproject.LICENSE.txt 58 | └── pyproject.toml 59 | ``` 60 | 61 | And you can import from the vendored library like: 62 | 63 | ```diff 64 | -from sampleproject.foo import bar 65 | +from myproject._vendor.sampleproject.foo import bar 66 | ``` 67 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Google LLC 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from setuptools import find_packages, setup 16 | 17 | with open("README.md") as f: 18 | long_description = f.read() 19 | 20 | setup( 21 | name="vendy", 22 | version="0.0.3", 23 | author="Dustin Ingram", 24 | author_email="di@python.org", 25 | classifiers=[ 26 | "License :: OSI Approved :: Apache Software License", 27 | "Programming Language :: Python :: 3", 28 | "Programming Language :: Python :: 3.5", 29 | "Programming Language :: Python :: 3.6", 30 | "Programming Language :: Python :: 3.7", 31 | ], 32 | install_requires=["click", "requests", "toml"], 33 | long_description=long_description, 34 | long_description_content_type="text/markdown", 35 | packages=find_packages(), 36 | python_requires=">=2.7,!=3.0,!=3.1,!=3.2,!=3.3", 37 | url="http://github.com/di/vendy", 38 | description="Vendy is a tool for vendoring third-party packages into your project", 39 | summary="Vendy is a tool for vendoring third-party packages into your project", 40 | entry_points={"console_scripts": ["vendy=vendy:cli"]}, 41 | ) 42 | -------------------------------------------------------------------------------- /vendy/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Google LLC 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from pathlib import Path 16 | import os 17 | 18 | import click 19 | import toml 20 | 21 | from .third_party.pip import from_pip 22 | 23 | 24 | class Config: 25 | def __init__(self, config): 26 | self.config = config 27 | 28 | @property 29 | def target(self): 30 | return self.config.get("target") 31 | 32 | @property 33 | def packages(self): 34 | return self.config.get("packages", []) 35 | 36 | @property 37 | def file_white_list(self): 38 | return self.config.get("file_white_list", []) 39 | 40 | @property 41 | def library_dirnames(self): 42 | return self.config.get("library_dirnames", {}) 43 | 44 | @property 45 | def hardcoded_license_urls(self): 46 | return self.config.get("hardcoded_license_urls", {}) 47 | 48 | @property 49 | def extra_stubs_needed(self): 50 | return self.config.get("extra_stubs_needed", {}) 51 | 52 | @property 53 | def vendor_dir(self): 54 | return Path(os.getcwd()) / self.target / "_vendor" 55 | 56 | @property 57 | def remove_all(self): 58 | return self.config.get("remove_all", []) + ["*.dist-info", "*.egg-info"] 59 | 60 | @property 61 | def drop_dir(self): 62 | return self.config.get("drop_dir", []) 63 | 64 | 65 | def read_config(ctx): 66 | try: 67 | pyproject_toml = toml.load("pyproject.toml") 68 | config = pyproject_toml.get("tool", {}).get("vendy", {}) 69 | except (toml.TomlDecodeError, OSError): 70 | ctx.fail( 71 | "Error reading configuration file: pyproject.toml invalid or misformatted" 72 | ) 73 | 74 | if not config: 75 | ctx.fail("Error reading configuration file: pyproject.toml not configured") 76 | 77 | config = Config(config) 78 | 79 | if not config.target: 80 | ctx.fail("Error reading configuration file: 'target' field missing") 81 | 82 | if not config.packages: 83 | ctx.fail("Error reading configuration file: no packages to vendor") 84 | 85 | return config 86 | 87 | 88 | @click.group(invoke_without_command=True) 89 | @click.pass_context 90 | def cli(ctx): 91 | ctx.obj = read_config(ctx) 92 | from_pip.main(ctx) 93 | 94 | 95 | @cli.command() 96 | def vendorize(): 97 | pass 98 | 99 | 100 | @cli.command() 101 | @click.pass_context 102 | def update_stubs(ctx): 103 | from_pip.update_stubs(ctx) 104 | -------------------------------------------------------------------------------- /vendy/__main__.py: -------------------------------------------------------------------------------- 1 | from . import cli 2 | 3 | if __name__ == "__main__": 4 | cli() 5 | -------------------------------------------------------------------------------- /vendy/third_party/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/di/vendy/9719372c66dbf0fc537fa2e3150090b6eb235284/vendy/third_party/__init__.py -------------------------------------------------------------------------------- /vendy/third_party/pip/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2008-2019 The pip developers (see AUTHORS.txt file) 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining 4 | a copy of this software and associated documentation files (the 5 | "Software"), to deal in the Software without restriction, including 6 | without limitation the rights to use, copy, modify, merge, publish, 7 | distribute, sublicense, and/or sell copies of the Software, and to 8 | permit persons to whom the Software is furnished to do so, subject to 9 | the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be 12 | included in all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 15 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 16 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 17 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 18 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 19 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 20 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /vendy/third_party/pip/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/di/vendy/9719372c66dbf0fc537fa2e3150090b6eb235284/vendy/third_party/pip/__init__.py -------------------------------------------------------------------------------- /vendy/third_party/pip/from_pip.py: -------------------------------------------------------------------------------- 1 | # Original script at: 2 | # https://github.com/pypa/pip/blob/master/tasks/vendoring/__init__.py 3 | 4 | from pathlib import Path 5 | import os 6 | import re 7 | import shutil 8 | import subprocess 9 | import tarfile 10 | import zipfile 11 | 12 | import click 13 | import requests 14 | 15 | 16 | def drop_dir(path, **kwargs): 17 | shutil.rmtree(str(path), **kwargs) 18 | 19 | 20 | def remove_all(paths): 21 | for path in paths: 22 | if path.is_dir(): 23 | drop_dir(path) 24 | else: 25 | path.unlink() 26 | 27 | 28 | def log(msg): 29 | click.echo("[vendy] %s" % (msg)) 30 | 31 | 32 | def run(command): 33 | subprocess.call(command.split()) 34 | 35 | 36 | def clean_vendor(config): 37 | # Old _vendor cleanup 38 | if not config.vendor_dir.exists(): 39 | return 40 | 41 | log("Cleaning %s" % config.vendor_dir) 42 | remove_all(config.vendor_dir.glob("*.pyc")) 43 | 44 | for item in config.vendor_dir.iterdir(): 45 | if item.is_dir(): 46 | shutil.rmtree(str(item)) 47 | elif item.name not in config.file_white_list: 48 | item.unlink() 49 | else: 50 | log("Skipping %s" % item) 51 | 52 | 53 | def detect_vendored_libs(config): 54 | retval = [] 55 | for item in config.vendor_dir.iterdir(): 56 | if item.is_dir(): 57 | retval.append(item.name) 58 | elif item.name.endswith(".pyi"): 59 | continue 60 | elif "LICENSE" in item.name or "COPYING" in item.name: 61 | continue 62 | elif item.name not in config.file_white_list: 63 | retval.append(item.name[:-3]) 64 | return retval 65 | 66 | 67 | def rewrite_imports(package_dir, vendored_libs, target): 68 | for item in package_dir.iterdir(): 69 | if item.is_dir(): 70 | rewrite_imports(item, vendored_libs, target) 71 | elif item.name.endswith(".py"): 72 | rewrite_file_imports(item, vendored_libs, target) 73 | 74 | 75 | def rewrite_file_imports(item, vendored_libs, target): 76 | """Rewrite 'import xxx' and 'from xxx import' for vendored_libs""" 77 | text = item.read_text(encoding="utf-8") 78 | # Revendor pkg_resources.extern first 79 | text = re.sub(r"pkg_resources\.extern", r"{}._vendor".format(target), text) 80 | text = re.sub(r"from \.extern", r"from {}._vendor".format(target), text) 81 | for lib in vendored_libs: 82 | text = re.sub( 83 | r"(\n\s*|^)import %s(\n\s*)" % lib, 84 | r"\1from %s._vendor import %s\2" % (target, lib), 85 | text, 86 | ) 87 | text = re.sub( 88 | r"(\n\s*|^)from %s(\.|\s+)" % lib, 89 | r"\1from %s._vendor.%s\2" % (target, lib), 90 | text, 91 | ) 92 | item.write_text(text, encoding="utf-8") 93 | 94 | 95 | def apply_patch(patch_file_path): 96 | log("Applying patch %s" % patch_file_path.name) 97 | run("git apply --verbose %s" % patch_file_path) 98 | 99 | 100 | def vendor(config): 101 | log("Installing vendored libraries") 102 | 103 | # Write out an empty __init__.py file in the _vendor directory 104 | # This allows us to import from it in 2.7 105 | Path(str(config.vendor_dir / '__init__.py')).touch() 106 | 107 | # We use --no-deps because we want to ensure that all of our dependencies 108 | # are added to the packages list, this includes all dependencies 109 | # recursively up the chain. 110 | run( 111 | "pip install -t {0} {1} --no-compile --no-deps".format( 112 | str(config.vendor_dir), " ".join(config.packages) 113 | ) 114 | ) 115 | 116 | for pattern in config.remove_all: 117 | remove_all(config.vendor_dir.glob(pattern)) 118 | 119 | for path in config.drop_dir: 120 | drop_dir(config.vendor_dir / path, ignore_errors=True) 121 | 122 | # Detect the vendored packages/modules 123 | vendored_libs = detect_vendored_libs(config) 124 | log("Detected vendored libraries: %s" % ", ".join(vendored_libs)) 125 | 126 | # Global import rewrites 127 | log("Rewriting all imports related to vendored libs") 128 | for item in config.vendor_dir.iterdir(): 129 | if item.is_dir(): 130 | rewrite_imports(item, vendored_libs, config.target) 131 | elif item.name not in config.file_white_list: 132 | rewrite_file_imports(item, vendored_libs, config.target) 133 | 134 | # Special cases: apply stored patches 135 | patch_dir = config.vendor_dir / "_patches" 136 | patch_files = list(patch_dir.glob("*.patch")) 137 | if patch_files: 138 | log("Applying patches") 139 | for patch in patch_files: 140 | apply_patch(patch) 141 | 142 | 143 | def download_licenses(ctx, config): 144 | log("Downloading licenses") 145 | tmp_dir = config.vendor_dir / "__tmp__" 146 | # TODO: get this from the .toml 147 | run( 148 | "pip download {0} --no-binary " 149 | ":all: --no-deps -d {1}".format(" ".join(config.packages), str(tmp_dir)) 150 | ) 151 | for sdist in tmp_dir.iterdir(): 152 | extract_license(ctx, config, sdist) 153 | drop_dir(tmp_dir) 154 | 155 | 156 | def extract_license(ctx, config, sdist): 157 | if sdist.suffixes[-2] == ".tar": 158 | ext = sdist.suffixes[-1][1:] 159 | with tarfile.open(sdist, mode="r:{}".format(ext)) as tar: 160 | found = find_and_extract_license(config, tar, tar.getmembers()) 161 | elif sdist.suffixes[-1] == ".zip": 162 | with zipfile.ZipFile(sdist) as zip: 163 | found = find_and_extract_license(config, zip, zip.infolist()) 164 | else: 165 | raise NotImplementedError("new sdist type!") 166 | 167 | if not found: 168 | log("License not found in {}, will download".format(sdist.name)) 169 | license_fallback(ctx, config, sdist.name) 170 | 171 | 172 | def find_and_extract_license(config, tar, members): 173 | found = False 174 | for member in members: 175 | try: 176 | name = member.name 177 | except AttributeError: # zipfile 178 | name = member.filename 179 | if "LICENSE" in name or "COPYING" in name: 180 | if "/test" in name: 181 | # some testing licenses in html5lib and distlib 182 | log("Ignoring {}".format(name)) 183 | continue 184 | found = True 185 | extract_license_member(config, tar, member, name) 186 | return found 187 | 188 | 189 | def license_fallback(ctx, config, sdist_name): 190 | """Hardcoded license URLs. Check when updating if those are still needed""" 191 | libname = libname_from_dir(sdist_name) 192 | if libname not in config.hardcoded_license_urls: 193 | ctx.fail("License not found for '{}'".format(libname)) 194 | 195 | url = config.hardcoded_license_urls[libname] 196 | _, _, name = url.rpartition("/") 197 | dest = license_destination(config, libname, name) 198 | log("Downloading {}".format(url)) 199 | r = requests.get(url, allow_redirects=True) 200 | r.raise_for_status() 201 | dest.write_bytes(r.content) 202 | 203 | 204 | def libname_from_dir(dirname): 205 | """Reconstruct the library name without it's version""" 206 | parts = [] 207 | for part in dirname.split("-"): 208 | if part[0].isdigit(): 209 | break 210 | parts.append(part) 211 | return "-".join(parts) 212 | 213 | 214 | def license_destination(config, libname, filename): 215 | """Given the (reconstructed) library name, find appropriate destination""" 216 | normal = config.vendor_dir / libname 217 | if normal.is_dir(): 218 | return normal / filename 219 | lowercase = config.vendor_dir / libname.lower() 220 | if lowercase.is_dir(): 221 | return lowercase / filename 222 | if libname in config.library_dirnames: 223 | return config.vendor_dir / config.library_dirnames[libname] / filename 224 | # fallback to libname.LICENSE (used for nondirs) 225 | return config.vendor_dir / "{}.{}".format(libname, filename) 226 | 227 | 228 | def extract_license_member(config, tar, member, name): 229 | mpath = Path(name) # relative path inside the sdist 230 | dirname = list(mpath.parents)[-2].name # -1 is . 231 | libname = libname_from_dir(dirname) 232 | dest = license_destination(config, libname, mpath.name) 233 | dest_relative = dest.relative_to(Path.cwd()) 234 | log("Extracting {} into {}".format(name, dest_relative)) 235 | try: 236 | fileobj = tar.extractfile(member) 237 | dest.write_bytes(fileobj.read()) 238 | except AttributeError: # zipfile 239 | dest.write_bytes(tar.read(member)) 240 | 241 | 242 | def update_stubs(ctx): 243 | config = ctx.obj 244 | vendored_libs = detect_vendored_libs(config) 245 | 246 | log("Add mypy stubs") 247 | 248 | for lib in vendored_libs: 249 | if lib not in config.extra_stubs_needed: 250 | (config.vendor_dir / (lib + ".pyi")).write_text("from %s import *" % lib) 251 | continue 252 | 253 | for selector in config.extra_stubs_needed[lib]: 254 | fname = selector.replace(".", os.sep) + ".pyi" 255 | if selector.endswith(".__init__"): 256 | selector = selector[:-9] 257 | 258 | f_path = config.vendor_dir / fname 259 | if not f_path.parent.exists(): 260 | f_path.parent.mkdir() 261 | f_path.write_text("from %s import *" % selector) 262 | 263 | 264 | def main(ctx): 265 | config = ctx.obj 266 | log("Using vendor dir: %s" % config.vendor_dir) 267 | clean_vendor(config) 268 | vendor(config) 269 | download_licenses(ctx, config) 270 | log("Revendoring complete") 271 | --------------------------------------------------------------------------------