├── test ├── functional │ ├── __init__.py │ ├── vectors │ │ ├── bad_description.cfg │ │ ├── another-test-package.setup │ │ ├── testpackage-reloaded.setup │ │ ├── my-test-package.setup │ │ ├── park.cfg │ │ ├── another-test-package.setup.py │ │ ├── my-test-package.setup.py │ │ └── testpackage-reloaded.setup.py │ ├── test_f_util.py │ ├── test_f_build.py │ ├── test_f_config.py │ ├── functional_helpers.py │ └── test_f_park.py └── pylintrc ├── requirements.txt ├── docs ├── requirements.txt ├── index.rst ├── Makefile ├── make.bat └── conf.py ├── MANIFEST.in ├── src ├── pylintrc └── pypi_parker │ ├── util.py │ ├── __init__.py │ ├── build.py │ └── config.py ├── CHANGELOG.rst ├── park.cfg ├── .travis.yml ├── setup.cfg ├── .gitignore ├── setup.py ├── tox.ini ├── README.rst └── LICENSE /test/functional/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | readme_renderer>=17.2 -------------------------------------------------------------------------------- /docs/requirements.txt: -------------------------------------------------------------------------------- 1 | sphinx>=1.3.0 2 | sphinx_rtd_theme 3 | sphinx-autodoc-typehints -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.rst 2 | include CHANGELOG.rst 3 | include LICENSE 4 | include requirements.txt -------------------------------------------------------------------------------- /src/pylintrc: -------------------------------------------------------------------------------- 1 | [FORMAT] 2 | max-line-length = 120 3 | 4 | [REPORTS] 5 | msg-template = {path}:{line}: [{msg_id}({symbol}), {obj}] {msg} 6 | -------------------------------------------------------------------------------- /test/functional/vectors/bad_description.cfg: -------------------------------------------------------------------------------- 1 | [DEFAULT] 2 | version: 3.1.4 3 | author: pypi-parker 4 | author_email: park-email@example-url.co.net 5 | url: example-url.co.net 6 | description: 7 | multiple 8 | lines 9 | 10 | [names] 11 | my-test-package: 12 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../README.rst 2 | 3 | Modules 4 | ******* 5 | 6 | .. autosummary:: 7 | :toctree: generated 8 | 9 | pypi_parker 10 | pypi_parker.build 11 | pypi_parker.config 12 | pypi_parker.util 13 | 14 | .. include:: ../CHANGELOG.rst 15 | -------------------------------------------------------------------------------- /CHANGELOG.rst: -------------------------------------------------------------------------------- 1 | Changelog 2 | ********* 3 | 4 | 0.1.2 5 | ===== 6 | * Minor fix to address mypy incompatibility 7 | 8 | 0.1.1 9 | ===== 10 | * Addressed `issue #1 `_ to properly 11 | handle description values to ensure pypi compatibility. 12 | 13 | 0.1.0 14 | ===== 15 | * Initial release 16 | -------------------------------------------------------------------------------- /test/functional/vectors/another-test-package.setup: -------------------------------------------------------------------------------- 1 | { 2 | "name": "another-test-package", 3 | "author": "pypi-parker", 4 | "author_email": "park-email@example-url.co.net", 5 | "url": "example-url.co.net", 6 | "description": "parked using pypi-parker", 7 | "long_description": "\nWoo!\nOverriding the long description but not the short description.", 8 | "classifiers": ["another thing", "thing 1"], 9 | "version": "3.1.4" 10 | } -------------------------------------------------------------------------------- /park.cfg: -------------------------------------------------------------------------------- 1 | [DEFAULT] 2 | author: Matt Bullock 3 | author_email: matt.s.b.42@gmail.com 4 | url: https://github.com/mattsb42/pypi-parker 5 | version: 0.0.9 6 | license: Apache License 2.0 7 | description: parked 8 | long_description: 9 | This package is parked by {author} to protect against typo misdirection. 10 | See {url} for more information. 11 | Did you mean to install "pypi-parker"? 12 | description_keys: 13 | author 14 | url 15 | 16 | [names] 17 | pypiparker: -------------------------------------------------------------------------------- /test/functional/vectors/testpackage-reloaded.setup: -------------------------------------------------------------------------------- 1 | { 2 | "name": "testpackage-reloaded", 3 | "author": "pypi-parker", 4 | "author_email": "park-email@example-url.co.net", 5 | "url": "example-url.co.net", 6 | "description": "This is a unique description. Locked by pypi-parker at example-url.co.net.", 7 | "long_description": "This is a unique description. Locked by pypi-parker at example-url.co.net.", 8 | "classifiers": ["Development Status :: 7 - Inactive"], 9 | "version": "3.1.4" 10 | } -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: python 3 | matrix: 4 | include: 5 | - python: 3.6 6 | env: TOXENV=py36 7 | - python: 3.6 8 | env: TOXENV=mypy 9 | - python: 3.6 10 | env: TOXENV=doc8 11 | - python: 3.6 12 | env: TOXENV=readme 13 | - python: 3.6 14 | env: TOXENV=flake8 15 | - python: 3.6 16 | env: TOXENV=pylint 17 | - python: 3.6 18 | env: TOXENV=flake8-tests 19 | - python: 3.6 20 | env: TOXENV=pylint-tests 21 | install: pip install tox 22 | script: tox 23 | -------------------------------------------------------------------------------- /test/functional/vectors/my-test-package.setup: -------------------------------------------------------------------------------- 1 | { 2 | "name": "my-test-package", 3 | "author": "pypi-parker", 4 | "author_email": "park-email@example-url.co.net", 5 | "url": "example-url.co.net", 6 | "description": "parked using pypi-parker", 7 | "long_description": "This package has been parked either for future use or to protect against typo misdirection.\nIf you believe that it has been parked in error, please contact the package owner.", 8 | "classifiers": ["Development Status :: 7 - Inactive"], 9 | "version": "3.1.4" 10 | } -------------------------------------------------------------------------------- /test/functional/vectors/park.cfg: -------------------------------------------------------------------------------- 1 | [DEFAULT] 2 | version: 3.1.4 3 | author: pypi-parker 4 | author_email: park-email@example-url.co.net 5 | url: example-url.co.net 6 | 7 | [names] 8 | my-test-package: 9 | another-test-package: 10 | 11 | [testpackage-reloaded] 12 | description: This is a unique description. Locked by {author} at {url}. 13 | description_keys: 14 | author 15 | url 16 | 17 | [another-test-package] 18 | long_description: 19 | Woo! 20 | Overriding the long description but not the short description. 21 | classifiers: 22 | thing 1 23 | another thing 24 | -------------------------------------------------------------------------------- /test/functional/test_f_util.py: -------------------------------------------------------------------------------- 1 | """Functional test suite for :class:`pypi_parker.util.SpecificTemporaryFile`.""" 2 | import base64 3 | import os 4 | 5 | from pypi_parker import util 6 | 7 | 8 | def test_specific_temporary_file(tmpdir): 9 | filename = tmpdir.mkdir('test').join('a_file.txt') 10 | body = str(base64.b64encode(os.urandom(1024))) 11 | 12 | assert not os.path.exists(str(filename)) 13 | 14 | with util.SpecificTemporaryFile(name=filename, body=body): 15 | assert os.path.isfile(str(filename)) 16 | assert filename.read() == body 17 | 18 | assert not os.path.exists(str(filename)) 19 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [wheel] 2 | universal = 1 3 | 4 | [metadata] 5 | license_file = LICENSE 6 | 7 | [coverage:report] 8 | show_missing = True 9 | 10 | [mypy] 11 | # TODO: figure out a better option and remove this 12 | ignore_missing_imports = True 13 | 14 | # Flake8 Configuration 15 | [flake8] 16 | max_complexity = 10 17 | max_line_length = 120 18 | import_order_style = google 19 | application_import_names = pypi_parker 20 | builtins = raw_input 21 | ignore = 22 | # Ignoring D205 and D400 because of false positives 23 | D205, D400, 24 | # Ignoring W503 : line break before binary operator 25 | W503 26 | 27 | # Doc8 Configuration 28 | [doc8] 29 | max-line-length = 120 30 | -------------------------------------------------------------------------------- /test/functional/vectors/another-test-package.setup.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from setuptools import setup 3 | 4 | args = ' '.join(sys.argv).strip() 5 | if not any(args.endswith(suffix) for suffix in ['setup.py check -r -s', 'setup.py sdist']): 6 | raise ImportError('parked using pypi-parker',) 7 | 8 | setup( 9 | author='pypi-parker', 10 | author_email='park-email@example-url.co.net', 11 | classifiers=['another thing', 'thing 1'], 12 | description='parked using pypi-parker', 13 | long_description='\nWoo!\nOverriding the long description but not the short description.', 14 | name='another-test-package', 15 | url='example-url.co.net', 16 | version='3.1.4' 17 | ) 18 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = python -msphinx 7 | SPHINXPROJ = pypi-parker 8 | SOURCEDIR = . 9 | BUILDDIR = _build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) -------------------------------------------------------------------------------- /test/functional/vectors/my-test-package.setup.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from setuptools import setup 3 | 4 | args = ' '.join(sys.argv).strip() 5 | if not any(args.endswith(suffix) for suffix in ['setup.py check -r -s', 'setup.py sdist']): 6 | raise ImportError('parked using pypi-parker',) 7 | 8 | setup( 9 | author='pypi-parker', 10 | author_email='park-email@example-url.co.net', 11 | classifiers=['Development Status :: 7 - Inactive'], 12 | description='parked using pypi-parker', 13 | long_description='This package has been parked either for future use or to protect against typo misdirection.\nIf you believe that it has been parked in error, please contact the package owner.', 14 | name='my-test-package', 15 | url='example-url.co.net', 16 | version='3.1.4' 17 | ) 18 | -------------------------------------------------------------------------------- /test/functional/vectors/testpackage-reloaded.setup.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from setuptools import setup 3 | 4 | args = ' '.join(sys.argv).strip() 5 | if not any(args.endswith(suffix) for suffix in ['setup.py check -r -s', 'setup.py sdist']): 6 | raise ImportError('This is a unique description. Locked by pypi-parker at example-url.co.net.',) 7 | 8 | setup( 9 | author='pypi-parker', 10 | author_email='park-email@example-url.co.net', 11 | classifiers=['Development Status :: 7 - Inactive'], 12 | description='This is a unique description. Locked by pypi-parker at example-url.co.net.', 13 | long_description='This is a unique description. Locked by pypi-parker at example-url.co.net.', 14 | name='testpackage-reloaded', 15 | url='example-url.co.net', 16 | version='3.1.4' 17 | ) 18 | -------------------------------------------------------------------------------- /test/pylintrc: -------------------------------------------------------------------------------- 1 | [MESSAGES CONTROL] 2 | # Disabling messages that we either don't care about 3 | # for tests or are necessary to break for tests. 4 | # 5 | # C0103 : invalid-name (we prefer long, descriptive, names for tests) 6 | # C0111 : missing-docstring (we don't write docstrings for tests) 7 | # E1101 : no-member (raised on patched objects with mock checks) 8 | # R0801 : duplicate-code (unit tests for similar things tend to be similar) 9 | # W0106 : expression-not-assigned (common for tests that catch exceptions) 10 | # W0212 : protected-access (raised when calling _ methods) 11 | # W0621 : redefined-outer-name (raised when using pytest-mock) 12 | # W0613 : unused-argument (raised when patches are needed but not called) 13 | disable = C0103, C0111, E1101, R0801, W0106, W0212, W0621, W0613 14 | 15 | [FORMAT] 16 | max-line-length = 120 17 | 18 | [REPORTS] 19 | msg-template = {path}:{line}: [{msg_id}({symbol}), {obj}] {msg} 20 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | pushd %~dp0 4 | 5 | REM Command file for Sphinx documentation 6 | 7 | if "%SPHINXBUILD%" == "" ( 8 | set SPHINXBUILD=python -msphinx 9 | ) 10 | set SOURCEDIR=. 11 | set BUILDDIR=_build 12 | set SPHINXPROJ=pypi-parker 13 | 14 | if "%1" == "" goto help 15 | 16 | %SPHINXBUILD% >NUL 2>NUL 17 | if errorlevel 9009 ( 18 | echo. 19 | echo.The Sphinx module was not found. Make sure you have Sphinx installed, 20 | echo.then set the SPHINXBUILD environment variable to point to the full 21 | echo.path of the 'sphinx-build' executable. Alternatively you may add the 22 | echo.Sphinx directory to PATH. 23 | echo. 24 | echo.If you don't have Sphinx installed, grab it from 25 | echo.http://sphinx-doc.org/ 26 | exit /b 1 27 | ) 28 | 29 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% 30 | goto end 31 | 32 | :help 33 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% 34 | 35 | :end 36 | popd 37 | -------------------------------------------------------------------------------- /src/pypi_parker/util.py: -------------------------------------------------------------------------------- 1 | """Utility helpers for :class:`pypi_parker.Park`.""" 2 | import os 3 | from typing import Any 4 | 5 | __all__ = ('SpecificTemporaryFile',) 6 | 7 | 8 | class SpecificTemporaryFile(object): # pylint: disable=too-few-public-methods 9 | """Context manager for temporary files with a known desired name and body. 10 | 11 | :param name: Filename of file to create 12 | :param body: Data to write to file 13 | """ 14 | 15 | def __init__(self, name: str, body: str) -> None: 16 | """Initialize parameters.""" 17 | self.name = name 18 | self.body = body 19 | 20 | def _write_file(self) -> None: 21 | """Write the requested body to the requested file.""" 22 | with open(self.name, 'w') as file: 23 | file.write(self.body) 24 | 25 | def _delete_file(self) -> None: 26 | """Delete the created file.""" 27 | os.remove(self.name) 28 | 29 | def __enter__(self): 30 | # type: () -> SpecificTemporaryFile 31 | """Create the specified file and write the body on enter.""" 32 | self._write_file() 33 | return self 34 | 35 | def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None: 36 | """Clean up the created file.""" 37 | self._delete_file() 38 | -------------------------------------------------------------------------------- /test/functional/test_f_build.py: -------------------------------------------------------------------------------- 1 | """Functional test suite for ``pypi_parker.config``.""" 2 | import os 3 | 4 | import pytest 5 | 6 | from pypi_parker import build 7 | 8 | from .functional_helpers import ( 9 | read_manifest_from_sdist, read_setup_config, read_setup_from_sdist, 10 | read_setup_py, TEST_PACKAGE_NAMES 11 | ) 12 | 13 | 14 | @pytest.mark.parametrize('name', TEST_PACKAGE_NAMES) 15 | def test_setup_body(name): 16 | setup_config = read_setup_config(name) 17 | 18 | assert build._setup_body(setup_config) == read_setup_py(name) 19 | 20 | 21 | @pytest.mark.parametrize('name', TEST_PACKAGE_NAMES) 22 | def test_generate_and_build_pacakge(tmpdir, name): 23 | target_dir = tmpdir.mkdir('test') 24 | setup_config = read_setup_config(name) 25 | 26 | build.generate_and_build_package( 27 | package_config=setup_config, 28 | origin_directory=str(target_dir) 29 | ) 30 | 31 | assert os.path.isdir(os.path.join(str(target_dir), 'dist')) 32 | dist_contents = os.listdir(os.path.join(str(target_dir), 'dist')) 33 | assert len(dist_contents) == 1 34 | sdist_file = os.path.join(str(target_dir), 'dist', dist_contents[0]) 35 | assert read_manifest_from_sdist(sdist_file) == build.MANIFEST 36 | assert read_setup_from_sdist(sdist_file) == read_setup_py(name) 37 | -------------------------------------------------------------------------------- /test/functional/test_f_config.py: -------------------------------------------------------------------------------- 1 | """Functional test suite for ``pypi_parker.config``.""" 2 | import os 3 | 4 | import pytest 5 | 6 | from pypi_parker import config 7 | 8 | from .functional_helpers import HERE, read_raw_config, read_setup_config, TEST_PACKAGE_NAMES 9 | 10 | 11 | def test_string_literal_to_lines(): 12 | source = ''' 13 | c 14 | a 15 | b 16 | a b c 17 | ''' 18 | result = ['a', 'a b c', 'b', 'c'] 19 | assert config._string_literal_to_lines(source) == result 20 | 21 | 22 | @pytest.mark.parametrize('name', TEST_PACKAGE_NAMES) 23 | def test_generate_setup(name): 24 | parser = read_raw_config() 25 | 26 | generated_setup = config._generate_setup(parser, name) 27 | 28 | assert generated_setup == read_setup_config(name) 29 | 30 | 31 | @pytest.mark.parametrize('name', TEST_PACKAGE_NAMES) 32 | def test_load_config(name): 33 | loaded_configs = [i for i in config.load_config(os.path.join(HERE, 'vectors', 'park.cfg'))] 34 | 35 | assert read_setup_config(name) in loaded_configs 36 | 37 | 38 | def test_load_config_newline_in_description(): 39 | with pytest.raises(ValueError) as excinfo: 40 | [i for i in config.load_config(os.path.join(HERE, 'vectors', 'bad_description.cfg'))] 41 | 42 | excinfo.match(r'Package "description" must be a single line.') 43 | -------------------------------------------------------------------------------- /src/pypi_parker/__init__.py: -------------------------------------------------------------------------------- 1 | """PyPI Parker setup expansion resources.""" 2 | # virtualenv + distutils bug in pylint: https://github.com/PyCQA/pylint/issues/73 3 | from distutils.cmd import Command # pylint: disable=import-error,no-name-in-module 4 | import os 5 | import sys 6 | 7 | from pypi_parker.build import generate_and_build_package 8 | from pypi_parker.config import load_config 9 | 10 | __version__ = '0.1.2' 11 | 12 | 13 | class Park(Command): 14 | """Distutils Command for reading a :class:`pypi-parker` configuration 15 | and building distribution files for each name. 16 | """ 17 | 18 | decription = 'Generates builds for all configured PyPI names' 19 | user_options = [ 20 | ('park-config=', 'p', 'path to pypi-parker config file') 21 | ] 22 | 23 | def initialize_options(self) -> None: 24 | """Set default values for options.""" 25 | self.park_config = 'park.cfg' # pylint: disable=attribute-defined-outside-init 26 | 27 | def finalize_options(self) -> None: # noqa=D401 28 | """Required by :class:`distutils.cmd` but not used.""" 29 | self.park_config = os.path.abspath(self.park_config) # pylint: disable=attribute-defined-outside-init 30 | 31 | if not os.path.isfile(self.park_config): 32 | sys.exit('Requested pypi_parker config file "{}" does not exist'.format(self.park_config)) 33 | 34 | def run(self) -> None: 35 | """Run command.""" 36 | base_dir = os.path.dirname(self.park_config) 37 | 38 | for package in load_config(self.park_config): 39 | generate_and_build_package(package, base_dir) 40 | -------------------------------------------------------------------------------- /test/functional/functional_helpers.py: -------------------------------------------------------------------------------- 1 | """Helper functions for ``pypi_parker`` functional tests.""" 2 | import codecs 3 | import configparser 4 | import json 5 | import os 6 | import tarfile 7 | 8 | HERE = os.path.abspath(os.path.dirname(__file__)) 9 | TEST_PACKAGE_NAMES = ( 10 | 'my-test-package', 11 | 'another-test-package', 12 | 'testpackage-reloaded' 13 | ) 14 | 15 | 16 | def read(filename): 17 | with open(filename) as f: 18 | return f.read() 19 | 20 | 21 | def read_raw_config(filename=None): 22 | if filename is None: 23 | filename = os.path.join(HERE, 'vectors', 'park.cfg') 24 | parser = configparser.ConfigParser() 25 | parser.read(filename) 26 | return parser 27 | 28 | 29 | def read_setup_config(name): 30 | return json.loads(read(os.path.join(HERE, 'vectors', name + '.setup'))) 31 | 32 | 33 | def read_setup_py(name): 34 | return read(os.path.join(HERE, 'vectors', name + '.setup.py')) 35 | 36 | 37 | def read_file_from_sdist(sdist_filename, target_filename): 38 | with tarfile.open(sdist_filename, 'r') as sdist: 39 | for name in sdist.getnames(): 40 | if name.endswith(target_filename) and name.count(os.path.sep) == 1: 41 | member = sdist.getmember(name) 42 | with sdist.extractfile(member) as target: 43 | return target.read() 44 | 45 | 46 | def read_setup_from_sdist(sdist_filename): 47 | return codecs.decode(read_file_from_sdist(sdist_filename, 'setup.py'), 'utf-8') 48 | 49 | 50 | def read_manifest_from_sdist(sdist_filename): 51 | return codecs.decode(read_file_from_sdist(sdist_filename, 'MANIFEST.in'), 'utf-8') 52 | -------------------------------------------------------------------------------- /.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 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | docs/generated/ 67 | 68 | # PyBuilder 69 | target/ 70 | 71 | # Jupyter Notebook 72 | .ipynb_checkpoints 73 | 74 | # pyenv 75 | .python-version 76 | 77 | # celery beat schedule file 78 | celerybeat-schedule 79 | 80 | # SageMath parsed files 81 | *.sage.py 82 | 83 | # dotenv 84 | .env 85 | 86 | # virtualenv 87 | .venv 88 | venv/ 89 | ENV/ 90 | 91 | # Spyder project settings 92 | .spyderproject 93 | .spyproject 94 | 95 | # Rope project settings 96 | .ropeproject 97 | 98 | # mkdocs documentation 99 | /site 100 | 101 | # mypy 102 | .mypy_cache/ 103 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | """PyPI Parker - Combatting Typosquatting""" 2 | import os 3 | import re 4 | 5 | from setuptools import find_packages, setup 6 | 7 | VERSION_RE = re.compile(r'''__version__ = ['"]([0-9.]+)['"]''') 8 | HERE = os.path.abspath(os.path.dirname(__file__)) 9 | 10 | 11 | def read(*args): 12 | """Read complete file contents.""" 13 | return open(os.path.join(HERE, *args)).read() 14 | 15 | 16 | def get_version(): 17 | """Read the version from this module.""" 18 | init = read('src', 'pypi_parker', '__init__.py') 19 | return VERSION_RE.search(init).group(1) 20 | 21 | 22 | def get_requirements(): 23 | """Read the requirements file.""" 24 | requirements = read('requirements.txt') 25 | return [r for r in requirements.strip().splitlines()] 26 | 27 | 28 | setup( 29 | name='pypi-parker', 30 | packages=find_packages('src'), 31 | package_dir={'': 'src'}, 32 | version=get_version(), 33 | author='Matt Bullock', 34 | maintainer='Matt Bullock', 35 | author_email='matt.s.b.42@gmail.com', 36 | url='https://github.com/mattsb42/pypi-parker', 37 | description='', 38 | long_description=read('README.rst'), 39 | keywords='pypi warehouse distutils typosquating', 40 | license='Apache License 2.0', 41 | install_requires=get_requirements(), 42 | classifiers=[ 43 | # 'Development Status :: 5 - Production/Stable', 44 | 'Development Status :: 4 - Beta', 45 | 'Intended Audience :: Developers', 46 | 'Natural Language :: English', 47 | 'License :: OSI Approved :: Apache Software License', 48 | 'Programming Language :: Python', 49 | 'Programming Language :: Python :: 3', 50 | 'Programming Language :: Python :: 3.6', 51 | 'Programming Language :: Python :: Implementation :: CPython', 52 | 'Topic :: System :: Software Distribution', 53 | 'Topic :: Utilities' 54 | ], 55 | entry_points={ 56 | 'distutils.commands': [ 57 | 'park = pypi_parker:Park' 58 | ] 59 | } 60 | ) 61 | -------------------------------------------------------------------------------- /test/functional/test_f_park.py: -------------------------------------------------------------------------------- 1 | """Functional test suite for :class:`pypi_parker.Park`.""" 2 | import os 3 | import shlex 4 | import subprocess 5 | import sys 6 | 7 | import pytest 8 | 9 | from .functional_helpers import HERE, read, TEST_PACKAGE_NAMES 10 | 11 | 12 | @pytest.mark.parametrize('config_filename, suffix', ( 13 | ('park.cfg', ''), 14 | ('A_DIFFERENT_FILENAME', ' --park=A_DIFFERENT_FILENAME'), 15 | ('ANOTHER_FILENAME', ' -p ANOTHER_FILENAME') 16 | )) 17 | def test_park(tmpdir, config_filename, suffix): 18 | target_dir = tmpdir.mkdir('test') 19 | target_setup = target_dir.join('setup.py') 20 | target_setup.write('from setuptools import setup\nsetup()\n') 21 | target_config = target_dir.join(config_filename) 22 | target_config.write(read(os.path.join(HERE, 'vectors', 'park.cfg'))) 23 | 24 | os.chdir(str(target_dir)) 25 | 26 | command_string = 'setup.py park' + suffix 27 | subprocess.check_call([sys.executable] + shlex.split(command_string)) 28 | 29 | results = os.listdir(os.path.join(str(target_dir), 'dist')) 30 | assert len(results) == len(TEST_PACKAGE_NAMES) 31 | 32 | 33 | def test_park_file_not_found_default(tmpdir): 34 | target_dir = tmpdir.mkdir('test') 35 | target_setup = target_dir.join('setup.py') 36 | target_setup.write('from setuptools import setup\nsetup()\n') 37 | 38 | os.chdir(str(target_dir)) 39 | 40 | with pytest.raises(subprocess.CalledProcessError): 41 | subprocess.check_call([sys.executable, 'setup.py', 'park']) 42 | 43 | 44 | def test_park_file_not_found_custom_filename(tmpdir): 45 | target_dir = tmpdir.mkdir('test') 46 | target_setup = target_dir.join('setup.py') 47 | target_setup.write('from setuptools import setup\nsetup()\n') 48 | target_config = target_dir.join('park.cfg') 49 | target_config.write(read(os.path.join(HERE, 'vectors', 'park.cfg'))) 50 | 51 | os.chdir(str(target_dir)) 52 | 53 | with pytest.raises(subprocess.CalledProcessError): 54 | subprocess.check_call([sys.executable, 'setup.py', 'park', '--park-config', 'ANOTHER_FILENAME']) 55 | -------------------------------------------------------------------------------- /src/pypi_parker/build.py: -------------------------------------------------------------------------------- 1 | """Tooling to generate and build ephemeral packages based on package configurations.""" 2 | import glob 3 | import os 4 | import shutil 5 | import subprocess 6 | import sys 7 | import tempfile 8 | 9 | from pypi_parker.config import SETUP_CONFIG 10 | from pypi_parker.util import SpecificTemporaryFile 11 | 12 | __all__ = ('generate_and_build_package',) 13 | ALLOWED_SETUP_SUFFIXES = ('setup.py sdist', 'setup.py check -r -s') 14 | MANIFEST = 'include setup.py' 15 | 16 | 17 | def _setup_body(setup_conf: SETUP_CONFIG) -> str: 18 | """Generate the setup.py body given a setup config. 19 | 20 | .. note:: 21 | 22 | The setup.py generated here will raise an ImportError for every actions 23 | except for those whitelisted for use when building the package. 24 | 25 | :param setup_conf: Setup config for which to generate setup.py 26 | """ 27 | return os.linesep.join([ 28 | 'import sys', 29 | 'from setuptools import setup', 30 | '', 31 | "args = ' '.join(sys.argv).strip()", 32 | 'if not any(args.endswith(suffix) for suffix in [{allowed_suffixes}]):', 33 | ' raise {error}', 34 | '', 35 | 'setup(', 36 | ' {config}', 37 | ')', 38 | '' 39 | ]).format( 40 | error=repr(ImportError(setup_conf['description'])), 41 | config=',{linesep} '.join([ 42 | '{}={}'.format(key, repr(value)) 43 | for key, value 44 | in sorted(setup_conf.items(), key=lambda item: item[0]) 45 | ]).format(linesep=os.linesep), 46 | allowed_suffixes=', '.join(repr(each) for each in sorted(ALLOWED_SETUP_SUFFIXES)) 47 | ) 48 | 49 | 50 | def generate_and_build_package(package_config: SETUP_CONFIG, origin_directory: str) -> None: 51 | """Generates, validates, and builds a package using the specified configuration and places 52 | the resulting distributable files in ``{origin_directory}/dist``. 53 | 54 | :param package_config: Package setup configuration 55 | :param origin_directory: Filepath to desired base output directory 56 | """ 57 | os.makedirs(os.path.join(origin_directory, 'dist'), exist_ok=True) 58 | 59 | with tempfile.TemporaryDirectory() as tmpdirname: 60 | 61 | os.chdir(tmpdirname) 62 | 63 | setup_py = SpecificTemporaryFile( 64 | name=os.path.join(tmpdirname, 'setup.py'), 65 | body=_setup_body(package_config) 66 | ) 67 | 68 | manifest_in = SpecificTemporaryFile( 69 | name=os.path.join(tmpdirname, 'MANIFEST.in'), 70 | body=MANIFEST 71 | ) 72 | 73 | with setup_py, manifest_in: 74 | validate_command = [sys.executable, setup_py.name, 'check', '-r', '-s'] 75 | subprocess.check_call(validate_command) 76 | 77 | build_command = [sys.executable, setup_py.name, 'sdist'] 78 | subprocess.check_call(build_command) 79 | 80 | for file in glob.glob(os.path.join(tmpdirname, 'dist/*')): 81 | shutil.copy(file, os.path.join(origin_directory, 'dist')) 82 | 83 | os.chdir(origin_directory) 84 | -------------------------------------------------------------------------------- /src/pypi_parker/config.py: -------------------------------------------------------------------------------- 1 | """Tooling to generate package configurations from configuration files.""" 2 | import configparser 3 | from typing import Dict, Iterator, Sequence, Union 4 | 5 | __all__ = ('load_config',) 6 | FALLBACK_VALUES = dict( 7 | classifiers=['Development Status :: 7 - Inactive'], 8 | description='parked using pypi-parker', 9 | long_description=( 10 | 'This package has been parked either for future use or to protect against typo misdirection.\n' 11 | 'If you believe that it has been parked in error, please contact the package owner.' 12 | ) 13 | ) 14 | STRING_LITERAL_KEYS = ('classifiers',) 15 | SETUP_CONFIG = Dict[str, Union[str, Sequence[str]]] 16 | 17 | 18 | def _string_literal_to_lines(string_literal: str) -> Sequence[str]: 19 | """Split a string literal into lines. 20 | 21 | :param string_literal: Source to split 22 | """ 23 | return sorted([ 24 | line.strip() for line 25 | in string_literal.strip().splitlines() 26 | ]) 27 | 28 | 29 | def _update_description(setup_base: SETUP_CONFIG) -> None: 30 | """Update description field with description keys if defined.""" 31 | try: 32 | description_keys = _string_literal_to_lines(str(setup_base.pop('description_keys'))) 33 | description_setup = {key: str(setup_base[key]) for key in description_keys} # type: Dict[str, str] 34 | except KeyError: 35 | return 36 | 37 | for field in ('description', 'long_description'): 38 | try: 39 | setup_base[field] = str(setup_base[field]).format(**description_setup) 40 | except KeyError: 41 | pass 42 | 43 | 44 | def _update_string_literal_values(setup_base: SETUP_CONFIG) -> None: 45 | """Update ``setup_base`` by splitting string literal key values into lines.""" 46 | for key in STRING_LITERAL_KEYS: 47 | try: 48 | setup_base[key] = _string_literal_to_lines(str(setup_base[key])) 49 | except KeyError: 50 | pass 51 | 52 | 53 | def _update_fallback_values(setup_base: SETUP_CONFIG) -> None: 54 | """Update ``setup_base`` with fallback values.""" 55 | if 'long_description' not in setup_base and 'description' in setup_base: 56 | setup_base['long_description'] = setup_base['description'] 57 | 58 | for key, value in FALLBACK_VALUES.items(): 59 | if key not in setup_base: 60 | setup_base[key] = value 61 | 62 | 63 | def _generate_setup(config: configparser.ConfigParser, name: str) -> SETUP_CONFIG: 64 | """Generate a ``setuptools.setup`` call for ``name`` from ``config``. 65 | 66 | :param config: Loaded parker config 67 | :param name: Package name for which to generate setup config 68 | """ 69 | setup_base = {} # type: SETUP_CONFIG 70 | if name in config: 71 | setup_base.update(dict(config[name].items())) 72 | else: 73 | setup_base.update(dict(config['DEFAULT'].items())) 74 | setup_base['name'] = name 75 | 76 | if name in config: 77 | setup_base.update(config[name].items()) 78 | 79 | _update_description(setup_base) 80 | _update_string_literal_values(setup_base) 81 | _update_fallback_values(setup_base) 82 | 83 | if len(str(setup_base['description']).splitlines()) > 1: 84 | raise ValueError('Package "description" must be a single line.') 85 | 86 | return setup_base 87 | 88 | 89 | def load_config(filename: str) -> Iterator[SETUP_CONFIG]: 90 | """Load ``parker.conf`` and generate all ``setuptools.setup`` calls. 91 | 92 | :param filename: Filename of configuation file to load 93 | """ 94 | config = configparser.ConfigParser() 95 | config.read(filename) 96 | 97 | names = config.sections() 98 | if 'names' in config: 99 | names.remove('names') 100 | names.extend([ 101 | name for name in config['names'] 102 | if name not in names and name not in config['DEFAULT'] 103 | ]) 104 | 105 | for name in names: 106 | yield _generate_setup(config, name) 107 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = 3 | py36, mypy, 4 | doc8, readme, 5 | flake8, pylint, 6 | flake8-tests, pylint-tests 7 | 8 | # Additional environments: 9 | # bandit :: Looks for security issues. Complains about subprocess. 10 | # vulture :: Looks for unused code. Prone to false-positives. 11 | # linters :: Runs all linters over all source code. 12 | # linters-tests :: Runs all linters over all tests. 13 | 14 | # Build/Deploy environments: 15 | # docs :: Build Sphinx docs 16 | # serve-docs :: Start webserver to host built Sphinx docs 17 | # park :: Build pypi-parker distributables 18 | # build :: Build source and wheel distributables 19 | # test-release :: Publish to testpypi 20 | # release :: Publish to pypi 21 | 22 | [testenv] 23 | sitepackages = False 24 | deps = 25 | mock 26 | pytest 27 | pytest-catchlog 28 | pytest-cov 29 | pytest-mock 30 | coverage 31 | commands = 32 | coverage run -m pytest \ 33 | --cov pypi_parker \ 34 | {posargs} 35 | 36 | # mypy 37 | [testenv:mypy] 38 | basepython = python3 39 | deps = 40 | coverage 41 | mypy 42 | commands = 43 | python -m mypy \ 44 | --linecoverage-report build \ 45 | src/pypi_parker/ 46 | # Make mypy linecoverage report readable by coverage 47 | python -c \ 48 | "t = open('.coverage', 'w');\ 49 | c = open('build/coverage.json').read();\ 50 | t.write('!coverage.py: This is a private format, don\'t read it directly!\n');\ 51 | t.write(c);\ 52 | t.close()" 53 | coverage report -m 54 | 55 | # Linters 56 | [testenv:flake8] 57 | basepython = python3 58 | deps = 59 | flake8 60 | flake8-docstrings 61 | flake8-import-order 62 | commands = 63 | flake8 src/pypi_parker/ setup.py 64 | 65 | [testenv:flake8-tests] 66 | basepython = {[testenv:flake8]basepython} 67 | deps = 68 | flake8 69 | flake8-import-order 70 | commands = 71 | flake8 \ 72 | # Ignore F811 redefinition errors in tests (breaks with pytest-mock use) 73 | --ignore F811 \ 74 | --exclude test/functional/vectors \ 75 | test/ 76 | 77 | [testenv:pylint] 78 | basepython = python3 79 | deps = 80 | {[testenv]deps} 81 | pyflakes 82 | pylint 83 | commands = 84 | pylint \ 85 | --rcfile=src/pylintrc \ 86 | src/pypi_parker/ \ 87 | setup.py 88 | 89 | [testenv:pylint-tests] 90 | basepython = {[testenv:pylint]basepython} 91 | deps = {[testenv:pylint]deps} 92 | commands = 93 | pylint \ 94 | --rcfile=test/pylintrc \ 95 | test/functional/ 96 | 97 | [testenv:doc8] 98 | basepython = python3 99 | deps = 100 | -rdocs/requirements.txt 101 | doc8 102 | commands = doc8 docs/index.rst README.rst CHANGELOG.rst 103 | 104 | [testenv:readme] 105 | basepython = python3 106 | deps = readme_renderer 107 | commands = python setup.py check -r -s 108 | 109 | [testenv:bandit] 110 | basepython = python3 111 | deps = bandit 112 | commands = bandit -r src/pypi_parker/ 113 | 114 | # Prone to false positives: only run independently 115 | [testenv:vulture] 116 | basepython = python3 117 | deps = vulture 118 | commands = vulture src/pypi_parker/ 119 | 120 | [testenv:linters] 121 | basepython = python3 122 | deps = 123 | {[testenv:flake8]deps} 124 | {[testenv:pylint]deps} 125 | {[testenv:doc8]deps} 126 | {[testenv:readme]deps} 127 | {[testenv:bandit]deps} 128 | commands = 129 | {[testenv:flake8]commands} 130 | {[testenv:pylint]commands} 131 | {[testenv:doc8]commands} 132 | {[testenv:readme]commands} 133 | {[testenv:bandit]commands} 134 | 135 | [testenv:linters-tests] 136 | basepython = python3 137 | deps = 138 | {[testenv:flake8-tests]deps} 139 | {[testenv:pylint-tests]deps} 140 | commands = 141 | {[testenv:flake8-tests]commands} 142 | {[testenv:pylint-tests]commands} 143 | 144 | # Documentation 145 | [testenv:docs] 146 | basepython = python3 147 | deps = -rdocs/requirements.txt 148 | commands = 149 | sphinx-build -E -c docs/ -b html docs/ docs/build/html 150 | 151 | [testenv:serve-docs] 152 | basepython = python3 153 | skip_install = true 154 | changedir = docs/build/html 155 | deps = 156 | commands = 157 | python -m http.server {posargs} 158 | 159 | # Release tooling 160 | [testenv:park] 161 | basepython = python3.6 162 | deps = setuptools 163 | commands = python setup.py park 164 | 165 | [testenv:build] 166 | basepython = python3 167 | skip_install = true 168 | deps = 169 | wheel 170 | setuptools 171 | commands = 172 | python setup.py sdist bdist_wheel 173 | 174 | [testenv:test-release] 175 | basepython = python3 176 | skip_install = true 177 | deps = 178 | {[testenv:build]deps} 179 | twine 180 | commands = 181 | {[testenv:build]commands} 182 | twine upload --skip-existing --repository testpypi dist/* 183 | 184 | [testenv:release] 185 | basepython = python3 186 | skip_install = true 187 | deps = 188 | {[testenv:build]deps} 189 | twine 190 | commands = 191 | {[testenv:build]commands} 192 | twine upload --skip-existing --repository pypi dist/* 193 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # pypi-parker documentation build configuration file, created by 5 | # sphinx-quickstart on Sat Sep 30 18:30:49 2017. 6 | # 7 | # This file is execfile()d with the current directory set to its 8 | # containing dir. 9 | # 10 | # Note that not all possible configuration values are present in this 11 | # autogenerated file. 12 | # 13 | # All configuration values have a default; values that are commented out 14 | # serve to show the default. 15 | import os 16 | import re 17 | 18 | VERSION_RE = re.compile(r'''__version__ = ['"]([0-9.]+)['"]''') 19 | HERE = os.path.abspath(os.path.dirname(__file__)) 20 | 21 | 22 | def read(*args): 23 | """Reads complete file contents.""" 24 | return open(os.path.join(HERE, *args)).read() 25 | 26 | 27 | def get_release(): 28 | """Reads the release (full three-part version number) from this module.""" 29 | init = read('..', 'src', 'pypi_parker', '__init__.py') 30 | return VERSION_RE.search(init).group(1) 31 | 32 | 33 | def get_version(): 34 | """Reads the version (MAJOR.MINOR) from this module.""" 35 | release = get_release() 36 | split_version = release.split('.') 37 | if len(split_version) == 3: 38 | return '.'.join(split_version[:2]) 39 | return release 40 | 41 | # If extensions (or modules to document with autodoc) are in another directory, 42 | # add these directories to sys.path here. If the directory is relative to the 43 | # documentation root, use os.path.abspath to make it absolute, like shown here. 44 | # 45 | # import os 46 | # import sys 47 | # sys.path.insert(0, os.path.abspath('.')) 48 | 49 | 50 | # -- General configuration ------------------------------------------------ 51 | 52 | # If your documentation needs a minimal Sphinx version, state it here. 53 | # 54 | # needs_sphinx = '1.0' 55 | 56 | # Add any Sphinx extension module names here, as strings. They can be 57 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 58 | # ones. 59 | extensions = [ 60 | 'sphinx.ext.autodoc', 61 | 'sphinx_autodoc_typehints', 62 | 'sphinx.ext.autosummary', 63 | 'sphinx.ext.doctest', 64 | 'sphinx.ext.intersphinx', 65 | 'sphinx.ext.coverage', 66 | 'sphinx.ext.viewcode' 67 | ] 68 | autosummary_generate = True 69 | autoclass_content = 'both' 70 | autodoc_default_flags = ['show-inheritance', 'members'] 71 | autodoc_member_order = 'bysource' 72 | 73 | # Add any paths that contain templates here, relative to this directory. 74 | templates_path = ['_templates'] 75 | 76 | # The suffix(es) of source filenames. 77 | # You can specify multiple suffix as a list of string: 78 | # 79 | # source_suffix = ['.rst', '.md'] 80 | source_suffix = '.rst' 81 | 82 | # The master toctree document. 83 | master_doc = 'index' 84 | 85 | # General information about the project. 86 | project = 'pypi-parker' 87 | copyright = '2017, Matt Bullock' 88 | author = 'Matt Bullock' 89 | 90 | # The version info for the project you're documenting, acts as replacement for 91 | # |version| and |release|, also used in various other places throughout the 92 | # built documents. 93 | # 94 | # The short X.Y version. 95 | version = get_version() 96 | # The full version, including alpha/beta/rc tags. 97 | release = get_release() 98 | 99 | # The language for content autogenerated by Sphinx. Refer to documentation 100 | # for a list of supported languages. 101 | # 102 | # This is also used if you do content translation via gettext catalogs. 103 | # Usually you set "language" from the command line for these cases. 104 | language = None 105 | 106 | # List of patterns, relative to source directory, that match files and 107 | # directories to ignore when looking for source files. 108 | # This patterns also effect to html_static_path and html_extra_path 109 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] 110 | 111 | # The name of the Pygments (syntax highlighting) style to use. 112 | pygments_style = 'sphinx' 113 | 114 | # If true, `todo` and `todoList` produce output, else they produce nothing. 115 | todo_include_todos = False 116 | 117 | 118 | # -- Options for HTML output ---------------------------------------------- 119 | 120 | # The theme to use for HTML and HTML Help pages. See the documentation for 121 | # a list of builtin themes. 122 | # 123 | html_theme = 'sphinx_rtd_theme' 124 | 125 | # Theme options are theme-specific and customize the look and feel of a theme 126 | # further. For a list of options available for each theme, see the 127 | # documentation. 128 | # 129 | # html_theme_options = {} 130 | 131 | # Add any paths that contain custom static files (such as style sheets) here, 132 | # relative to this directory. They are copied after the builtin static files, 133 | # so a file named "default.css" will overwrite the builtin "default.css". 134 | html_static_path = ['_static'] 135 | 136 | # Custom sidebar templates, must be a dictionary that maps document names 137 | # to template names. 138 | # 139 | # This is required for the alabaster theme 140 | # refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars 141 | html_sidebars = { 142 | '**': [ 143 | 'about.html', 144 | 'navigation.html', 145 | 'relations.html', # needs 'show_related': True theme option to display 146 | 'searchbox.html', 147 | 'donate.html', 148 | ] 149 | } 150 | 151 | 152 | # -- Options for HTMLHelp output ------------------------------------------ 153 | 154 | # Output file base name for HTML help builder. 155 | htmlhelp_basename = 'pypi-parkerdoc' 156 | 157 | 158 | # -- Options for LaTeX output --------------------------------------------- 159 | 160 | latex_elements = { 161 | # The paper size ('letterpaper' or 'a4paper'). 162 | # 163 | # 'papersize': 'letterpaper', 164 | 165 | # The font size ('10pt', '11pt' or '12pt'). 166 | # 167 | # 'pointsize': '10pt', 168 | 169 | # Additional stuff for the LaTeX preamble. 170 | # 171 | # 'preamble': '', 172 | 173 | # Latex figure (float) alignment 174 | # 175 | # 'figure_align': 'htbp', 176 | } 177 | 178 | # Grouping the document tree into LaTeX files. List of tuples 179 | # (source start file, target name, title, 180 | # author, documentclass [howto, manual, or own class]). 181 | latex_documents = [ 182 | (master_doc, 'pypi-parker.tex', 'pypi-parker Documentation', 183 | 'Matt Bullock', 'manual'), 184 | ] 185 | 186 | 187 | # -- Options for manual page output --------------------------------------- 188 | 189 | # One entry per manual page. List of tuples 190 | # (source start file, name, description, authors, manual section). 191 | man_pages = [ 192 | (master_doc, 'pypi-parker', 'pypi-parker Documentation', 193 | [author], 1) 194 | ] 195 | 196 | 197 | # -- Options for Texinfo output ------------------------------------------- 198 | 199 | # Grouping the document tree into Texinfo files. List of tuples 200 | # (source start file, target name, title, author, 201 | # dir menu entry, description, category) 202 | texinfo_documents = [ 203 | (master_doc, 'pypi-parker', 'pypi-parker Documentation', 204 | author, 'pypi-parker', 'One line description of project.', 205 | 'Miscellaneous'), 206 | ] 207 | 208 | 209 | 210 | 211 | # Example configuration for intersphinx: refer to the Python standard library. 212 | intersphinx_mapping = {'https://docs.python.org/': None} 213 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ########### 2 | pypi-parker 3 | ########### 4 | 5 | .. image:: https://img.shields.io/pypi/v/pypi-parker.svg 6 | :target: https://pypi.python.org/pypi/pypi-parker 7 | :alt: Latest Version 8 | 9 | .. image:: https://readthedocs.org/projects/pypi-parker/badge/ 10 | :target: https://pypi-parker.readthedocs.io/en/stable/ 11 | :alt: Documentation Status 12 | 13 | .. image:: https://travis-ci.org/mattsb42/pypi-parker.svg?branch=master 14 | :target: https://travis-ci.org/mattsb42/pypi-parker 15 | 16 | ``pypi-parker`` lets you easily park package names on PyPI to protect users of your packages 17 | from typosquatting. 18 | 19 | `Typosquatting`_ is a problem: in general, but also on PyPI. There are efforts being taken 20 | by pypa to `protect core library names`_, but this does not (and really cannot and probably 21 | should not attempt to) help individual package owners. For example, ``reqeusts`` rather than 22 | ``requests``, or ``crytpography`` rather than ``cryptography``. Because of the self-serve 23 | nature of PyPI, individual package owners are left to their own devices to protect their users. 24 | This is not inherently a problem: in my opinion this is a reasonable balance to keep the barrier 25 | to entry for publishing PyPI package low. However, tooling should exist to make it easy for 26 | package owners to protect their users. That is what ``pypi-parker`` sets out to do. 27 | 28 | Objectives 29 | ********** 30 | * Self-serve is a good thing. Let's not try and get rid of that. Work with it instead. 31 | * Package owners should be able to easily protect users of their packages from malicious typosquatting. 32 | * It should be easy for package owners to introduce ``pypi-parker`` into their existing package builds. 33 | * Parked packages should: 34 | 35 | * fail fast and not `do anything else`_ 36 | * be self documenting, both in metadata and in source 37 | * contain functionally complete ``setup.py`` files to allow whitelisted external validators to work 38 | 39 | * The `readme_renderer`_ validator is run on each generated package before building. 40 | 41 | What does it do? 42 | **************** 43 | ``pypi-parker`` provides a custom distutils command ``park`` that interprets a provided config 44 | file to generate empty Python package source distributables. These packages will always throw 45 | an ImportError when someone tries to install them. You can customize the ImportError message 46 | to help guide users to the correct package. 47 | 48 | Using the Config File 49 | ===================== 50 | ``pypi-parker`` uses a `configparser`_ config file to determine what packages to generate and what metadata 51 | to include with each. 52 | 53 | There are two special sections: ``names`` and ``DEFAULT``. 54 | 55 | * ``DEFAULT`` : Values in ``DEFAULT`` are used if that key is not present in a package-specific section. 56 | * ``names`` : Keys in ``names`` are interpretted as package names that should all use only the values in ``DEFAULT``. 57 | 58 | Unless otherwise indicated, all key/value pairs loaded for each package are loaded directly 59 | into the ``setup`` call for that generated package. 60 | 61 | Special Packages 62 | ---------------- 63 | 64 | If you want to specify custom values for specific packages, you can add additional sections 65 | for those packages. For any sections found aside from ``DEFAULT`` and ``names``, the section 66 | name is used as the package name. 67 | 68 | Special Section Keys 69 | -------------------- 70 | 71 | * ``description_keys`` : This line-delimited value is used with ``str.format`` to build the 72 | final ``description`` value. 73 | * ``classifiers`` : If multiple lines are provided for this value, and each line will be treated 74 | as a separate entry. 75 | * ``description`` : 76 | 77 | * This value cannot contain multiple lines. 78 | * This value is also used for the ``ImportError`` message in the generated ``setup.py``. 79 | 80 | Default Values 81 | ============== 82 | * **config file name** : ``park.cfg`` 83 | * **classifiers** : ``Development Status :: 7 - Inactive`` 84 | * **description** : ``parked using pypi-parker`` 85 | * **long_description** : 86 | 87 | .. code-block:: text 88 | 89 | This package has been parked either for future use or to protect against typo misdirection. 90 | If you believe that it has been parked in error, please contact the package owner. 91 | 92 | Example 93 | ------- 94 | 95 | **park.cfg** 96 | 97 | .. code-block:: ini 98 | 99 | [DEFAULT] 100 | author: mattsb42 101 | 102 | [my-package-name] 103 | url: https://github.com/mattsb42/my-package-name 104 | description: This package is parked by {author}. See {url} for more information. 105 | description_keys: 106 | author 107 | url 108 | classifiers: 109 | Development Status :: 7 - Inactive 110 | Operating System :: OS Independent 111 | Topic :: Utilities 112 | 113 | **Generated setup.py** 114 | 115 | .. code-block:: python 116 | 117 | from setuptools import setup 118 | 119 | args = ' '.join(sys.argv).strip() 120 | if not any(args.endswith(suffix) for suffix in ['setup.py sdist', 'setup.py check -r -s']): 121 | raise ImportError('This package is parked by mattsb42. See https://github.com/mattsb42/my-package-name for more information.') 122 | 123 | setup( 124 | author='mattsb42', 125 | url='https://github.com/mattsb42/my-package-name', 126 | description='This package is parked by mattsb42. See https://github.com/mattsb42/my-package-name for more information.', 127 | classifiers=[ 128 | 'Development Status :: 7 - Inactive', 129 | 'Operating System :: OS Independent', 130 | 'Topic :: Utilities' 131 | ] 132 | ) 133 | 134 | **Install attempt** 135 | 136 | .. code-block:: sh 137 | 138 | $ pip install my-package-name 139 | Processing my-package-name 140 | Complete output from command python setup.py egg_info: 141 | Traceback (most recent call last): 142 | File "", line 1, in 143 | File "/tmp/pip-oma2zoy6-build/setup.py", line 6, in 144 | raise ImportError('This package is parked by mattsb42. See https://github.com/mattsb42/my-package-name for more information.',) 145 | ImportError: This package is parked by mattsb42. See https://github.com/mattsb42/my-package-name for more information. 146 | 147 | ---------------------------------------- 148 | Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-oma2zoy6-build/ 149 | 150 | Ok, how do I use it? 151 | ******************** 152 | 153 | 1. Install ``pypi-parker`` wherever you will be running your builds. 154 | 155 | .. code-block:: sh 156 | 157 | pip install pypi-parker 158 | 159 | 2. Define the package names you want to target in your config file. 160 | 3. Call ``setup.py`` with the ``park`` command. 161 | 162 | .. code-block:: sh 163 | 164 | python setup.py park 165 | 166 | * If you want to use a custom config file, specify it with the ``park-config`` argument. 167 | 168 | .. code-block:: sh 169 | 170 | python setup.py park --park-config={filename} 171 | 172 | 4. Upload the resulting contents of ``dist`` to your package index of choice. 173 | 174 | **Example tox configuration** 175 | 176 | .. code-block:: ini 177 | 178 | [testenv:park] 179 | basepython = python3.6 180 | deps = 181 | setuptools 182 | pypi-parker 183 | commands = python setup.py park 184 | 185 | .. _configparser: https://docs.python.org/3/library/configparser.html 186 | .. _do anything else: http://incolumitas.com/2016/06/08/typosquatting-package-managers/ 187 | .. _readme_renderer: https://github.com/pypa/readme_renderer 188 | .. _Typosquatting: https://en.wikipedia.org/wiki/Typosquatting 189 | .. _protect core library names: https://github.com/pypa/warehouse/issues/2151 190 | -------------------------------------------------------------------------------- /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 {yyyy} {name of copyright owner} 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 | --------------------------------------------------------------------------------