示例#1
0
def parse_workflow_config(rawactions):
    """Given a list of options from [ticket-workflow]"""

    required_attrs = {
        'oldstates': [],
        'newstate': '',
        'name': '',
        'label': '',
        'default': 0,
        'operations': [],
        'permissions': [],
    }
    optional_attrs = {
        'set_owner': [],
        'set_resolution': [],
    }
    known_attrs = required_attrs.copy()
    known_attrs.update(optional_attrs)

    actions = defaultdict(dict)
    for option, value in rawactions:
        parts = option.split('.')
        name = parts[0]
        if len(parts) == 1:
            try:
                # Base name, of the syntax: old,states,here -> newstate
                oldstates, newstate = [x.strip() for x in value.split('->')]
            except ValueError:
                continue  # Syntax error, a warning will be logged later
            actions[name]['oldstates'] = to_list(oldstates)
            actions[name]['newstate'] = newstate
        else:
            attribute = parts[1]
            if attribute not in known_attrs.keys() or \
                    isinstance(known_attrs[attribute], str):
                actions[name][attribute] = value
            elif isinstance(known_attrs[attribute], int):
                actions[name][attribute] = int(value)
            elif isinstance(known_attrs[attribute], list):
                actions[name][attribute] = to_list(value)

    for action, attributes in actions.items():
        if 'label' not in attributes:
            if 'name' in attributes:  # backwards-compatibility, #11828
                attributes['label'] = attributes['name']
            else:
                attributes['label'] = action.replace("_", " ").strip()
        for key, val in required_attrs.items():
            attributes.setdefault(key, val)

    return actions
示例#2
0
    def parse_authz(self):
        self.log.debug("Parsing authz security policy %s", self.authz_file)

        self.authz = UnicodeConfigParser()
        try:
            self.authz.read(self.authz_file)
        except ParsingError as e:
            self.log.error("Error parsing authz permission policy file: %s", to_unicode(e))
            raise ConfigurationError()
        groups = {}
        if self.authz.has_section("groups"):
            for group, users in self.authz.items("groups"):
                groups[group] = to_list(users)

        self.groups_by_user = {}

        def add_items(group, items):
            for item in items:
                if item.startswith("@"):
                    add_items(group, groups[item[1:]])
                else:
                    self.groups_by_user.setdefault(item, set()).add(group)

        for group, users in groups.iteritems():
            add_items("@" + group, users)

        self.authz_mtime = os.path.getmtime(self.authz_file)
示例#3
0
def parse_subscriber_config(rawsubscriptions):
    """Given a list of options from [notification-subscriber]"""

    required_attrs = {
        'distributor': 'email',
        'priority': 100,
        'adverb': 'always',
        'format': None,
    }
    optional_attrs = {}
    known_attrs = required_attrs.copy()
    known_attrs.update(optional_attrs)

    byname = defaultdict(dict)
    for option, value in rawsubscriptions:
        parts = option.split('.', 1)
        name = parts[0]
        if len(parts) == 1:
            byname[name].update({'name': name, 'class': value.strip()})
        else:
            attribute = parts[1]
            known = known_attrs.get(attribute)
            if known is None or isinstance(known, basestring):
                pass
            elif isinstance(known, int):
                value = int(value)
            elif isinstance(known, bool):
                value = as_bool(value)
            elif isinstance(known, list):
                value = to_list(value)
            byname[name][attribute] = value

    byclass = defaultdict(list)
    for name, attributes in byname.items():
        for key, value in required_attrs.items():
            attributes.setdefault(key, value)
        byclass[attributes['class']].append(attributes)
    for values in byclass.values():
        values.sort(key=lambda value: (value['priority'], value['name']))

    return byclass
示例#4
0
文件: api.py 项目: pkdevbox/trac
def parse_subscriber_config(rawsubscriptions):
    """Given a list of options from [notification-subscriber]"""

    required_attrs = {
        'distributor': 'email',
        'priority': 100,
        'adverb': 'always',
        'format': 'text/plain',
    }
    optional_attrs = {}
    known_attrs = required_attrs.copy()
    known_attrs.update(optional_attrs)

    byname = defaultdict(dict)
    for option, value in rawsubscriptions:
        parts = option.split('.', 1)
        name = parts[0]
        if len(parts) == 1:
            byname[name].update({'name': name, 'class': value.strip()})
        else:
            attribute = parts[1]
            known = known_attrs.get(attribute)
            if known is None or isinstance(known, basestring):
                pass
            elif isinstance(known, int):
                value = int(value)
            elif isinstance(known, bool):
                value = as_bool(value)
            elif isinstance(known, list):
                value = to_list(value)
            byname[name][attribute] = value

    byclass = defaultdict(list)
    for name, attributes in byname.items():
        for key, value in required_attrs.items():
            attributes.setdefault(key, value)
        byclass[attributes['class']].append(attributes)
    for values in byclass.values():
        values.sort(key=lambda value: (value['priority'], value['name']))

    return byclass
示例#5
0
    def authz_permissions(self, resource_key, username):
        # TODO: Handle permission negation in sections. eg. "if in this
        # ticket, remove TICKET_MODIFY"
        if username and username != "anonymous":
            valid_users = ["*", "authenticated", username]
        else:
            valid_users = ["*", "anonymous"]
        for resource_section in [a for a in self.authz.sections() if a != "groups"]:
            resource_glob = resource_section
            if "@" not in resource_glob:
                resource_glob += "@*"

            if fnmatchcase(resource_key, resource_glob):
                for who, permissions in self.authz.items(resource_section):
                    permissions = to_list(permissions)
                    if who in valid_users or who in self.groups_by_user.get(username, []):
                        self.log.debug("%s matched section %s for user %s", resource_key, resource_glob, username)
                        if isinstance(permissions, basestring):
                            return [permissions]
                        else:
                            return permissions
        return None
示例#6
0
def parse_subscriber_config(rawsubscriptions):
    """Given a list of options from [notification-subscriber]"""

    required_attrs = {
        'distributor': 'email',
        'priority': 100,
        'adverb': 'always',
        'format': 'text/plain',
    }
    optional_attrs = {}
    known_attrs = required_attrs.copy()
    known_attrs.update(optional_attrs)

    byname = defaultdict(dict)
    for option, value in rawsubscriptions:
        parts = option.split('.')
        name = parts[0]
        if len(parts) == 1:
            byname[name]['name'] = name
            byname[name]['class'] = value.strip()
        else:
            attribute = parts[1]
            if attribute not in known_attrs.keys or \
                    isinstance(known_attrs[attribute], str):
                byname[name][attribute] = value
            elif isinstance(known_attrs[attribute], int):
                byname[name][attribute] = int(value)
            elif isinstance(known_attrs[attribute], bool):
                byname[name][attribute] = as_bool(value)
            elif isinstance(known_attrs[attribute], list):
                byname[name][attribute] = to_list(value)

    byclass = defaultdict(list)
    for name, attributes in byname.items():
        for key, val in required_attrs.items():
            attributes.setdefault(key, val)
        byclass[attributes['class']].append(attributes)

    return byclass
示例#7
0
 def _get_review_options(self, action):
     values = self.config.getlist('ticket-workflow',
                                  action + '.code_review')
     return OrderedDict(to_list(v, sep='->') for v in values)
示例#8
0
    def expand_macro(self, formatter, name, content):
        if name == 'DownloadsCount':
            api = self.env[DownloadsApi]

            # Check empty macro content.
            download_ids = []
            if content and content.strip() != '':
                # Get download IDs or filenames from content.
                items = to_list(content)

                # Resolve filenames to IDs.
                for item in items:
                    try:
                        # Try if it's download ID first.
                        download_id = int(item)
                        if download_id:
                            download_ids.append(download_id)
                        else:
                            # Any zero ID means all downloads.
                            download_ids = []
                            break
                    except ValueError:
                        # If it wasn't ID resolve filename.
                        download_id = api.get_download_id_from_file(item)
                        if download_id:
                            download_ids.append(download_id)
                        else:
                            self.log.debug("Could not resolve download "
                                           "filename to ID.")

            # Empty list mean all.
            if len(download_ids) == 0:
                download_ids = None

            # Ask for aggregated downloads count.
            self.log.debug(download_ids)
            count = api.get_number_of_downloads(download_ids)

            # Return simple <span> with result.
            return html.span(to_unicode(count), class_="downloads_count")

        elif name == 'ListDownloads':
            # Determine wiki page name.
            page_name = formatter.req.path_info[6:] or 'WikiStart'

            api = self.env[DownloadsApi]

            # Get form values.
            req = formatter.req
            order = req.args.get('order') or 'id'
            desc = req.args.get('desc')
            has_tags = self.env.is_component_enabled('tractags.api.TagEngine')
            visible_fields = self.config.getlist('downloads', 'visible_fields')

            # Prepare template data.
            data = {
                'order': order,
                'desc': desc,
                'has_tags': has_tags,
                'downloads': api.get_downloads(order, desc),
                'visible_fields': visible_fields,
                'page_name': page_name
            }

            # Return rendered template.
            return to_unicode(
                Chrome(self.env).render_template(formatter.req,
                                                 'wiki-downloads-list.html',
                                                 {'downloads': data},
                                                 'text/html', True))