def parse_element(self,
                      element_name: str,
                      template: Dict[str, str] = None) -> Tuple[str, str]:
        """
        Parse element.

        Args:
            element_name: name of element that should be parsed, if name contains "." then first part of name will be
                used as file name and second as element name.
            template: template that show what replacements should be done e.g. {'some_text': 'text123'} will transform
                selector "//div[text()='%some_text%']" to "//div[text()='text123']".
        """
        parser = ConfigParser()
        splitted_name = element_name.split('.', 1)
        if len(splitted_name) == 1:
            splitted_name = [self._default_page] + splitted_name
        file_name, name = [part.lower() for part in splitted_name]
        ui_map_folder_files = {
            f.lower()[:-4]: f
            for f in listdir(self._ui_map_folder) if f.lower().endswith('.ini')
        }
        if file_name not in ui_map_folder_files:
            raise UIMapException(f'File "{file_name}" was not found.')

        parser.read(path.join(self._ui_map_folder,
                              ui_map_folder_files[file_name]),
                    encoding='utf-8')
        lowered_sections = OrderedDict()
        for section_name, section_data in parser._sections.items():
            lowered_sections[section_name.lower()] = section_data
        parser._sections = lowered_sections
        if not parser.has_section(name):
            raise UIMapException(f'Element "{element_name}" was not found.')

        el_type = parser.get(name, 'type')
        el_selector = parser.get(name, 'selector')
        if self._language and parser.has_option(name, self._language):
            el_selector += parser.get(name, self._language)

        if parser.has_option(name, 'parent'):
            parent_el_name = parser.get(name, 'parent')
            parent_el_type, parent_el_selector = self.parse_element(
                parent_el_name)
            if parent_el_type != el_type:
                raise UIMapException(
                    f'"{element_name}" element and "{parent_el_name}" element have different element '
                    f'types.')
            el_selector = parent_el_selector + el_selector

        if template:
            for k, v in template.items():
                el_selector = el_selector.replace('%%%s%%' % k, v)

        return el_type, el_selector
示例#2
0
    def _sorted_configparser(self, parser: ConfigParser) -> ConfigParser:
        out = ConfigParser(dict_type=OrderedDict)  # type: ignore

        # `out.read_dict(parser)` might not work here as expected: the keys from
        # the `[DEFAULT]` section would be set in *all* sections instead of
        # just the `[DEFAULT]` one.
        out.read_string(self._parser_to_str(parser))

        for section in out._sections:  # type: ignore
            section_ = OrderedDict(
                sorted(out._sections[section].items())  # type: ignore
            )
            out._sections[section] = section_  # type: ignore

        out._sections = OrderedDict(sorted(out._sections.items()))  # type: ignore
        return out
示例#3
0
def main():

    # Start off by running egg_info
    subprocess.call([sys.executable, 'setup.py', 'egg_info'])

    # Check that only one egg-info directory exists
    egg_info_dir = glob.glob('*.egg-info')
    if len(egg_info_dir) != 1:
        print("Expected only one .egg-info directory, got {0}".format(
            egg_info_dir))
        sys.exit(1)
    else:
        egg_info_dir = egg_info_dir[0]

    # Read in any existing setup.cfg file (this will just create an empty
    # configuration if the file doesn't exist yet)
    conf = ConfigParser()
    conf.read('setup.cfg')

    # Add required sections

    if not conf.has_section('metadata'):
        conf.add_section('metadata')

    if not conf.has_section('options'):
        conf.add_section('options')

    # Parse the PKG-INFO file
    dist = Develop('.')

    # Populate the metadata
    for key, handler in METADATA_KEYS.items():
        translated = handler.serialize(getattr(dist, key))
        if translated is not None:
            conf.set('metadata', handler.setup_cfg_name, translated)

    # Populate the options
    conf.set(
        'options', 'zip_safe',
        str(not os.path.exists(os.path.join(egg_info_dir, 'not-zip-safe'))))
    conf.set('options', 'packages', 'find:')
    if dist.requires_python is not None:
        conf.set('options', 'python_requires', dist.requires_python)

    # Check entry points, if they exist
    if os.path.exists(os.path.join(egg_info_dir, 'entry_points.txt')):

        # Entry points are stored in a file that has a config-compatible syntax
        entry = ConfigParser()
        entry.read(os.path.join(egg_info_dir, 'entry_points.txt'))

        if not conf.has_section('options.entry_points'):
            conf.add_section('options.entry_points')

        for section in entry.sections():
            entry_points = []
            for item in entry[section]:
                entry_points.append('{0} = {1}'.format(item,
                                                       entry[section][item]))
            conf.set('options.entry_points', section,
                     os.linesep + os.linesep.join(entry_points))

    # Check install and extras requirements
    if os.path.exists(os.path.join(egg_info_dir, 'requires.txt')):

        # The syntax is
        #
        # install requirements, one per line
        #
        # [extra name]
        # requirements, one per line
        #
        # [another extra name]
        # etc.

        with open(os.path.join(egg_info_dir, 'requires.txt')) as f:
            requires = defaultdict(list)
            section = 'default'
            for req in f:
                if req.startswith('['):
                    section = req.strip()[1:-1]
                elif req.strip() != '':
                    requires[section].append(req.strip())

            conf.set('options', 'install_requires',
                     os.linesep + os.linesep.join(requires['default']))

            # If there are more than one entries in the requires dict, there are some extras
            if len(requires) > 1:
                if not conf.has_section('options.extras_require'):
                    conf.add_section('options.extras_require')
                for section in sorted(requires):
                    if section != 'default':
                        conf.set('options.extras_require', section,
                                 '; '.join(requires[section]))

    # Sort the sections
    def sections_key(section):
        if section == 'metadata':
            return 'a'
        elif section == 'options':
            return 'b'
        elif section.startswith('options'):
            return 'c' + section
        else:
            return 'd'

    conf._sections = OrderedDict([
        (section, conf._sections[section])
        for section in sorted(conf._sections, key=sections_key)
    ])

    with open('setup.cfg', 'w') as f:
        conf.write(f)