#!/usr/bin/env python
"""
Distutils setup file, used to install or test 'setuptools'
"""

import io
import os
import sys
import textwrap

import setuptools


here = os.path.dirname(__file__)


def require_metadata():
    "Prevent improper installs without necessary metadata. See #659"
    if not os.path.exists('setuptools.egg-info'):
        msg = "Cannot build setuptools without metadata. Run bootstrap.py"
        raise RuntimeError(msg)


def read_commands():
    command_ns = {}
    cmd_module_path = 'setuptools/command/__init__.py'
    init_path = os.path.join(here, cmd_module_path)
    with open(init_path) as init_file:
        exec(init_file.read(), command_ns)
    return command_ns['__all__']


def _gen_console_scripts():
    yield "easy_install = setuptools.command.easy_install:main"

    # Gentoo distributions manage the python-version-specific scripts
    # themselves, so those platforms define an environment variable to
    # suppress the creation of the version-specific scripts.
    var_names = (
        'SETUPTOOLS_DISABLE_VERSIONED_EASY_INSTALL_SCRIPT',
        'DISTRIBUTE_DISABLE_VERSIONED_EASY_INSTALL_SCRIPT',
    )
    if any(os.environ.get(var) not in (None, "", "0") for var in var_names):
        return
    yield ("easy_install-{shortver} = setuptools.command.easy_install:main"
        .format(shortver=sys.version[:3]))


readme_path = os.path.join(here, 'README.rst')
with io.open(readme_path, encoding='utf-8') as readme_file:
    long_description = readme_file.read()

package_data = dict(
    setuptools=['script (dev).tmpl', 'script.tmpl', 'site-patch.py'],
)

force_windows_specific_files = (
    os.environ.get("SETUPTOOLS_INSTALL_WINDOWS_SPECIFIC_FILES")
    not in (None, "", "0")
)

include_windows_files = (
    sys.platform == 'win32' or
    os.name == 'java' and os._name == 'nt' or
    force_windows_specific_files
)

if include_windows_files:
    package_data.setdefault('setuptools', []).extend(['*.exe'])
    package_data.setdefault('setuptools.command', []).extend(['*.xml'])

needs_pytest = set(['ptr', 'pytest', 'test']).intersection(sys.argv)
pytest_runner = ['pytest-runner'] if needs_pytest else []
needs_wheel = set(['release', 'bdist_wheel']).intersection(sys.argv)
wheel = ['wheel'] if needs_wheel else []


def pypi_link(pkg_filename):
    """
    Given the filename, including md5 fragment, construct the
    dependency link for PyPI.
    """
    root = 'https://pypi.python.org/packages/source'
    name, sep, rest = pkg_filename.partition('-')
    parts = root, name[0], name, pkg_filename
    return '/'.join(parts)


setup_params = dict(
    name="setuptools",
    version="25.0.1",
    description="Easily download, build, install, upgrade, and uninstall "
        "Python packages",
    author="Python Packaging Authority",
    author_email="distutils-sig@python.org",
    long_description=long_description,
    keywords="CPAN PyPI distutils eggs package management",
    url="https://github.com/pypa/setuptools",
    src_root=None,
    packages=setuptools.find_packages(exclude=['*.tests']),
    package_data=package_data,

    py_modules=['easy_install'],

    zip_safe=True,

    entry_points={
        "distutils.commands": [
            "%(cmd)s = setuptools.command.%(cmd)s:%(cmd)s" % locals()
            for cmd in read_commands()
        ],
        "distutils.setup_keywords": [
            "eager_resources        = setuptools.dist:assert_string_list",
            "namespace_packages     = setuptools.dist:check_nsp",
            "extras_require         = setuptools.dist:check_extras",
            "install_requires       = setuptools.dist:check_requirements",
            "tests_require          = setuptools.dist:check_requirements",
            "setup_requires         = setuptools.dist:check_requirements",
            "python_requires        = setuptools.dist:check_specifier",
            "entry_points           = setuptools.dist:check_entry_points",
            "test_suite             = setuptools.dist:check_test_suite",
            "zip_safe               = setuptools.dist:assert_bool",
            "package_data           = setuptools.dist:check_package_data",
            "exclude_package_data   = setuptools.dist:check_package_data",
            "include_package_data   = setuptools.dist:assert_bool",
            "packages               = setuptools.dist:check_packages",
            "dependency_links       = setuptools.dist:assert_string_list",
            "test_loader            = setuptools.dist:check_importable",
            "test_runner            = setuptools.dist:check_importable",
            "use_2to3               = setuptools.dist:assert_bool",
            "convert_2to3_doctests  = setuptools.dist:assert_string_list",
            "use_2to3_fixers        = setuptools.dist:assert_string_list",
            "use_2to3_exclude_fixers = setuptools.dist:assert_string_list",
        ],
        "egg_info.writers": [
            "PKG-INFO = setuptools.command.egg_info:write_pkg_info",
            "requires.txt = setuptools.command.egg_info:write_requirements",
            "entry_points.txt = setuptools.command.egg_info:write_entries",
            "eager_resources.txt = setuptools.command.egg_info:overwrite_arg",
            "namespace_packages.txt = setuptools.command.egg_info:overwrite_arg",
            "top_level.txt = setuptools.command.egg_info:write_toplevel_names",
            "depends.txt = setuptools.command.egg_info:warn_depends_obsolete",
            "dependency_links.txt = setuptools.command.egg_info:overwrite_arg",
        ],
        "console_scripts": list(_gen_console_scripts()),

        "setuptools.installation":
            ['eggsecutable = setuptools.command.easy_install:bootstrap'],
    },


    classifiers=textwrap.dedent("""
        Development Status :: 5 - Production/Stable
        Intended Audience :: Developers
        License :: OSI Approved :: MIT License
        Operating System :: OS Independent
        Programming Language :: Python :: 2.6
        Programming Language :: Python :: 2.7
        Programming Language :: Python :: 3
        Programming Language :: Python :: 3.3
        Programming Language :: Python :: 3.4
        Programming Language :: Python :: 3.5
        Topic :: Software Development :: Libraries :: Python Modules
        Topic :: System :: Archiving :: Packaging
        Topic :: System :: Systems Administration
        Topic :: Utilities
        """).strip().splitlines(),
    extras_require={
        "ssl:sys_platform=='win32'": "wincertstore==0.2",
        "certs": "certifi==2016.2.28",
    },
    dependency_links=[
        pypi_link(
            'certifi-2016.2.28.tar.gz#md5=5d672aa766e1f773c75cfeccd02d3650',
        ),
        pypi_link(
            'wincertstore-0.2.zip#md5=ae728f2f007185648d0c7a8679b361e2',
        ),
    ],
    scripts=[],
    tests_require=[
        'setuptools[ssl]',
        'pytest-flake8',
        # workaround for pytest-flake8 #7
        'flake8<3dev',
        'pytest>=2.8',
    ] + (['mock'] if sys.version_info[:2] < (3, 3) else []),
    setup_requires=[
    ] + pytest_runner + wheel,
)

if __name__ == '__main__':
    # allow setup.py to run from another directory
    here and os.path.chdir(here)
    require_metadata()
    dist = setuptools.setup(**setup_params)

setup.py
#!/usr/bin/env python
"""
Distutils setup file, used to install or test 'setuptools'
"""

import io
import os
import sys
import textwrap

import setuptools


here = os.path.dirname(__file__)


def require_metadata():
    "Prevent improper installs without necessary metadata. See #659"
    if not os.path.exists('setuptools.egg-info'):
        msg = "Cannot build setuptools without metadata. Run bootstrap.py"
        raise RuntimeError(msg)


def read_commands():
    command_ns = {}
    cmd_module_path = 'setuptools/command/__init__.py'
    init_path = os.path.join(here, cmd_module_path)
    with open(init_path) as init_file:
        exec(init_file.read(), command_ns)
    return command_ns['__all__']


def _gen_console_scripts():
    yield "easy_install = setuptools.command.easy_install:main"

    # Gentoo distributions manage the python-version-specific scripts
    # themselves, so those platforms define an environment variable to
    # suppress the creation of the version-specific scripts.
    var_names = (
        'SETUPTOOLS_DISABLE_VERSIONED_EASY_INSTALL_SCRIPT',
        'DISTRIBUTE_DISABLE_VERSIONED_EASY_INSTALL_SCRIPT',
    )
    if any(os.environ.get(var) not in (None, "", "0") for var in var_names):
        return
    yield ("easy_install-{shortver} = setuptools.command.easy_install:main"
        .format(shortver=sys.version[:3]))


readme_path = os.path.join(here, 'README.rst')
with io.open(readme_path, encoding='utf-8') as readme_file:
    long_description = readme_file.read()

package_data = dict(
    setuptools=['script (dev).tmpl', 'script.tmpl', 'site-patch.py'],
)

force_windows_specific_files = (
    os.environ.get("SETUPTOOLS_INSTALL_WINDOWS_SPECIFIC_FILES")
    not in (None, "", "0")
)

include_windows_files = (
    sys.platform == 'win32' or
    os.name == 'java' and os._name == 'nt' or
    force_windows_specific_files
)

if include_windows_files:
    package_data.setdefault('setuptools', []).extend(['*.exe'])
    package_data.setdefault('setuptools.command', []).extend(['*.xml'])

needs_pytest = set(['ptr', 'pytest', 'test']).intersection(sys.argv)
pytest_runner = ['pytest-runner'] if needs_pytest else []
needs_wheel = set(['release', 'bdist_wheel']).intersection(sys.argv)
wheel = ['wheel'] if needs_wheel else []


def pypi_link(pkg_filename):
    """
    Given the filename, including md5 fragment, construct the
    dependency link for PyPI.
    """
    root = 'https://pypi.python.org/packages/source'
    name, sep, rest = pkg_filename.partition('-')
    parts = root, name[0], name, pkg_filename
    return '/'.join(parts)


setup_params = dict(
    name="setuptools",
    version="25.0.1",
    description="Easily download, build, install, upgrade, and uninstall "
        "Python packages",
    author="Python Packaging Authority",
    author_email="distutils-sig@python.org",
    long_description=long_description,
    keywords="CPAN PyPI distutils eggs package management",
    url="https://github.com/pypa/setuptools",
    src_root=None,
    packages=setuptools.find_packages(exclude=['*.tests']),
    package_data=package_data,

    py_modules=['easy_install'],

    zip_safe=True,

    entry_points={
        "distutils.commands": [
            "%(cmd)s = setuptools.command.%(cmd)s:%(cmd)s" % locals()
            for cmd in read_commands()
        ],
        "distutils.setup_keywords": [
            "eager_resources        = setuptools.dist:assert_string_list",
            "namespace_packages     = setuptools.dist:check_nsp",
            "extras_require         = setuptools.dist:check_extras",
            "install_requires       = setuptools.dist:check_requirements",
            "tests_require          = setuptools.dist:check_requirements",
            "setup_requires         = setuptools.dist:check_requirements",
            "python_requires        = setuptools.dist:check_specifier",
            "entry_points           = setuptools.dist:check_entry_points",
            "test_suite             = setuptools.dist:check_test_suite",
            "zip_safe               = setuptools.dist:assert_bool",
            "package_data           = setuptools.dist:check_package_data",
            "exclude_package_data   = setuptools.dist:check_package_data",
            "include_package_data   = setuptools.dist:assert_bool",
            "packages               = setuptools.dist:check_packages",
            "dependency_links       = setuptools.dist:assert_string_list",
            "test_loader            = setuptools.dist:check_importable",
            "test_runner            = setuptools.dist:check_importable",
            "use_2to3               = setuptools.dist:assert_bool",
            "convert_2to3_doctests  = setuptools.dist:assert_string_list",
            "use_2to3_fixers        = setuptools.dist:assert_string_list",
            "use_2to3_exclude_fixers = setuptools.dist:assert_string_list",
        ],
        "egg_info.writers": [
            "PKG-INFO = setuptools.command.egg_info:write_pkg_info",
            "requires.txt = setuptools.command.egg_info:write_requirements",
            "entry_points.txt = setuptools.command.egg_info:write_entries",
            "eager_resources.txt = setuptools.command.egg_info:overwrite_arg",
            "namespace_packages.txt = setuptools.command.egg_info:overwrite_arg",
            "top_level.txt = setuptools.command.egg_info:write_toplevel_names",
            "depends.txt = setuptools.command.egg_info:warn_depends_obsolete",
            "dependency_links.txt = setuptools.command.egg_info:overwrite_arg",
        ],
        "console_scripts": list(_gen_console_scripts()),

        "setuptools.installation":
            ['eggsecutable = setuptools.command.easy_install:bootstrap'],
    },


    classifiers=textwrap.dedent("""
        Development Status :: 5 - Production/Stable
        Intended Audience :: Developers
        License :: OSI Approved :: MIT License
        Operating System :: OS Independent
        Programming Language :: Python :: 2.6
        Programming Language :: Python :: 2.7
        Programming Language :: Python :: 3
        Programming Language :: Python :: 3.3
        Programming Language :: Python :: 3.4
        Programming Language :: Python :: 3.5
        Topic :: Software Development :: Libraries :: Python Modules
        Topic :: System :: Archiving :: Packaging
        Topic :: System :: Systems Administration
        Topic :: Utilities
        """).strip().splitlines(),
    extras_require={
        "ssl:sys_platform=='win32'": "wincertstore==0.2",
        "certs": "certifi==2016.2.28",
    },
    dependency_links=[
        pypi_link(
            'certifi-2016.2.28.tar.gz#md5=5d672aa766e1f773c75cfeccd02d3650',
        ),
        pypi_link(
            'wincertstore-0.2.zip#md5=ae728f2f007185648d0c7a8679b361e2',
        ),
    ],
    scripts=[],
    tests_require=[
        'setuptools[ssl]',
        'pytest-flake8',
        # workaround for pytest-flake8 #7
        'flake8<3dev',
        'pytest>=2.8',
    ] + (['mock'] if sys.version_info[:2] < (3, 3) else []),
    setup_requires=[
    ] + pytest_runner + wheel,
)

if __name__ == '__main__':
    # allow setup.py to run from another directory
    here and os.chdir(here)
    require_metadata()
    dist = setuptools.setup(**setup_params)

setup.py
diff --git a/setup.py b/setup.py
index af5e3ac418..e4d85b0b3f 100755
--- a/setup.py
+++ b/setup.py
@@ -191,6 +191,6 @@ def pypi_link(pkg_filename):
 
 if __name__ == '__main__':
     # allow setup.py to run from another directory
-    here and os.path.chdir(here)
+    here and os.chdir(here)
     require_metadata()
     dist = setuptools.setup(**setup_params)

AttributeError: 'module' object has no attribute 'chdir' in 25.0.1
The new `setuptools == 25.0.1` just failed on our CI with `AttributeError: 'module' object has no attribute 'chdir'`.

The new expression [`here and os.path.chdir(here)`](https://github.com/pypa/setuptools/blob/21ab99e53f0c263a2210cf51525d6edcae1ae9a7/setup.py#L194) in `setup.py` was probably meant to use `os.chdir()`, since `os.path` has no `chdir()`.

_(Note: Lots of buildout related noise in the traceback, but I didn't want to truncate it and risk omitting relevant info)_

```
Getting distribution for 'setuptools'.
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/var/lib/jenkins/zope/eggs/setuptools-18.2-py2.7.egg/setuptools/command/easy_install.py", line 2245, in main
    distclass=DistributionWithoutHelpCommands, **kw
  File "/usr/local/python/2.7.10/lib/python2.7/distutils/core.py", line 151, in setup
    dist.run_commands()
  File "/usr/local/python/2.7.10/lib/python2.7/distutils/dist.py", line 953, in run_commands
    self.run_command(cmd)
  File "/usr/local/python/2.7.10/lib/python2.7/distutils/dist.py", line 972, in run_command
    cmd_obj.run()
  File "/var/lib/jenkins/zope/eggs/setuptools-18.2-py2.7.egg/setuptools/command/easy_install.py", line 380, in run
    self.easy_install(spec, not self.no_deps)
  File "/var/lib/jenkins/zope/eggs/setuptools-18.2-py2.7.egg/setuptools/command/easy_install.py", line 610, in easy_install
    return self.install_item(None, spec, tmpdir, deps, True)
  File "/var/lib/jenkins/zope/eggs/setuptools-18.2-py2.7.egg/setuptools/command/easy_install.py", line 659, in install_item
    dists = self.install_eggs(spec, download, tmpdir)
  File "/var/lib/jenkins/zope/eggs/setuptools-18.2-py2.7.egg/setuptools/command/easy_install.py", line 842, in install_eggs
    return self.build_and_install(setup_script, setup_base)
  File "/var/lib/jenkins/zope/eggs/setuptools-18.2-py2.7.egg/setuptools/command/easy_install.py", line 1070, in build_and_install
    self.run_setup(setup_script, setup_base, args)
  File "/var/lib/jenkins/zope/eggs/setuptools-18.2-py2.7.egg/setuptools/command/easy_install.py", line 1056, in run_setup
    run_setup(setup_script, args)
  File "/var/lib/jenkins/zope/eggs/setuptools-18.2-py2.7.egg/setuptools/sandbox.py", line 240, in run_setup
    raise
  File "/usr/local/python/2.7.10/lib/python2.7/contextlib.py", line 35, in __exit__
    self.gen.throw(type, value, traceback)
  File "/var/lib/jenkins/zope/eggs/setuptools-18.2-py2.7.egg/setuptools/sandbox.py", line 193, in setup_context
    yield
  File "/usr/local/python/2.7.10/lib/python2.7/contextlib.py", line 35, in __exit__
    self.gen.throw(type, value, traceback)
  File "/var/lib/jenkins/zope/eggs/setuptools-18.2-py2.7.egg/setuptools/sandbox.py", line 164, in save_modules
    saved_exc.resume()
  File "/var/lib/jenkins/zope/eggs/setuptools-18.2-py2.7.egg/setuptools/sandbox.py", line 139, in resume
    compat.reraise(type, exc, self._tb)
  File "/var/lib/jenkins/zope/eggs/setuptools-18.2-py2.7.egg/setuptools/sandbox.py", line 152, in save_modules
    yield saved
  File "/var/lib/jenkins/zope/eggs/setuptools-18.2-py2.7.egg/setuptools/sandbox.py", line 193, in setup_context
    yield
  File "/var/lib/jenkins/zope/eggs/setuptools-18.2-py2.7.egg/setuptools/sandbox.py", line 237, in run_setup
    DirectorySandbox(setup_dir).run(runner)
  File "/var/lib/jenkins/zope/eggs/setuptools-18.2-py2.7.egg/setuptools/sandbox.py", line 267, in run
    return func()
  File "/var/lib/jenkins/zope/eggs/setuptools-18.2-py2.7.egg/setuptools/sandbox.py", line 236, in runner
    _execfile(setup_script, ns)
  File "/var/lib/jenkins/zope/eggs/setuptools-18.2-py2.7.egg/setuptools/sandbox.py", line 46, in _execfile
    exec(code, globals, locals)
  File "/tmp/easy_install-6d2nJI/setuptools-25.0.1/setup.py", line 194, in <module>

AttributeError: 'module' object has no attribute 'chdir'
```

