File: api.py

package info (click to toggle)
trac-tags 0.9-3
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 596 kB
  • sloc: python: 3,541; makefile: 2
file content (616 lines) | stat: -rw-r--r-- 23,120 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
# -*- coding: utf-8 -*-
#
# Copyright (C) 2006 Alec Thomas <alec@swapoff.org>
# Copyright (C) 2011-2014 Steffen Hoffmann <hoff.st@web.de>
# Copyright (C) 2014 Jun Omae <jun66j5@gmail.com>
# Copyright (C) 2014 Ryan J Ollos <ryan.j.ollos@gmail.com>
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#

import re
try:
    import threading
except ImportError:
    import dummy_threading as threading
    threading._get_ident = lambda: 0

from operator import itemgetter
from pkg_resources import resource_filename

from trac.config import BoolOption, ListOption, Option
from trac.core import Component, ExtensionPoint, Interface, TracError
from trac.core import implements
from trac.perm import IPermissionPolicy, IPermissionRequestor
from trac.perm import PermissionError, PermissionSystem
from trac.resource import IResourceManager, get_resource_url
from trac.resource import get_resource_description
from trac.util import get_reporter_id
from trac.util.text import to_unicode
from trac.util.translation import domain_functions
from trac.wiki.model import WikiPage

# Import translation functions.
add_domain, _, N_, gettext, ngettext, tag_, tagn_ = \
    domain_functions('tractags', ('add_domain', '_', 'N_', 'gettext',
                                  'ngettext', 'tag_', 'tagn_'))
dgettext = None

from tractags.model import resource_tags, tag_frequency, tag_resource
from tractags.model import tagged_resources
# Now call module importing i18n methods from here.
from tractags.query import *

REALM_RE = re.compile('realm:(\w+)', re.U | re.I)


class Counter(dict):
    """Dict subclass for counting hashable objects.

    Sometimes called a bag or multiset.  Elements are stored as dictionary
    keys and their counts are stored as dictionary values.

    >>> Counter('zyzygy')
    Counter({'y': 3, 'z': 2, 'g': 1})

    """

    def __init__(self, iterable=None, **kwargs):
        """Create a new, empty Counter object.

        And if given, count elements from an input iterable.  Or, initialize
        the count from another mapping of elements to their counts.

        >>> c = Counter()                   # a new, empty counter
        >>> c = Counter('gallahad')         # a new counter from an iterable
        >>> c = Counter({'a': 4, 'b': 2})   # a new counter from a mapping
        >>> c = Counter(a=4, b=2)           # a new counter from keyword args

        """
        self.update(iterable, **kwargs)

    def most_common(self, n=None):
        """List the n most common elements and their counts from the most
        common to the least.  If n is None, then list all element counts.

        >>> Counter('abracadabra').most_common(3)
        [('a', 5), ('r', 2), ('b', 2)]
        >>> Counter('abracadabra').most_common()
        [('a', 5), ('r', 2), ('b', 2), ('c', 1), ('d', 1)]

        """
        if n is None:
            return sorted(self.iteritems(), key=itemgetter(1), reverse=True)
        # DEVEL: Use `heapq.nlargest(n, self.iteritems(), key=itemgetter(1))`,
        #        when compatibility with Python2.4 is not an issue anymore.
        return sorted(self.iteritems(), key=itemgetter(1), reverse=True)[:n]

    # Override dict methods where the meaning changes for Counter objects.

    @classmethod
    def fromkeys(cls, iterable, v=None):
        raise NotImplementedError(
            'Counter.fromkeys() is undefined. Use Counter(iterable) instead.')

    def update(self, iterable=None, **kwargs):
        """Like dict.update() but add counts instead of replacing them.

        Source can be an iterable, a dictionary, or another Counter instance.

        >>> c = Counter('which')
        >>> c.update('witch')           # add elements from another iterable
        >>> d = Counter('watch')
        >>> c.update(d)                 # add elements from another counter
        >>> c['h']                      # four 'h' in which, witch, and watch
        4

        """
        if iterable is not None:
            if hasattr(iterable, 'iteritems'):
                if self:
                    self_get = self.get
                    for elem, count in iterable.iteritems():
                        self[elem] = self_get(elem, 0) + count
                else:
                    dict.update(self, iterable) # fast path for empty counter
            else:
                self_get = self.get
                for elem in iterable:
                    self[elem] = self_get(elem, 0) + 1
        if kwargs:
            self.update(kwargs)

    def copy(self):
        """Like dict.copy() but returns a Counter instance instead of a dict.
        """
        return Counter(self)

    def __delitem__(self, elem):
        """Like dict.__delitem__(), but does not raise KeyError for missing
        values.
        """
        if elem in self:
            dict.__delitem__(self, elem)

    def __repr__(self):
        if not self:
            return '%s()' % self.__class__.__name__
        items = ', '.join(map('%r: %r'.__mod__, self.most_common()))
        return '%s({%s})' % (self.__class__.__name__, items)

    # Multiset-style mathematical operations discussed in:
    #       Knuth TAOCP Volume II section 4.6.3 exercise 19
    #       and at http://en.wikipedia.org/wiki/Multiset

    def __add__(self, other):
        """Add counts from two counters.

        >>> Counter('abbb') + Counter('bcc')
        Counter({'b': 4, 'c': 2, 'a': 1})

        """
        if not isinstance(other, Counter):
            return NotImplemented
        result = Counter()
        self_get = self.get
        other_get = other.get
        for elem in set(self) | set(other):
            newcount = self_get(elem, 0) + other_get(elem, 0)
            if newcount > 0:
                result[elem] = newcount
        return result


class InvalidTagRealm(TracError):
    pass


class ITagProvider(Interface):
    """The interface for Components providing per-realm tag storage and
    manipulation methods.

    Change comments and reparenting are supported since tags-0.7.
    """
    def get_taggable_realm():
        """Return the realm this provider supports tags on."""

    def get_tagged_resources(req, tags=None, filter=None):
        """Return a sequence of resources and *all* their tags.

        :param tags: If provided, return only those resources with the given
                     tags.
        :param filter: If provided, skip matching resources.

        :rtype: Sequence of (resource, tags) tuples.
        """

    def get_all_tags(req, filter=None):
        """Return all tags with numbers of occurance.

        :param filter: If provided, skip matching resources.

        :rtype: Counter object (dict sub-class: {tag_name: tag_frequency} ).

        """

    def get_resource_tags(req, resource, when=None):
        """Get tags for a Resource object."""

    def resource_tags(resource):
        """Get tags for a Resource object skipping permission checks."""

    def set_resource_tags(req, resource, tags, comment=u'', when=None):
        """Set tags for a resource."""

    def reparent_resource_tags(req, resource, old_id, comment=u''):
        """Move tags, typically when renaming an existing resource."""

    def remove_resource_tags(req, resource, comment=u''):
        """Remove all tags from a resource."""

    def describe_tagged_resource(req, resource):
        """Return a one line description of the tagged resource."""


class DefaultTagProvider(Component):
    """An abstract base tag provider that stores tags in the database.

    Use this if you need storage for your tags. Simply set the class variable
    `realm` and optionally `check_permission()`.

    See tractags.wiki.WikiTagProvider for an example.
    """

    implements(ITagProvider)

    abstract = True

    # Resource realm this provider manages tags for. Set this.
    realm = None

    revisable = False

    def __init__(self):
        # Do this once, because configuration lookups are costly.
        cfg = self.env.config
        self.revisable = self.realm in cfg.getlist('tags', 'revisable_realms')

    # Public methods

    def check_permission(self, perm, action):
        """Delegate function for checking permissions.

        Override to implement custom permissions. Defaults to TAGS_VIEW and
        TAGS_MODIFY.
        """
        map = {'view': 'TAGS_VIEW', 'modify': 'TAGS_MODIFY'}
        return map[action] in perm('tag')

    # ITagProvider methods

    def get_taggable_realm(self):
        return self.realm

    def get_tagged_resources(self, req, tags=None, filter=None):
        if not self.check_permission(req.perm, 'view'):
            return
        return tagged_resources(self.env, self.check_permission, req.perm,
                                self.realm, tags, filter)

    def get_all_tags(self, req, filter=None):
        all_tags = Counter()
        for tag, count in tag_frequency(self.env, self.realm, filter):
            all_tags[tag] = count
        return all_tags

    def get_resource_tags(self, req, resource, when=None):
        assert resource.realm == self.realm
        if not self.check_permission(req.perm(resource), 'view'):
            return
        return resource_tags(self.env, resource, when=when)

    def resource_tags(self, resource):
        assert resource.realm == self.realm
        return resource_tags(self.env, resource)

    def set_resource_tags(self, req, resource, tags, comment=u'', when=None):
        assert resource.realm == self.realm
        if not self.check_permission(req.perm(resource), 'modify'):
            raise PermissionError(resource=resource, env=self.env)
        tag_resource(self.env, resource, author=self._get_author(req),
                     tags=tags, log=self.revisable, when=when)

    def reparent_resource_tags(self, req, resource, old_id, comment=u''):
        assert resource.realm == self.realm
        if not self.check_permission(req.perm(resource), 'modify'):
            raise PermissionError(resource=resource, env=self.env)
        tag_resource(self.env, resource, old_id, self._get_author(req),
                     log=self.revisable)

    def remove_resource_tags(self, req, resource, comment=u''):
        assert resource.realm == self.realm
        if not self.check_permission(req.perm(resource), 'modify'):
            raise PermissionError(resource=resource, env=self.env)
        tag_resource(self.env, resource, author=self._get_author(req),
                     log=self.revisable)

    def describe_tagged_resource(self, req, resource):
        raise NotImplementedError

    def _get_author(self, req):
        return get_reporter_id(req, 'author')


class TagPolicy(Component):
    """[extra] Security policy based on tags."""

    implements(IPermissionPolicy)

    def check_permission(self, action, username, resource, perm):
        if resource is None or action.split('_')[0] != resource.realm.upper():
            return None

        from tractags.api import TagSystem

        class FakeRequest(object):
            def __init__(self, perm):
                self.perm = perm

        permission = action.lower().split('_')[1]
        req = FakeRequest(perm)
        tags = TagSystem(self.env).get_tags(None, resource)

        # Explicitly denied?
        if ':-'.join((username, permission)) in tags:
            return False

        # Find all granted permissions for the requesting user from
        # tagged permissions by expanding any meta action as well.
        if action in set(PermissionSystem(self.env).expand_actions(
                         ['_'.join([resource.realm, t.split(':')[1]]).upper()
                          for t in tags if t.split(':')[0] == username])):
            return True


class TagSystem(Component):
    """[main] Tagging system for Trac.

    Associating resources with tags is easy, faceted content classification.

    Available components are marked according to their relevance as follows:

     `[main]`:: provide core with a generic tagging engine as well as support
     for common realms 'ticket' (TracTickets) and 'wiki' (TracWiki).
     `[opt]`:: add more features to improve user experience and maintenance
     `[extra]`:: enable advanced features for specific use cases

    Make sure to understand their purpose before deactivating `[main]` or
    activating `[extra]` components.
    """

    implements(IPermissionRequestor, IResourceManager)

    tag_providers = ExtensionPoint(ITagProvider)

    revisable = ListOption('tags', 'revisable_realms', 'wiki',
        doc="Comma-separated list of realms requiring tag change history.")
    wiki_page_link = BoolOption('tags', 'wiki_page_link', True,
        doc="Link a tag to the wiki page with same name, if it exists.")
    wiki_page_prefix = Option('tags', 'wiki_page_prefix', '',
        doc="Prefix for tag wiki page names.")

    # Internal variables
    _realm_provider_map = None

    def __init__(self):
        # Bind the 'tractags' catalog to the specified locale directory.
        locale_dir = resource_filename(__name__, 'locale')
        add_domain(self.env.path, locale_dir)

        self._populate_provider_map()

    # Public methods

    def query(self, req, query='', attribute_handlers=None):
        """Returns a sequence of (resource, tags) tuples matching a query.

        Query syntax is described in tractags.query.

        :param attribute_handlers: Register additional query attribute
                                   handlers. See Query documentation for more
                                   information.
        """
        def realm_handler(_, node, context):
            return query.match(node, [context.realm])

        all_attribute_handlers = {
            'realm': realm_handler,
        }
        all_attribute_handlers.update(attribute_handlers or {})
        query = Query(query, attribute_handlers=all_attribute_handlers)
        providers = set()
        for m in REALM_RE.finditer(query.as_string()):
            realm = m.group(1)
            providers.add(self._get_provider(realm))
        if not providers:
            providers = self.tag_providers

        query_tags = set(query.terms())
        for provider in providers:
            self.env.log.debug('Querying ' + repr(provider))
            for resource, tags in provider.get_tagged_resources(req,
                                                          query_tags) or []:
                if query(tags, context=resource):
                    yield resource, tags

    def get_taggable_realms(self, perm=None):
        """Returns the names of available taggable realms as set.

        If a `PermissionCache` object is passed as optional `perm` argument,
        permission checks will be done for tag providers that have a
        `check_permission` method.
        """
        return set(p.get_taggable_realm()
                   for p in self.tag_providers
                   if perm is None or not hasattr(p, 'check_permission') or
                       p.check_permission(perm, 'view'))

    def get_all_tags(self, req, realms=[]):
        """Get all tags for all supported realms or only for specified ones.

        Returns a Counter object (special dict) with tag name as key and tag
        frequency as value.
        """
        all_tags = Counter()
        all_realms = self.get_taggable_realms(req.perm)
        if not realms or set(realms) == all_realms:
            realms = all_realms
        for provider in self.tag_providers:
            if provider.get_taggable_realm() in realms:
                try:
                    all_tags += provider.get_all_tags(req)
                except AttributeError:
                    # Fallback for older providers.
                    try:
                        for resource, tags in \
                            provider.get_tagged_resources(req):
                                all_tags.update(tags)
                    except TypeError:
                        # Defense against loose ITagProvider implementations,
                        # that might become obsolete in the future.
                        self.env.log.warning('ITagProvider %r has outdated'
                                             'get_tagged_resources() method' %
                                             provider)
        return all_tags

    def get_tags(self, req, resource, when=None):
        """Get tags for resource."""
        if not req:
            # Bypass permission checks as required i. e. for TagsPolicy,
            # an IPermissionProvider.
            return set(self._get_provider(resource.realm) \
                       .resource_tags(resource))
        return set(self._get_provider(resource.realm) \
                   .get_resource_tags(req, resource, when=when))

    def set_tags(self, req, resource, tags, comment=u'', when=None):
        """Set tags on a resource.

        Existing tags are replaced.
        """
        try:
            return self._get_provider(resource.realm) \
                   .set_resource_tags(req, resource, set(tags), comment, when)
        except TypeError:
            # Handle old style tag providers gracefully.
            return self._get_provider(resource.realm) \
                   .set_resource_tags(req, resource, set(tags))

    def add_tags(self, req, resource, tags, comment=u''):
        """Add to existing tags on a resource."""
        tags = set(tags)
        tags.update(self.get_tags(req, resource))
        try:
            self.set_tags(req, resource, tags, comment)
        except TypeError:
            # Handle old style tag providers gracefully.
            self.set_tags(req, resource, tags)

    def reparent_tags(self, req, resource, old_name, comment=u''):
        """Move tags, typically when renaming an existing resource.

        Tags can't be moved between different tag realms with intention.
        """
        provider = self._get_provider(resource.realm)
        provider.reparent_resource_tags(req, resource, old_name, comment)

    def replace_tag(self, req, old_tags, new_tag=None, comment=u'',
                    allow_delete=False, filter=[]):
        """Replace one or more tags in all resources it exists/they exist in.

        Tagged resources may be filtered by realm and tag deletion is
        optionally allowed for convenience as well.
        """
        # Provide list regardless of attribute type.
        for provider in [p for p in self.tag_providers
                         if not filter or p.get_taggable_realm() in filter]:
            for resource, tags in \
                    provider.get_tagged_resources(req, old_tags):
                old_tags = set(old_tags)
                if old_tags.issuperset(tags) and not new_tag:
                    if allow_delete:
                        self.delete_tags(req, resource, None, comment)
                else:
                    s_tags = set(tags)
                    eff_tags = s_tags - old_tags
                    if new_tag:
                        eff_tags.add(new_tag)
                    # Prevent to touch resources without effective change.
                    if eff_tags != s_tags and (allow_delete or new_tag):
                        self.set_tags(req, resource, eff_tags, comment)

    def delete_tags(self, req, resource, tags=None, comment=u''):
        """Delete tags on a resource.

        If tags is None, remove all tags on the resource.
        """
        provider = self._get_provider(resource.realm)
        if tags is None:
            try:
                provider.remove_resource_tags(req, resource, comment)
            except TypeError:
                 # Handle old style tag providers gracefully.
                provider.remove_resource_tags(req, resource)
        else:
            current_tags = set(provider.get_resource_tags(req, resource))
            current_tags.difference_update(tags)
            try:
                provider.set_resource_tags(req, resource, current_tags,
                                           comment)
            except TypeError:
                 # Handle old style tag providers gracefully.
                provider.set_resource_tags(req, resource, current_tags)

    def describe_tagged_resource(self, req, resource):
        """Returns a short description of a taggable resource."""
        provider = self._get_provider(resource.realm)
        try:
            return provider.describe_tagged_resource(req, resource)
        except (AttributeError, NotImplementedError):
            # Fallback to resource provider method.
            self.env.log.info('ITagProvider %r does not implement '
                              'describe_tagged_resource()' % provider)
            return get_resource_description(self.env, resource, 'summary')

    # IPermissionRequestor method
    def get_permission_actions(self):
        action = ['TAGS_VIEW', 'TAGS_MODIFY']
        actions = [action[0], (action[1], [action[0]]),
                   ('TAGS_ADMIN', action)]
        return actions

    # IResourceManager methods

    def get_resource_realms(self):
        yield 'tag'

    def get_resource_url(self, resource, href, form_realms=None, **kwargs):
        if self.wiki_page_link:
            page = WikiPage(self.env, self.wiki_page_prefix + resource.id)
            if page.exists:
                return get_resource_url(self.env, page.resource, href,
                                        **kwargs)
        if form_realms:
            return href.tags(form_realms, q=unicode(resource.id), **kwargs)
        return href.tags(unicode(resource.id), form_realms, **kwargs)

    def get_resource_description(self, resource, format='default',
                                 context=None, **kwargs):
        if self.wiki_page_link:
            page = WikiPage(self.env, self.wiki_page_prefix + resource.id)
            if page.exists:
                return get_resource_description(self.env, page.resource,
                                                format, **kwargs)
        rid = to_unicode(resource.id)
        if format in ('compact', 'default'):
            return rid
        else:
            return u'tag:%s' % rid

    # Internal methods

    def _populate_provider_map(self):
        if self._realm_provider_map is None:
            # Only use the map once it is fully initialized.
            map = dict((provider.get_taggable_realm(), provider)
                       for provider in self.tag_providers)
            self._realm_provider_map = map

    def _get_provider(self, realm):
        try:
            return self._realm_provider_map[realm]
        except KeyError:
            raise InvalidTagRealm(_("Tags are not supported on the '%s' realm")
                                  % realm)


class RequestsProxy(object):

    def __init__(self):
        self.current = threading.local()

    def get(self):
        try:
            return self.current.req
        except:
            return None

    def set(self, req):
        self.current.req = req

    def reset(self):
        self.current.req = None


requests = RequestsProxy()