コード例 #1
0
def _sanitize_and_merge_envs(app_env: dict, task_env: dict) -> dict:
    envs = {}
    for (k, v) in app_env.items():
        envs[remove_prefix(k, "TASKCFG_ALL_")] = v
    for (k, v) in task_env.items():
        if v.count(v[0]) == len(v):
            v = v[0]
        envs[remove_prefix(k, "TASKCFG_ALL_")] = v
    return envs
コード例 #2
0
def _sanitize_and_merge_envs(app_env: dict, task_env: dict) -> dict:
    """Cleans the env vars by trimming DCOS task prefixes"""
    envs = {}
    for (k, v) in app_env.items():
        envs[remove_prefix(k, "TASKCFG_ALL_")] = v
    for (k, v) in task_env.items():
        if v.count(v[0]) == len(v):
            v = v[0]
        envs[remove_prefix(k, "TASKCFG_ALL_")] = v
    return envs
コード例 #3
0
ファイル: plugin.py プロジェクト: MCDReforged/PluginCatalogue
    def __parse_version(self, plugin_id: str) -> Optional[str]:
        # Possible tag names
        #   plugin_id-v1.2.3
        #   plugin_id-1.2.3
        #   v1.2.3
        #   1.2.3

        def test_and_return(version_str: str) -> Optional[str]:
            try:
                Version(version_str, allow_wildcard=False)
            except:
                return None
            else:
                return version_str

        version = self.tag_name
        if version.startswith(plugin_id + '-'):
            version = utils.remove_prefix(version, plugin_id + '-')
        if len(version) == 0:
            return version
        if version[0].isdigit():
            return test_and_return(version)
        elif version[0].lower() == 'v':
            return test_and_return(version[1:])
        else:
            return None
コード例 #4
0
    def get_all():

        names_dict = {}
        for key in db.prefix('name_'):
            names_dict[utils.remove_prefix('name', key)] = db[key]

        return names_dict
コード例 #5
0
ファイル: Container.py プロジェクト: abferm/libqmi
    def add_sections(self, sections):
        if self.fields is None:
            return

        translations = { 'name'       : self.name,
                         'camelcase'  : utils.build_camelcase_name (self.fullname),
                         'underscore' : utils.build_underscore_name (self.fullname),
                         'type_macro' : 'QMI_TYPE_' + utils.remove_prefix(utils.build_underscore_uppercase_name(self.fullname), 'QMI_') }

        # Standard
        template = (
            '${underscore}_get_type\n'
            '${type_macro}\n')
        sections['standard'] += string.Template(template).substitute(translations)

        # Public types
        template = (
            '${camelcase}\n')
        sections['public-types'] += string.Template(template).substitute(translations)

        # Public methods
        template = '<SUBSECTION ${camelcase}Methods>\n'
        if self.readonly == False:
            template += (
                '${underscore}_new\n')
        template += (
            '${underscore}_ref\n'
            '${underscore}_unref\n')
        sections['public-methods'] += string.Template(template).substitute(translations)

        for field in self.fields:
            field.add_sections(sections)
コード例 #6
0
ファイル: Container.py プロジェクト: proteus-cpi/libqmi
    def add_sections(self, sections):
        if self.fields is None:
            return

        translations = { 'name'       : self.name,
                         'camelcase'  : utils.build_camelcase_name (self.fullname),
                         'underscore' : utils.build_underscore_name (self.fullname),
                         'type_macro' : 'QMI_TYPE_' + utils.remove_prefix(utils.build_underscore_uppercase_name(self.fullname), 'QMI_') }

        # Standard
        template = (
            '${underscore}_get_type\n'
            '${type_macro}\n')
        sections['standard'] += string.Template(template).substitute(translations)

        # Public types
        template = (
            '${camelcase}\n')
        sections['public-types'] += string.Template(template).substitute(translations)

        # Public methods
        template = '<SUBSECTION ${camelcase}Methods>\n'
        if self.readonly == False:
            template += (
                '${underscore}_new\n')
        template += (
            '${underscore}_ref\n'
            '${underscore}_unref\n')
        sections['public-methods'] += string.Template(template).substitute(translations)

        for field in self.fields:
            field.add_sections(sections)
コード例 #7
0
    def get_all():

        insults_dict = {}
        for key in db.prefix('insult_'):
            insults_dict[utils.remove_prefix('insult', key)] = db[key]

        return insults_dict
コード例 #8
0
def calculate_metrics(path, config=radon_cfg):
    results = {}
    for k, result in CombinedHarvester([path], config).results:
        k = utils.remove_prefix(k, path)
        # Mongo does not like . in key names. Deal with multiple dots.
        parts = k.split('.')
        k = parts[0]
        ext = '.'.join(parts[1:])
        result.update({'meta': {'ext': ext}})
        results[k] = result
    return results
コード例 #9
0
def __parse_server_nodes(node, address):
    server = ServerNodeModel(name=node.get('name'),
                             size=node.get('server_type'),
                             roles=None,
                             public_ip=node.get('ipv4_address'),
                             res_id=node.get('id'),
                             res_addr=address)
    server.roles = [
        utils.remove_prefix(k, 'k8sgen.rol.')
        for k, v in node.get('labels').items() if k.startswith('k8sgen.rol.')
    ]
    return server
コード例 #10
0
    def add_insult(insult):

        insults = list(db.prefix('insult_'))

        biggest_id = 0
        for item in insults:
            id = int(utils.remove_prefix('insult', item))

            if biggest_id < id:
                biggest_id = id

        db["insult_" + str(biggest_id + 1)] = insult
        return "L'ajout de : " + insult + " a fonctionné !"
コード例 #11
0
    def add_name(name):

        names = list(db.prefix('name_'))

        biggest_id = 0
        for item in names:
            id = int(utils.remove_prefix('name', item))

            if biggest_id < id:
                biggest_id = id

        db["name_" + str(biggest_id + 1)] = name
        return "L'ajout de : " + name + " a fonctionné !"
コード例 #12
0
def _fetch_tasks_envs(app_id: str, task_count: int) -> dict:
    """Pulls task configuration"""
    envs = {}
    for task in range(task_count):
        task_name = remove_prefix(app_id, "/").replace("/", ".") + "__kafka-{}-broker__".format(task)
        log.info("Downloading configuration from task: {}".format(task_name))
        _, out, err = run_cmd("{} task exec {} bash -c 'env'".format(DCOS, task_name))
        for env in out.split("\n"):
            key, value = env.split("=")
            if key not in envs:
                envs[key] = [value]
            else:
                envs[key].append(value)
    return envs
コード例 #13
0
def _fetch_tasks_envs(app_id: str, task_count: int) -> dict:
    envs = {}
    for task in range(task_count):
        task_name = remove_prefix(app_id, '/').replace('/', '.') + "__node-{}-server__".format(task)
        log.info("Downloading configuration from task: {}".format(task_name))
        _, out, err = run_cmd("{} task exec {} bash -c 'env'".format(DCOS, task_name))
        for env in out.split('\n'):
            key, value = env.split('=')
            if key not in envs:
                envs[key] = [value]
            else:
                envs[key].append(value)
        _, out, err = run_cmd("{} task exec {} bash -c 'cat $MESOS_SANDBOX/new_user_password'".format(DCOS, task_name))
        envs["NEW_USER_PASSWORD"] = out
    return envs
コード例 #14
0
def get_refs_preds(l, type=1):
    if type==1:
        tails = l["fact"]["tails"]
        head = l["fact"]["head"]
        prompt = l["prompt"]
        generations = l["generations"]
        gens = [remove_prefix(g, prompt).strip() for g in generations]
    if type==2:
        tails = l["tails"]
        head = l["head"]
        gens = l["generations"]
    if type==3:
        tails = l["fact"]["tails"]
        head = l["fact"]["head"]
        gens = l["generations"]
    return gens, tails, head
コード例 #15
0
    def __emit_types(self, hfile, cfile, translations):
        translations['type_macro'] = 'QMI_TYPE_' + utils.remove_prefix(
            utils.build_underscore_uppercase_name(self.fullname), 'QMI_')
        # Emit types header
        template = '\n'
        if self.static == False:
            template += (
                '/**\n'
                ' * ${camelcase}:\n'
                ' *\n'
                ' * The #${camelcase} structure contains private data and should only be accessed\n'
                ' * using the provided API.\n'
                ' *\n'
                ' * Since: ${since}\n'
                ' */\n')
        template += (
            'typedef struct _${camelcase} ${camelcase};\n'
            '${static}GType ${underscore}_get_type (void) G_GNUC_CONST;\n'
            '#define ${type_macro} (${underscore}_get_type ())\n')
        hfile.write(string.Template(template).substitute(translations))

        # Emit types source
        template = ('\n'
                    'struct _${camelcase} {\n'
                    '    volatile gint ref_count;\n')
        cfile.write(string.Template(template).substitute(translations))

        if self.fields is not None:
            for field in self.fields:
                if field.variable is not None:
                    variable_declaration = field.variable.build_variable_declaration(
                        False, '    ', field.variable_name)
                    translations['field_variable_name'] = field.variable_name
                    translations['field_name'] = field.name
                    template = ('\n'
                                '    /* ${field_name} */\n'
                                '    gboolean ${field_variable_name}_set;\n')
                    cfile.write(
                        string.Template(template).substitute(translations))
                    cfile.write(variable_declaration)

        cfile.write('};\n')
コード例 #16
0
ファイル: Container.py プロジェクト: abferm/libqmi
    def __emit_types(self, hfile, cfile, translations):
        translations['type_macro'] = 'QMI_TYPE_' + utils.remove_prefix(utils.build_underscore_uppercase_name(self.fullname), 'QMI_')
        # Emit types header
        template = (
            '\n'
            '/**\n'
            ' * ${camelcase}:\n'
            ' *\n'
            ' * The #${camelcase} structure contains private data and should only be accessed\n'
            ' * using the provided API.\n'
            ' */\n'
            'typedef struct _${camelcase} ${camelcase};\n'
            '${static}GType ${underscore}_get_type (void) G_GNUC_CONST;\n'
            '#define ${type_macro} (${underscore}_get_type ())\n')
        hfile.write(string.Template(template).substitute(translations))

        # Emit types source
        template = (
            '\n'
            'struct _${camelcase} {\n'
            '    volatile gint ref_count;\n')
        cfile.write(string.Template(template).substitute(translations))

        if self.fields is not None:
            for field in self.fields:
                if field.variable is not None:
                    variable_declaration = field.variable.build_variable_declaration(False, '    ', field.variable_name)
                    translations['field_variable_name'] = field.variable_name
                    translations['field_name'] = field.name
                    template = (
                        '\n'
                        '    /* ${field_name} */\n'
                        '    gboolean ${field_variable_name}_set;\n')
                    cfile.write(string.Template(template).substitute(translations))
                    cfile.write(variable_declaration)

        cfile.write(
            '};\n')
コード例 #17
0
    def get_files_covered_by_target(self, target):
        """Returns a list of source files covered by the specific fuzz target.

    Args:
      target: The name of the fuzz target whose coverage is requested.

    Returns:
      A list of files that the fuzz target covers or None.
    """
        target_cov = self.get_target_coverage(target)
        if not target_cov:
            logging.info('No coverage available for %s', target)
            return None

        coverage_per_file = get_coverage_per_file(target_cov)
        if not coverage_per_file:
            logging.info('No files found in coverage report.')
            return None

        affected_file_list = []
        for file_cov in coverage_per_file:
            norm_file_path = os.path.normpath(file_cov['filename'])
            if not norm_file_path.startswith(self.repo_path):
                # Exclude files outside of the main repo.
                continue

            if not is_file_covered(file_cov):
                # Don't consider a file affected if code in it is never executed.
                continue

            # TODO(metzman): It's weird to me that we access file_cov['filename']
            # again and not norm_file_path, figure out if this makes sense.
            relative_path = utils.remove_prefix(file_cov['filename'],
                                                self.repo_path)
            affected_file_list.append(relative_path)

        return affected_file_list
コード例 #18
0
 def __gather_env_vars():
     return {
         utils.remove_prefix(env, 'CLDGEN_TF_').lower(): val
         for env, val in os.environ.items() if env.startswith('CLDGEN_TF')
     }
コード例 #19
0
ファイル: Client.py プロジェクト: a170785/buildroot
    def __emit_class(self, hfile, cfile, message_list):

        # Check if we'll have indications
        has_indications = False
        for message in message_list.list:
            if message.type == 'Indication':
                has_indications = True
                break

        translations = { 'underscore'                 : utils.build_underscore_name(self.name),
                         'no_prefix_underscore_upper' : utils.build_underscore_name(self.name[4:]).upper(),
                         'camelcase'                  : utils.build_camelcase_name(self.name),
                         'hyphened'                   : utils.build_dashed_name(self.name),
                         'service'                    : self.service.upper() }

        # Emit class header
        template = (
            '#define QMI_TYPE_${no_prefix_underscore_upper}            (${underscore}_get_type ())\n'
            '#define QMI_${no_prefix_underscore_upper}(obj)            (G_TYPE_CHECK_INSTANCE_CAST ((obj), QMI_TYPE_${no_prefix_underscore_upper}, ${camelcase}))\n'
            '#define QMI_${no_prefix_underscore_upper}_CLASS(klass)    (G_TYPE_CHECK_CLASS_CAST ((klass),  QMI_TYPE_${no_prefix_underscore_upper}, ${camelcase}Class))\n'
            '#define QMI_IS_${no_prefix_underscore_upper}(obj)         (G_TYPE_CHECK_INSTANCE_TYPE ((obj), QMI_TYPE_${no_prefix_underscore_upper}))\n'
            '#define QMI_IS_${no_prefix_underscore_upper}_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass),  QMI_TYPE_${no_prefix_underscore_upper}))\n'
            '#define QMI_${no_prefix_underscore_upper}_GET_CLASS(obj)  (G_TYPE_INSTANCE_GET_CLASS ((obj),  QMI_TYPE_${no_prefix_underscore_upper}, ${camelcase}Class))\n'
            '\n'
            'typedef struct _${camelcase} ${camelcase};\n'
            'typedef struct _${camelcase}Class ${camelcase}Class;\n'
            '\n'
            '/**\n'
            ' * ${camelcase}:\n'
            ' *\n'
            ' * The #${camelcase} structure contains private data and should only be accessed\n'
            ' * using the provided API.\n'
            ' */\n'
            'struct _${camelcase} {\n'
            '    /*< private >*/\n'
            '    QmiClient parent;\n'
            '    gpointer priv_unused;\n'
            '};\n'
            '\n'
            'struct _${camelcase}Class {\n'
            '    /*< private >*/\n'
            '    QmiClientClass parent;\n'
            '};\n'
            '\n'
            'GType ${underscore}_get_type (void);\n'
            '\n')
        hfile.write(string.Template(template).substitute(translations))

        # Emit class source. Documentation skipped for the CTL service.
        template = ''
        if self.service != 'CTL':
            template += (
                '\n'
                '/**\n'
                ' * SECTION: ${hyphened}\n'
                ' * @title: ${camelcase}\n'
                ' * @short_description: #QmiClient for the ${service} service.\n'
                ' *\n'
                ' * #QmiClient which handles operations in the ${service} service.\n'
                ' */\n'
                '\n')
        template += (
            'G_DEFINE_TYPE (${camelcase}, ${underscore}, QMI_TYPE_CLIENT);\n')

        if has_indications:
            template += (
                '\n'
                'enum {\n')
            for message in message_list.list:
                if message.type == 'Indication':
                    translations['signal_id'] = utils.build_underscore_uppercase_name(message.name)
                    inner_template = (
                        '    SIGNAL_${signal_id},\n')
                    template += string.Template(inner_template).substitute(translations)
            template += (
                '    SIGNAL_LAST\n'
                '};\n'
                '\n'
                'static guint signals[SIGNAL_LAST] = { 0 };\n')

        template += (
            '\n'
            'static void\n'
            'process_indication (QmiClient *self,\n'
            '                    QmiMessage *message)\n'
            '{\n'
            '    switch (qmi_message_get_message_id (message)) {\n')

        for message in message_list.list:
            if message.type == 'Indication':
                translations['enum_name'] = message.id_enum_name
                translations['message_fullname_underscore'] = utils.build_underscore_name(message.fullname)
                translations['message_name'] = message.name
                translations['signal_id'] = utils.build_underscore_uppercase_name(message.name)
                inner_template = ''
                if message.output is not None and message.output.fields is not None:
                    # At least one field in the indication
                    translations['output_camelcase'] = utils.build_camelcase_name(message.output.fullname)
                    translations['output_underscore'] = utils.build_underscore_name(message.output.fullname)
                    translations['output_underscore'] = utils.build_underscore_name(message.output.fullname)
                    inner_template += (
                        '        case ${enum_name}: {\n'
                        '            ${output_camelcase} *output;\n'
                        '            GError *error = NULL;\n'
                        '\n'
                        '            /* Parse indication */\n'
                        '            output = __${message_fullname_underscore}_indication_parse (message, &error);\n'
                        '            if (!output) {\n'
                        '                g_warning ("Couldn\'t parse \'${message_name}\' indication: %s",\n'
                        '                           error ? error->message : "Unknown error");\n'
                        '                if (error)\n'
                        '                    g_error_free (error);\n'
                        '            } else {\n'
                        '                g_signal_emit (self, signals[SIGNAL_${signal_id}], 0, output);\n'
                        '                ${output_underscore}_unref (output);\n'
                        '            }\n'
                        '            break;\n'
                        '        }\n')
                else:
                    # No output field in the indication
                    inner_template += (
                        '        case ${enum_name}: {\n'
                        '            g_signal_emit (self, signals[SIGNAL_${signal_id}], 0, NULL);\n'
                        '            break;\n'
                        '        }\n')

                template += string.Template(inner_template).substitute(translations)

        template += (
            '        default:\n'
            '            break;\n'
            '    }\n'
            '}\n'
            '\n'
            'static void\n'
            '${underscore}_init (${camelcase} *self)\n'
            '{\n'
            '}\n'
            '\n'
            'static void\n'
            '${underscore}_class_init (${camelcase}Class *klass)\n'
            '{\n'
            '    QmiClientClass *client_class = QMI_CLIENT_CLASS (klass);\n'
            '\n'
            '    client_class->process_indication = process_indication;\n')

        for message in message_list.list:
            if message.type == 'Indication':
                translations['signal_name'] = utils.build_dashed_name(message.name)
                translations['signal_id'] = utils.build_underscore_uppercase_name(message.name)
                translations['message_name'] = message.name
                inner_template = ''
                if message.output is not None and message.output.fields is not None:
                    # At least one field in the indication
                    translations['output_camelcase'] = utils.build_camelcase_name(message.output.fullname)
                    translations['bundle_type'] = 'QMI_TYPE_' + utils.remove_prefix(utils.build_underscore_uppercase_name(message.output.fullname), 'QMI_')
                    translations['service'] = self.service.upper()
                    translations['message_name_dashed'] = message.name.replace(' ', '-')
                    inner_template += (
                        '\n'
                        '    /**\n'
                        '     * ${camelcase}::${signal_name}:\n'
                        '     * @object: A #${camelcase}.\n'
                        '     * @output: A #${output_camelcase}.\n'
                        '     *\n'
                        '     * The ::${signal_name} signal gets emitted when a \'<link linkend=\"libqmi-glib-${service}-${message_name_dashed}.top_of_page\">${message_name}</link>\' indication is received.\n'
                        '     */\n'
                        '    signals[SIGNAL_${signal_id}] =\n'
                        '        g_signal_new ("${signal_name}",\n'
                        '                      G_OBJECT_CLASS_TYPE (G_OBJECT_CLASS (klass)),\n'
                        '                      G_SIGNAL_RUN_LAST,\n'
                        '                      0,\n'
                        '                      NULL,\n'
                        '                      NULL,\n'
                        '                      NULL,\n'
                        '                      G_TYPE_NONE,\n'
                        '                      1,\n'
                        '                      ${bundle_type});\n')
                else:
                    # No output field in the indication
                    inner_template += (
                        '\n'
                        '    /**\n'
                        '     * ${camelcase}::${signal_name}:\n'
                        '     * @object: A #${camelcase}.\n'
                        '     *\n'
                        '     * The ::${signal_name} signal gets emitted when a \'${message_name}\' indication is received.\n'
                        '     */\n'
                        '    signals[SIGNAL_${signal_id}] =\n'
                        '        g_signal_new ("${signal_name}",\n'
                        '                      G_OBJECT_CLASS_TYPE (G_OBJECT_CLASS (klass)),\n'
                        '                      G_SIGNAL_RUN_LAST,\n'
                        '                      0,\n'
                        '                      NULL,\n'
                        '                      NULL,\n'
                        '                      NULL,\n'
                        '                      G_TYPE_NONE,\n'
                        '                      0);\n')
                template += string.Template(inner_template).substitute(translations)

        template += (
            '}\n'
            '\n')
        cfile.write(string.Template(template).substitute(translations))
コード例 #20
0
ファイル: plugin.py プロジェクト: MCDReforged/PluginCatalogue
 def repos_path(self) -> str:
     # TISUnion/QuickBackupM
     return utils.remove_prefix(self.repository, 'https://github.com/')
コード例 #21
0
def metrics(config, t: tree.UdbTree) -> bool:
    def write(_dir, _file, _ms) -> bool:
        if not os.path.exists(_dir):
            os.makedirs(_dir)
        return utils.write_lines_to_file(_file, _ms)

    out_dir = f'{config["out_dir_md"]}Metrics'
    if not os.path.exists(out_dir):
        os.mkdir(out_dir)

    base_path = config['udb_source_root']
    deps = get_dep_on_dict(t)
    bys = get_dep_by_dict(deps)
    header_depends_on = '\n|Depends ON    |  Count|\n'
    header_depends_by = '\n|Depends BY    |  Count|\n'
    header_data = '|:---             |---:   |\n'

    for arch in t.root.walk():
        # write directory level md files
        path = utils.remove_prefix(arch.path, 'Directory Structure')
        if arch == t.root:
            new_out_dir = out_dir
            f_name = f'{out_dir}/application-metrics.md'
            rs = ['# Application Metrics\n']
        else:
            new_out_dir = f'{out_dir}{path}'
            f_name = f'{new_out_dir}/{arch.name}-metrics.md'
            rs = [f'# {arch.name} Metrics\n']
        rs.extend(converters.get_metric_markdown(arch.metrics))
        if not write(new_out_dir, f_name, rs):
            return False

        # write file level md files
        if len(arch.ent_children) == 0:
            continue

        pos = f_name.rfind('/')
        t_str = f_name[:pos]
        f_name = t_str + '/zzz-file-metrics.md'
        rs = ['# File Metrics and Dependencies\n\n']
        for ent in arch.ent_children:
            # metrics
            full_name = rel_path(ent.long_name, base_path)
            rs.append(f'## {ent.name}\n')
            rs.append(f'full path ==> {full_name}\n\n')
            rs.extend(converters.get_metric_markdown(ent.metrics))

            # dependencies
            # dep_ons = list(ent.deps.items())
            dep_ons = [(t.uids[k].path, v) for k, v in ent.deps.items()]
            if len(dep_ons) > 0:
                rs.extend([header_depends_on, header_data])
                dep_ons.sort(key=lambda r: r[0])
                for dep in dep_ons:
                    # rel = rel_path(dep[0], base_path)
                    rel = dep[0].replace('Directory Structure/', '')
                    link = get_link_within_file_metrics(path, rel, rel.split('/')[-1])
                    rs.append(f'|[{rel}]({link})|{dep[1]:6}|\n')
                rs.append('\n&nbsp;\n')

            dep_bys = [(t.uids[k].path, v) for k, v in bys[ent.uid].items()]
            if len(dep_bys) > 0:
                rs.extend([header_depends_by, header_data])
                dep_bys.sort(key=lambda r: r[0])
                for d_by in dep_bys:
                    # rel = rel_path(d_by[0], base_path)
                    rel = d_by[0].replace('Directory Structure/', '')
                    link = get_link_within_file_metrics(path, rel, rel.split('/')[-1])
                    rs.append(f'|[{rel}]({link})|{d_by[1]:6}|\n')
                rs.append('\n&nbsp;\n')
            rs.append('\n\n')

        if not write(new_out_dir, f_name, rs):
            return False

    return True
コード例 #22
0
ファイル: Client.py プロジェクト: fendouzhe660/dd-wrt
    def __emit_class(self, hfile, cfile, message_list):

        # Check if we'll have indications
        has_indications = False
        for message in message_list.list:
            if message.type == 'Indication':
                has_indications = True
                break

        translations = {
            'underscore':
            utils.build_underscore_name(self.name),
            'no_prefix_underscore_upper':
            utils.build_underscore_name(self.name[4:]).upper(),
            'camelcase':
            utils.build_camelcase_name(self.name),
            'hyphened':
            utils.build_dashed_name(self.name),
            'service':
            self.service.upper()
        }

        # Emit class header
        template = (
            '#define QMI_TYPE_${no_prefix_underscore_upper}            (${underscore}_get_type ())\n'
            '#define QMI_${no_prefix_underscore_upper}(obj)            (G_TYPE_CHECK_INSTANCE_CAST ((obj), QMI_TYPE_${no_prefix_underscore_upper}, ${camelcase}))\n'
            '#define QMI_${no_prefix_underscore_upper}_CLASS(klass)    (G_TYPE_CHECK_CLASS_CAST ((klass),  QMI_TYPE_${no_prefix_underscore_upper}, ${camelcase}Class))\n'
            '#define QMI_IS_${no_prefix_underscore_upper}(obj)         (G_TYPE_CHECK_INSTANCE_TYPE ((obj), QMI_TYPE_${no_prefix_underscore_upper}))\n'
            '#define QMI_IS_${no_prefix_underscore_upper}_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass),  QMI_TYPE_${no_prefix_underscore_upper}))\n'
            '#define QMI_${no_prefix_underscore_upper}_GET_CLASS(obj)  (G_TYPE_INSTANCE_GET_CLASS ((obj),  QMI_TYPE_${no_prefix_underscore_upper}, ${camelcase}Class))\n'
            '\n'
            'typedef struct _${camelcase} ${camelcase};\n'
            'typedef struct _${camelcase}Class ${camelcase}Class;\n'
            '\n'
            '/**\n'
            ' * ${camelcase}:\n'
            ' *\n'
            ' * The #${camelcase} structure contains private data and should only be accessed\n'
            ' * using the provided API.\n'
            ' */\n'
            'struct _${camelcase} {\n'
            '    /*< private >*/\n'
            '    QmiClient parent;\n'
            '    gpointer priv_unused;\n'
            '};\n'
            '\n'
            'struct _${camelcase}Class {\n'
            '    /*< private >*/\n'
            '    QmiClientClass parent;\n'
            '};\n'
            '\n'
            'GType ${underscore}_get_type (void);\n'
            '\n')
        hfile.write(string.Template(template).substitute(translations))

        # Emit class source. Documentation skipped for the CTL service.
        template = ''
        if self.service != 'CTL':
            template += (
                '\n'
                '/**\n'
                ' * SECTION: ${hyphened}\n'
                ' * @title: ${camelcase}\n'
                ' * @short_description: #QmiClient for the ${service} service.\n'
                ' *\n'
                ' * #QmiClient which handles operations in the ${service} service.\n'
                ' */\n'
                '\n')
        template += (
            'G_DEFINE_TYPE (${camelcase}, ${underscore}, QMI_TYPE_CLIENT);\n')

        if has_indications:
            template += ('\n' 'enum {\n')
            for message in message_list.list:
                if message.type == 'Indication':
                    translations[
                        'signal_id'] = utils.build_underscore_uppercase_name(
                            message.name)
                    inner_template = ('    SIGNAL_${signal_id},\n')
                    template += string.Template(inner_template).substitute(
                        translations)
            template += ('    SIGNAL_LAST\n'
                         '};\n'
                         '\n'
                         'static guint signals[SIGNAL_LAST] = { 0 };\n')

        template += ('\n'
                     'static void\n'
                     'process_indication (QmiClient *self,\n'
                     '                    QmiMessage *message)\n'
                     '{\n'
                     '    switch (qmi_message_get_message_id (message)) {\n')

        for message in message_list.list:
            if message.type == 'Indication':
                translations['enum_name'] = message.id_enum_name
                translations[
                    'message_fullname_underscore'] = utils.build_underscore_name(
                        message.fullname)
                translations['message_name'] = message.name
                translations[
                    'signal_id'] = utils.build_underscore_uppercase_name(
                        message.name)
                inner_template = ''
                if message.output is not None and message.output.fields is not None:
                    # At least one field in the indication
                    translations[
                        'output_camelcase'] = utils.build_camelcase_name(
                            message.output.fullname)
                    translations[
                        'output_underscore'] = utils.build_underscore_name(
                            message.output.fullname)
                    translations[
                        'output_underscore'] = utils.build_underscore_name(
                            message.output.fullname)
                    inner_template += (
                        '        case ${enum_name}: {\n'
                        '            ${output_camelcase} *output;\n'
                        '            GError *error = NULL;\n'
                        '\n'
                        '            /* Parse indication */\n'
                        '            output = __${message_fullname_underscore}_indication_parse (message, &error);\n'
                        '            if (!output) {\n'
                        '                g_warning ("Couldn\'t parse \'${message_name}\' indication: %s",\n'
                        '                           error ? error->message : "Unknown error");\n'
                        '                if (error)\n'
                        '                    g_error_free (error);\n'
                        '            } else {\n'
                        '                g_signal_emit (self, signals[SIGNAL_${signal_id}], 0, output);\n'
                        '                ${output_underscore}_unref (output);\n'
                        '            }\n'
                        '            break;\n'
                        '        }\n')
                else:
                    # No output field in the indication
                    inner_template += (
                        '        case ${enum_name}: {\n'
                        '            g_signal_emit (self, signals[SIGNAL_${signal_id}], 0, NULL);\n'
                        '            break;\n'
                        '        }\n')

                template += string.Template(inner_template).substitute(
                    translations)

        template += (
            '        default:\n'
            '            break;\n'
            '    }\n'
            '}\n'
            '\n'
            'static void\n'
            '${underscore}_init (${camelcase} *self)\n'
            '{\n'
            '}\n'
            '\n'
            'static void\n'
            '${underscore}_class_init (${camelcase}Class *klass)\n'
            '{\n'
            '    QmiClientClass *client_class = QMI_CLIENT_CLASS (klass);\n'
            '\n'
            '    client_class->process_indication = process_indication;\n')

        for message in message_list.list:
            if message.type == 'Indication':
                translations['signal_name'] = utils.build_dashed_name(
                    message.name)
                translations[
                    'signal_id'] = utils.build_underscore_uppercase_name(
                        message.name)
                translations['message_name'] = message.name
                inner_template = ''
                if message.output is not None and message.output.fields is not None:
                    # At least one field in the indication
                    translations[
                        'output_camelcase'] = utils.build_camelcase_name(
                            message.output.fullname)
                    translations[
                        'bundle_type'] = 'QMI_TYPE_' + utils.remove_prefix(
                            utils.build_underscore_uppercase_name(
                                message.output.fullname), 'QMI_')
                    translations['service'] = self.service.upper()
                    translations['message_name_dashed'] = message.name.replace(
                        ' ', '-')
                    inner_template += (
                        '\n'
                        '    /**\n'
                        '     * ${camelcase}::${signal_name}:\n'
                        '     * @object: A #${camelcase}.\n'
                        '     * @output: A #${output_camelcase}.\n'
                        '     *\n'
                        '     * The ::${signal_name} signal gets emitted when a \'<link linkend=\"libqmi-glib-${service}-${message_name_dashed}.top_of_page\">${message_name}</link>\' indication is received.\n'
                        '     */\n'
                        '    signals[SIGNAL_${signal_id}] =\n'
                        '        g_signal_new ("${signal_name}",\n'
                        '                      G_OBJECT_CLASS_TYPE (G_OBJECT_CLASS (klass)),\n'
                        '                      G_SIGNAL_RUN_LAST,\n'
                        '                      0,\n'
                        '                      NULL,\n'
                        '                      NULL,\n'
                        '                      NULL,\n'
                        '                      G_TYPE_NONE,\n'
                        '                      1,\n'
                        '                      ${bundle_type});\n')
                else:
                    # No output field in the indication
                    inner_template += (
                        '\n'
                        '    /**\n'
                        '     * ${camelcase}::${signal_name}:\n'
                        '     * @object: A #${camelcase}.\n'
                        '     *\n'
                        '     * The ::${signal_name} signal gets emitted when a \'${message_name}\' indication is received.\n'
                        '     */\n'
                        '    signals[SIGNAL_${signal_id}] =\n'
                        '        g_signal_new ("${signal_name}",\n'
                        '                      G_OBJECT_CLASS_TYPE (G_OBJECT_CLASS (klass)),\n'
                        '                      G_SIGNAL_RUN_LAST,\n'
                        '                      0,\n'
                        '                      NULL,\n'
                        '                      NULL,\n'
                        '                      NULL,\n'
                        '                      G_TYPE_NONE,\n'
                        '                      0);\n')
                template += string.Template(inner_template).substitute(
                    translations)

        template += ('}\n' '\n')
        cfile.write(string.Template(template).substitute(translations))
コード例 #23
0
ファイル: doc_gen.py プロジェクト: eagle3236/PluginCatalogue
def _write_plugin(plugin: Plugin, file: IO[str]):
    file.write('## {}\n'.format(plugin.id))
    file.write('\n')

    file.write('### {}\n'.format(Text('basic_info')))
    file.write('\n')

    file.write('- {}: `{}`\n'.format(Text('plugin_id'), plugin.id))
    if plugin.is_data_fetched():
        file.write('- {}: {}\n'.format(Text('plugin_name'),
                                       plugin.meta_info.name))
        file.write('- {}: {}\n'.format(Text('version'), plugin.latest_version))
        file.write('  - {}: {}\n'.format(Text('metadata_version'),
                                         plugin.meta_info.version))
        file.write('  - {}: {}\n'.format(
            Text('release_version'), plugin.release_summary.latest_version))
    else:
        file.write('- {}: {}\n'.format(Text('version'), failed()))

    file.write('- {}: {}\n'.format(
        Text('total_downloads'), plugin.release_summary.get_total_downloads()))
    file.write('- {}: {}\n'.format(
        Text('authors'),
        ', '.join(map(lambda a: a.to_markdown(), plugin.authors))))
    file.write('- {}: {}\n'.format(Text('repository'), plugin.repository))
    file.write('- {}: {}\n'.format(Text('labels'),
                                   get_label_list_markdown(plugin)))
    if plugin.is_data_fetched():
        file.write('- {}: {}\n'.format(
            Text('description'), plugin.meta_info.translated_description))
    else:
        file.write('- {}: {}\n'.format(Text('description'), failed()))
    file.write('\n')

    file.write('### {}\n'.format(Text('dependencies')))
    file.write('\n')
    if plugin.is_data_fetched():
        table = Table(Text('plugin_id'), Text('dependencies.requirement'))
        for pid, req in plugin.meta_info.dependencies.items():
            table.add_row(Link(pid, get_plugin_detail_link(pid)),
                          utils.format_markdown(req))
        table.write(file)
    else:
        file.write('{}\n'.format(failed()))
        file.write('\n')

    file.write('### {}\n'.format(Text('requirements')))
    file.write('\n')
    if plugin.is_data_fetched():
        table = Table(Text('python_package'), Text('requirements.requirement'))
        for line in plugin.meta_info.requirements:
            matched = re.match(r'^[^<>=~^]+', line)
            if matched is None:
                print('Unknown requirement line "{}" in plugin {}'.format(
                    line, plugin))
                continue
            package = matched.group()
            req = utils.remove_prefix(line, package)
            table.add_row(
                Link(package, 'https://pypi.org/project/{}'.format(package)),
                utils.format_markdown(req))
        table.write(file)
    else:
        file.write('{}\n'.format(failed()))
        file.write('\n')

    file.write('### {}\n'.format(Text('introduction')))
    file.write('\n')
    file.write(plugin.introduction.get() or '{}\n'.format(none()))
    file.write('\n')