def testParseMap(self):
     m = EntryPoint.parse_map({'xyz':self.submap_str})
     self.checkSubMap(m['xyz'])
     self.assertEqual(list(m.keys()),['xyz'])
     m = EntryPoint.parse_map("[xyz]\n"+self.submap_str)
     self.checkSubMap(m['xyz'])
     self.assertEqual(list(m.keys()),['xyz'])
     self.assertRaises(ValueError, EntryPoint.parse_map, ["[xyz]", "[xyz]"])
     self.assertRaises(ValueError, EntryPoint.parse_map, self.submap_str)
 def testParseMap(self):
     m = EntryPoint.parse_map({'xyz':self.submap_str})
     self.checkSubMap(m['xyz'])
     self.assertEqual(list(m.keys()),['xyz'])
     m = EntryPoint.parse_map("[xyz]\n"+self.submap_str)
     self.checkSubMap(m['xyz'])
     self.assertEqual(list(m.keys()),['xyz'])
     self.assertRaises(ValueError, EntryPoint.parse_map, ["[xyz]", "[xyz]"])
     self.assertRaises(ValueError, EntryPoint.parse_map, self.submap_str)
Exemple #3
0
    def run(self):
        """
        Generate man pages for the scripts defined in distutils setup().

        The cli application is gathered from the setuptools setup()
        function in setup.py.

        The generated man pages are written to files in the directory given
        by ``--target``.
        """
        eps = EntryPoint.parse_map(self.distribution.entry_points or '')

        if 'console_scripts' not in eps or not eps['console_scripts']:
            raise DistutilsSetupError('No entry points defined in setup()')

        console_scripts = [(k, v) for k, v in eps['console_scripts'].items()]
        # FIXME: create own setup() attribute for CLI script configuration
        for name, entry_point in console_scripts:
            self.announce('Load entry point {0}'.format(name), level=2)
            cli = entry_point.resolve()
            self.announce('Generate man pages for {0}'.format(name), level=2)
            write_man_pages(name,
                            cli,
                            version=self.version,
                            target_dir=self.target)
Exemple #4
0
    def gen_header(self):
        epm = EntryPoint.parse_map(self.distribution.entry_points or "")
        ep = epm.get("setuptools.installation", {}).get("eggsecutable")
        if ep is None:
            return "w"  # not an eggsecutable, do it the usual way.

        if not ep.attrs or ep.extras:
            raise DistutilsSetupError("eggsecutable entry point (%r) cannot have 'extras' " "or refer to a module" % (ep,))

        pyver = sys.version[:3]
        pkg = ep.module_name
        full = ".".join(ep.attrs)
        base = ep.attrs[0]
        basename = os.path.basename(self.egg_output)

        header = (
            "#!/bin/sh\n"
            'if [ `basename $0` = "%(basename)s" ]\n'
            'then exec python%(pyver)s -c "'
            "import sys, os; sys.path.insert(0, os.path.abspath('$0')); "
            "from %(pkg)s import %(base)s; sys.exit(%(full)s())"
            '" "$@"\n'
            "else\n"
            "  echo $0 is not the correct name for this egg file.\n"
            "  echo Please rename it back to %(basename)s and try again.\n"
            "  exec false\n"
            "fi\n"
        ) % locals()

        if not self.dry_run:
            mkpath(os.path.dirname(self.egg_output), dry_run=self.dry_run)
            f = open(self.egg_output, "w")
            f.write(header)
            f.close()
        return "a"
Exemple #5
0
def _read_entry_points(ep_contents):
    ep_map = EntryPoint.parse_map(ep_contents)

    for _, epgroup in ep_map.iteritems():
        for epname, ep in epgroup.iteritems():
            epgroup[epname] = str(ep)

    return ep_map
def parse_entry_points(fp):
    return {
        gr: {
            k: {
                "module": e.module_name,
                "attr": '.'.join(e.attrs) if e.attrs else None,
                "extras": list(e.extras),
            }
            for k, e in eps.items()
        }
        for gr, eps in EntryPoint.parse_map(fp).items()
    }
def get_wex_entry_points_from_cwd():
    try:
        with open(os.path.join(os.getcwd(), 'entry_points.txt')) as txt:
            entry_point_map = EntryPoint.parse_map(txt.read())
        entry_points = {str(ep): ep for ep in entry_point_map[GROUP].values()}
        if os.getcwd() not in sys.path:
            sys.path.insert(0, os.getcwd())
    except IOError as exc:
        if exc.errno != errno.ENOENT:
            raise
        entry_points = {}

    return entry_points
Exemple #8
0
def get_wex_entry_points_from_cwd():
    try:
        with open(os.path.join(os.getcwd(), 'entry_points.txt')) as txt:
            entry_point_map = EntryPoint.parse_map(txt.read())
        entry_points = dict(
            (str(ep), ep) for ep in entry_point_map.get(GROUP, {}).values())
        if os.getcwd() not in sys.path:
            sys.path.insert(0, os.getcwd())
    except IOError as exc:
        if exc.errno != errno.ENOENT:
            raise
        entry_points = {}

    return entry_points
 def get_theme_dir(self):
     ''' Validate theme option and return path to theme's root obtained from entry point. '''
     entry_points = EntryPoint.parse_map(self.distribution.entry_points,
                                         self.distribution)
     if 'mkdocs.themes' not in entry_points:
         raise DistutilsOptionError(
             "no mkdocs.themes are defined in entry_points")
     if self.theme is None and len(entry_points['mkdocs.themes']) == 1:
         # Default to the only theme defined in entry_points as none specified.
         self.theme = tuple(entry_points['mkdocs.themes'].keys())[0]
     if self.theme not in entry_points['mkdocs.themes']:
         raise DistutilsOptionError(
             "you must specify a valid theme name to work on")
     theme = entry_points['mkdocs.themes'][self.theme]
     return path.dirname(theme.resolve().__file__)
Exemple #10
0
 def run(self):
     install_scripts.run(self)
     orig_install_dir = self.install_dir
     self.install_dir = self.install_agents
     eps = EntryPoint.parse_map(self.distribution.entry_points)
     header = get_script_header('')
     for ep in eps.get('resource_agents', {}).values():
         filename = os.path.join(*(ep.name.split('.')))
         contents = header + self.agent_template % {
             'module': ep.module_name,
             'class': ep.attrs[0],
             'method': '.'.join(ep.attrs),
         }
         self.write_script(filename, contents)
     self.install_dir = orig_install_dir
 def testParseMap(self):
     m = EntryPoint.parse_map({'xyz': self.submap_str})
     self.checkSubMap(m['xyz'])
     assert list(m.keys()) == ['xyz']
     m = EntryPoint.parse_map("[xyz]\n" + self.submap_str)
     self.checkSubMap(m['xyz'])
     assert list(m.keys()) == ['xyz']
     with pytest.raises(ValueError):
         EntryPoint.parse_map(["[xyz]", "[xyz]"])
     with pytest.raises(ValueError):
         EntryPoint.parse_map(self.submap_str)
Exemple #12
0
 def testParseMap(self):
     m = EntryPoint.parse_map({'xyz': self.submap_str})
     self.checkSubMap(m['xyz'])
     assert list(m.keys()) == ['xyz']
     m = EntryPoint.parse_map("[xyz]\n" + self.submap_str)
     self.checkSubMap(m['xyz'])
     assert list(m.keys()) == ['xyz']
     with pytest.raises(ValueError):
         EntryPoint.parse_map(["[xyz]", "[xyz]"])
     with pytest.raises(ValueError):
         EntryPoint.parse_map(self.submap_str)
Exemple #13
0
    def false_setup(*args, **kwargs):
        cmdline = []
        setupdir = os.path.dirname(globals['__file__'])
        storepath = os.path.join(setupdir, 'setupargs-pypicontents.json')
        banned_options = [
            'setup_requires', 'test_requires', 'conda_buildnum', 'd2to1',
            'distclass', 'email', 'entry_points', 'executables', 'home_page',
            'include_package_data', 'install_requires', 'licesne',
            'namespace_packages', 'pbr', 'platform', 'use_2to3',
            'use_scm_version'
        ]

        from distutils.dist import Distribution
        from distutils.command.build_py import build_py
        from pkg_resources import EntryPoint

        for opt in banned_options:
            kwargs.pop(opt, None)

        kwargs.update({'script_name': globals['__file__'], 'script_args': []})

        bpy = build_py(Distribution(kwargs))
        bpy.finalize_options()
        _bpy_mods = bpy.find_all_modules()
        _join_mods = ['.'.join([p, m]).strip('.') for p, m, f in _bpy_mods]
        modules = [
            '.'.join(m.split('.')[:-1])
            if m.endswith('.__init__') or m.endswith('.__main__') else m
            for m in _join_mods
        ]

        if 'scripts' in kwargs:
            cmdline.extend([os.path.basename(s) for s in kwargs['scripts']])
        if 'entry_points' in kwargs:
            entrymap = EntryPoint.parse_map(kwargs['entry_points'])
            if 'console_scripts' in entrymap:
                cmdline.extend(entrymap['console_scripts'].keys())

        with open(storepath, 'w') as store:
            store.write(
                u(
                    json.dumps({
                        'modules': sorted(set(modules)),
                        'cmdline': sorted(set(cmdline))
                    })))
Exemple #14
0
    def gen_header(self):
        epm = EntryPoint.parse_map(self.distribution.entry_points or '')
        ep = epm.get('setuptools.installation', {}).get('eggsecutable')
        if ep is None:
            return 'w'  # not an eggsecutable, do it the usual way.

        warnings.warn(
            "Eggsecutables are deprecated and will be removed in a future "
            "version.",
            SetuptoolsDeprecationWarning
        )

        if not ep.attrs or ep.extras:
            raise DistutilsSetupError(
                "eggsecutable entry point (%r) cannot have 'extras' "
                "or refer to a module" % (ep,)
            )

        pyver = '{}.{}'.format(*sys.version_info)
        pkg = ep.module_name
        full = '.'.join(ep.attrs)
        base = ep.attrs[0]
        basename = os.path.basename(self.egg_output)

        header = (
            "#!/bin/sh\n"
            'if [ `basename $0` = "%(basename)s" ]\n'
            'then exec python%(pyver)s -c "'
            "import sys, os; sys.path.insert(0, os.path.abspath('$0')); "
            "from %(pkg)s import %(base)s; sys.exit(%(full)s())"
            '" "$@"\n'
            'else\n'
            '  echo $0 is not the correct name for this egg file.\n'
            '  echo Please rename it back to %(basename)s and try again.\n'
            '  exec false\n'
            'fi\n'
        ) % locals()

        if not self.dry_run:
            mkpath(os.path.dirname(self.egg_output), dry_run=self.dry_run)
            f = open(self.egg_output, 'w')
            f.write(header)
            f.close()
        return 'a'
    def gen_header(self):
        epm = EntryPoint.parse_map(self.distribution.entry_points or '')
        ep = epm.get('setuptools.installation',{}).get('eggsecutable')
        if ep is None:
            return 'w'  # not an eggsecutable, do it the usual way.

        if not ep.attrs or ep.extras:
            raise DistutilsSetupError(
                "eggsecutable entry point (%r) cannot have 'extras' "
                "or refer to a module" % (ep,)
            )

        pyver = sys.version[:3]
        pkg = ep.module_name
        full = '.'.join(ep.attrs)
        base = ep.attrs[0]
        basename = os.path.basename(self.egg_output)

        header = (
            "#!/bin/sh\n"
            'if [ `basename $0` = "%(basename)s" ]\n'
            'then exec python%(pyver)s -c "'
            "import sys, os; sys.path.insert(0, os.path.abspath('$0')); "
            "from %(pkg)s import %(base)s; sys.exit(%(full)s())"
            '" "$@"\n'
            'else\n'
            '  echo $0 is not the correct name for this egg file.\n'
            '  echo Please rename it back to %(basename)s and try again.\n'
            '  exec false\n'
            'fi\n'

        ) % locals()

        if not self.dry_run:
            mkpath(os.path.dirname(self.egg_output), dry_run=self.dry_run)
            f = open(self.egg_output, 'w')
            f.write(header)
            f.close()
        return 'a'
Exemple #16
0
    def false_setup(*args, **kwargs):
        cmdline = []
        setupdir = os.path.dirname(globals['__file__'])
        storepath = os.path.join(setupdir, 'setupargs-pypicontents.json')
        banned_options = ['setup_requires', 'test_requires', 'conda_buildnum',
                          'd2to1', 'distclass', 'email', 'entry_points',
                          'executables', 'home_page', 'include_package_data',
                          'install_requires', 'licesne', 'namespace_packages',
                          'pbr', 'platform', 'use_2to3', 'use_scm_version']

        from distutils.dist import Distribution
        from distutils.command.build_py import build_py
        from pkg_resources import EntryPoint

        for opt in banned_options:
            kwargs.pop(opt, None)

        kwargs.update({'script_name': globals['__file__'],
                       'script_args': []})

        bpy = build_py(Distribution(kwargs))
        bpy.finalize_options()
        _bpy_mods = bpy.find_all_modules()
        _join_mods = ['.'.join([p, m]).strip('.') for p, m, f in _bpy_mods]
        modules = ['.'.join(m.split('.')[:-1])
                   if m.endswith('.__init__') or m.endswith('.__main__')
                   else m for m in _join_mods]

        if 'scripts' in kwargs:
            cmdline.extend([os.path.basename(s) for s in kwargs['scripts']])
        if 'entry_points' in kwargs:
            entrymap = EntryPoint.parse_map(kwargs['entry_points'])
            if 'console_scripts' in entrymap:
                cmdline.extend(entrymap['console_scripts'].keys())

        with open(storepath, 'w') as store:
            store.write(u(json.dumps({'modules': sorted(set(modules)),
                                      'cmdline': sorted(set(cmdline))})))
Exemple #17
0
def test_plugin_entrypoint_is_loadable():
    ep_path = os.path.join(ep, 'Some_plugin.egg-info', 'entry_points.txt')
    ep_file = open(ep_path, 'r')
    lines = ep_file.readlines()
    ep_file.close()
    assert EntryPoint.parse_map(lines)
Exemple #18
0
    def run(self):
        entry_points = {}
        gui_scripts = []

        entry_points_map = EntryPoint.parse_map(self.distribution.entry_points)
        for entry_key in entry_keys:
            with suppress(KeyError):
                entry_points.update(entry_points_map[entry_key])
                if entry_key == 'gui_scripts':
                    gui_scripts.extend(entry_points_map[entry_key].keys())

        try:
            options = {}
            for key, value in dict(
                    self.distribution.command_options['build_exe']).items():
                options[key] = value[1]
        except (KeyError, TypeError):
            options = {}

        scripts = copy(self.distribution.scripts)
        self.distribution.scripts = []
        for required_directory in [self.build_temp, self.build_exe]:
            shutil.rmtree(required_directory, ignore_errors=True)
            os.makedirs(required_directory, exist_ok=True)

        for entry_point in entry_points.values():
            scripts.append(self._generate_script(entry_point, self.build_temp))

        lib_dirs = ['lib', 'lib{}'.format(build_dir()[3:])]
        for lib_dir in lib_dirs:
            shutil.rmtree(
                os.path.join(self.build_base, lib_dir), ignore_errors=True)

        self.run_command('build')

        for default_option in ['pathex', 'hiddenimports', 'binaries']:
            options.setdefault(default_option, [])

        # by convention, all paths appended to py_options must be absolute
        options['hiddenimports'].extend(self.distribution.install_requires)
        for lib_dir in lib_dirs:
            if os.path.isdir(os.path.join(self.build_base, lib_dir)):
                options['pathex'].append(
                    os.path.abspath(os.path.join(self.build_base, lib_dir)))

        if not options['pathex']:
            raise ValueError('Unable to find lib directory!')

        if version.parse(sys.version[0:3]) >= version.parse('3.4'):
            for package in self.distribution.packages:
                options['hiddenimports'].extend(collect_submodules(package))

        options['specpath'] = os.path.abspath(self.build_temp)
        options['pathex'].append(os.path.abspath(self.build_temp))

        for i, tp in enumerate(options.setdefault('datas', [])):
            options['datas'][i][0] = os.path.abspath(options['datas'][i][0])

        if not self.optimize_imports:
            self._discover_dependencies(options)

        executables = []
        for script, executable in zip(scripts, self.executables):
            executable = executable or Executable(script)
            executable.script = script
            executable._options = dict(options, **executable.options)
            executable._options['name'] = '.'.join(
                ntpath.basename(script).split('.')[:-1])
            if executable._options['name'] in gui_scripts:
                executable._options['console'] = False

            executables.append(executable)

        for executable in executables:
            rename_script(executable)

        names = [executable.options['name'] for executable in executables]
        for executable in executables:
            self._freeze(executable, self.build_temp, self.build_exe)

        for name in names[1:]:
            move_tree(
                os.path.join(self.build_exe, name),
                os.path.join(self.build_exe, names[0]))

        move_tree(os.path.join(self.build_exe, names[0]), self.build_exe)

        shutil.rmtree(self.build_temp, ignore_errors=True)

        # TODO: Compare file hashes to make sure we haven't replaced files with a different version
        for name in names:
            shutil.rmtree(
                os.path.join(self.build_exe, name), ignore_errors=True)
Exemple #19
0
def test_plugin_entrypoint_is_loadable():
    epfile = os.path.join(ep, 'Some_plugin.egg-info', 'entry_points.txt')
    assert EntryPoint.parse_map(open(epfile, 'r').readlines())
Exemple #20
0
 def gen_header(self):
     epm = EntryPoint.parse_map(self.distribution.entry_points or '')
     ep = epm.get('setuptools.installation',{}).get('eggsecutable')
Exemple #21
0
 def add_entry_points(self, entry_map_section):
     """Add entry points."""
     recursive_merge(
         self.dist.get_entry_map(),
         EntryPoint.parse_map(entry_map_section, self.dist))
Exemple #22
0
 def gen_header(self):
     epm = EntryPoint.parse_map(self.distribution.entry_points or '')
     ep = epm.get('setuptools.installation', {}).get('eggsecutable')
     if ep is None:
         return 'w'  # not an eggsecutable, do it the usual way.
Exemple #23
0
    def run(self):
        entry_points = {}
        gui_scripts = []

        entry_points_map = EntryPoint.parse_map(self.distribution.entry_points)
        for entry_key in entry_keys:
            with suppress(KeyError):
                entry_points.update(entry_points_map[entry_key])
                if entry_key == 'gui_scripts':
                    gui_scripts.extend(entry_points_map[entry_key].keys())

        try:
            options = {}
            for key, value in dict(
                    self.distribution.command_options['build_exe']).items():
                options[key] = value[1]
        except (KeyError, TypeError):
            options = {}

        scripts = copy(self.distribution.scripts)
        self.distribution.scripts = []

        workpath = os.path.join(self.build_temp, 'workpath')
        distpath = os.path.join(self.build_temp, 'distpath')

        for required_directory in [distpath, self.build_exe, workpath]:
            shutil.rmtree(required_directory, ignore_errors=True)
            try:
                os.makedirs(
                    required_directory
                )  # exist_ok not available in py2, so we just catch the exception
            except OSError as exc:
                if exc.errno == errno.EEXIST and os.path.isdir(
                        required_directory):
                    pass
                else:
                    raise

        for entry_point in entry_points.values():
            scripts.append(self._generate_script(entry_point, workpath))

        lib_dirs = ['lib', 'lib{}'.format(build_dir()[3:])]
        for lib_dir in lib_dirs:
            shutil.rmtree(os.path.join(self.build_base, lib_dir),
                          ignore_errors=True)

        self.run_command('build')

        for default_option in [
                'pathex',
                'hiddenimports',
                'binaries',
                'collect_all',
                'collect_binaries',
                'collect_data',
                'collect_submodules',
                'copy_metadata',
                'recursive_copy_metadata',
        ]:
            options.setdefault(default_option, [])

        # by convention, all paths appended to py_options must be absolute
        for lib_dir in lib_dirs:
            if os.path.isdir(os.path.join(self.build_base, lib_dir)):
                options['pathex'].append(
                    os.path.abspath(os.path.join(self.build_base, lib_dir)))

        if not options['pathex']:
            raise ValueError('Unable to find lib directory!')

        options['specpath'] = os.path.abspath(workpath)
        options['pathex'].append(os.path.abspath(workpath))

        for i, tp in enumerate(options.setdefault('datas', [])):
            options['datas'][i] = (os.path.abspath(options['datas'][i][0]),
                                   options['datas'][i][1])

        if not self.optimize_imports:
            self._discover_dependencies(options)

        executables = []
        for script, executable in zip(scripts, self.executables):
            executable = executable or Executable(script)
            executable.script = script
            executable._options = dict(options, **executable.options)
            executable._options['name'] = '.'.join(
                ntpath.basename(script).split('.')[:-1])
            if executable._options['name'] in gui_scripts:
                executable._options['console'] = False

            executables.append(executable)

        for executable in executables:
            rename_script(executable)

        for executable in executables:
            self._freeze(executable, workpath, distpath)

        # TODO: Compare file hashes to make sure we haven't replaced files with
        # a different version
        names = [executable.options['name'] for executable in executables]
        for name in names[1:]:
            move_tree(os.path.join(distpath, name),
                      os.path.join(distpath, names[0]))

        move_tree(os.path.join(distpath, names[0]), self.build_exe)

        shutil.rmtree(self.build_temp, ignore_errors=True)
        shutil.rmtree(distpath, ignore_errors=True)