[ext/rest] add directive bookmark to rest (closes #2545595)

authorNicolas Chauvat <nicolas.chauvat@logilab.fr>
changeset4e1f7847116f
branchdefault
phasedraft
hiddenyes
parent revision#0020aa12af07 [c-c create] make post-create step optional (closes #2712041)
child revision<not specified>
files modified by this revision
doc/book/en/tutorials/index.rst
doc/book/en/tutorials/textreports/index.rst
ext/rest.py
ext/test/unittest_rest.py
# HG changeset patch
# User Nicolas Chauvat <nicolas.chauvat@logilab.fr>
# Date 1364252135 -3600
# Mon Mar 25 23:55:35 2013 +0100
# Node ID 4e1f7847116f233ae8d8db38f7b5934d1a9eeef0
# Parent 0020aa12af07a45200041ac858a0becf8e2330c3
[ext/rest] add directive bookmark to rest (closes #2545595)

diff --git a/doc/book/en/tutorials/index.rst b/doc/book/en/tutorials/index.rst
@@ -16,5 +16,6 @@
1     :numbered:
2 
3     base/index
4     advanced/index
5     tools/windmill.rst
6 +   textreports/index
diff --git a/doc/book/en/tutorials/textreports/index.rst b/doc/book/en/tutorials/textreports/index.rst
@@ -0,0 +1,13 @@
7 +.. -*- coding: utf-8 -*-
8 +
9 +Writing text reports with RestructuredText
10 +==========================================
11 +
12 +|cubicweb| offers several text formats for the RichString type used in schemas,
13 +including restructuredtext.
14 +
15 +Three additional restructuredtext roles are defined by |cubicweb|:
16 +
17 +.. autodocfunction:: cubicweb.ext.rest.eid_reference_role
18 +.. autodocfunction:: cubicweb.ext.rest.rql_role
19 +.. autodocfunction:: cubicweb.ext.rest.bookmark_role
diff --git a/ext/rest.py b/ext/rest.py
@@ -34,10 +34,11 @@
20 
21  from cStringIO import StringIO
22  from itertools import chain
23  from logging import getLogger
24  from os.path import join
25 +from urlparse import urlsplit
26 
27  from docutils import statemachine, nodes, utils, io
28  from docutils.core import Publisher
29  from docutils.parsers.rst import Parser, states, directives
30  from docutils.parsers.rst.roles import register_canonical_role, set_classes
@@ -126,10 +127,67 @@
31      except Exception as exc:
32          content = 'an error occured while interpreting this rql directive: %r' % exc
33      set_classes(options)
34      return [nodes.raw('', content, format='html')], []
35 
36 +def bookmark_role(role, rawtext, text, lineno, inliner, options={}, content=[]):
37 +    """:bookmark:`<bookmark-eid>` or :bookmark:`<eid>:<vid>`
38 +
39 +    Example: :bookmark:`1234:table`
40 +
41 +    Replace the directive with the output of applying the view to the resultset
42 +    returned by the query stored in the bookmark. By default, the view is the one
43 +    stored in the bookmark, but it can be overridden by the directive as in the
44 +    example above.
45 +
46 +    "X eid %(userid)s" can be used in the RQL query stored in the Bookmark, for
47 +    this query will be executed with the argument {'userid': _cw.user.eid}.
48 +    """
49 +    _cw = inliner.document.settings.context._cw
50 +    text = text.strip()
51 +    try:
52 +        if ':' in text:
53 +            eid, vid = text.rsplit(u':', 1)
54 +            eid = int(eid)
55 +        else:
56 +            eid, vid = int(text), None
57 +    except ValueError:
58 +        msg = inliner.reporter.error(
59 +            'EID number must be a positive number; "%s" is invalid.'
60 +            % text, line=lineno)
61 +        prb = inliner.problematic(rawtext, rawtext, msg)
62 +        return [prb], [msg]
63 +    try:
64 +        bookmark = _cw.entity_from_eid(eid)
65 +    except UnknownEid:
66 +        msg = inliner.reporter.error('Unknown EID %s.' % text, line=lineno)
67 +        prb = inliner.problematic(rawtext, rawtext, msg)
68 +        return [prb], [msg]
69 +    try:
70 +        params = dict(_cw.url_parse_qsl(urlsplit(bookmark.path).query))
71 +        rql = params['rql']
72 +        if vid is None:
73 +            vid = params.get('vid')
74 +    except (ValueError, KeyError), exc:
75 +        msg = inliner.reporter.error('Could not parse bookmark path %s [%s].'
76 +                                     % (bookmark.path, exc), line=lineno)
77 +        prb = inliner.problematic(rawtext, rawtext, msg)
78 +        return [prb], [msg]
79 +    try:
80 +        rset = _cw.execute(rql, {'userid': _cw.user.eid})
81 +        if rset:
82 +            if vid is None:
83 +                vid = vid_from_rset(_cw, rset, _cw.vreg.schema)
84 +        else:
85 +            vid = 'noresult'
86 +        view = _cw.vreg['views'].select(vid, _cw, rset=rset)
87 +        content = view.render()
88 +    except Exception, exc:
89 +        content = 'An error occured while interpreting directive bookmark: %r' % exc
90 +    set_classes(options)
91 +    return [nodes.raw('', content, format='html')], []
92 +
93  def winclude_directive(name, arguments, options, content, lineno,
94                         content_offset, block_text, state, state_machine):
95      """Include a reST file as part of the content of this reST file.
96 
97      same as standard include directive but using config.locate_doc_resource to
@@ -321,8 +379,9 @@
98      if _INITIALIZED:
99          return
100      _INITIALIZED = True
101      register_canonical_role('eid', eid_reference_role)
102      register_canonical_role('rql', rql_role)
103 +    register_canonical_role('bookmark', bookmark_role)
104      directives.register_directive('winclude', winclude_directive)
105      if pygments_directive is not None:
106          directives.register_directive('sourcecode', pygments_directive)
diff --git a/ext/test/unittest_rest.py b/ext/test/unittest_rest.py
@@ -73,7 +73,14 @@
107      def test_rql_role_without_vid(self):
108          context = self.context()
109          out = rest_publish(context, ':rql:`Any X WHERE X is CWUser`')
110          self.assertEqual(out, u'<p><h1>CWUser_plural</h1><div class="section"><a href="http://testing.fr/cubicweb/cwuser/admin" title="">admin</a></div><div class="section"><a href="http://testing.fr/cubicweb/cwuser/anon" title="">anon</a></div></p>\n')
111 
112 +    def test_bookmark_role(self):
113 +        context = self.context()
114 +        rset = self.execute('INSERT Bookmark X: X title "hello", X path "/view?rql=Any X WHERE X is CWUser"')
115 +        eid = rset[0][0]
116 +        out = rest_publish(context, ':bookmark:`%s`' % eid)
117 +        self.assertEqual(out, u'<p><h1>CWUser_plural</h1><div class="section"><a href="http://testing.fr/cubicweb/cwuser/admin" title="">admin</a></div><div class="section"><a href="http://testing.fr/cubicweb/cwuser/anon" title="">anon</a></div></p>\n')
118 +
119  if __name__ == '__main__':
120      unittest_main()