Exemplo n.º 1
0
    def extras(self) -> List["Flattenable"]:
        r = super().extras()

        sourceHref = util.srclink(self.ob)
        source: "Flattenable"
        if sourceHref:
            source = (" ",
                      tags.a("(source)", href=sourceHref, class_="sourceLink"))
        else:
            source = tags.transparent
        r.append(
            tags.p(
                tags.code(tags.span("class", class_='py-keyword'), " ",
                          tags.span(self.ob.name, class_='py-defname'),
                          self.classSignature(), ":", source)))

        scs = sorted(self.ob.subclasses, key=objects_order)
        if not scs:
            return r
        p = assembleList(self.ob.system, "Known subclasses: ",
                         [o.fullName() for o in scs], "moreSubclasses",
                         self.page_url)
        if p is not None:
            r.append(tags.p(p))
        return r
Exemplo n.º 2
0
def format_docstring(obj: model.Documentable) -> Tag:
    """Generate an HTML representation of a docstring"""

    doc, source = get_docstring(obj)

    # Use cached or split version if possible.
    pdoc = obj.parsed_docstring

    if source is None:
        if pdoc is None:
            # We don't use 'source' if pdoc is None, but mypy is not that
            # sophisticated, so we fool it by assigning a dummy object.
            source = obj
        else:
            # A split field is documented by its parent.
            source = obj.parent
            assert source is not None

    if pdoc is None and doc is not None:
        pdoc = parse_docstring(obj, doc, source)
        obj.parsed_docstring = pdoc

    ret: Tag = tags.div
    if pdoc is None:
        ret(tags.p(class_='undocumented')("Undocumented"))
    else:
        try:
            stan = pdoc.to_stan(_EpydocLinker(source))
        except Exception as e:
            errs = [ParseError(f'{e.__class__.__name__}: {e}', 1)]
            if doc is None:
                stan = tags.p(class_="undocumented")('Broken description')
            else:
                pdoc_plain = pydoctor.epydoc.markup.plaintext.parse_docstring(
                    doc, errs)
                stan = pdoc_plain.to_stan(_EpydocLinker(source))
            reportErrors(source, errs)
        if stan.tagName:
            ret(stan)
        else:
            ret(*stan.children)

    fh = FieldHandler(obj)
    if isinstance(obj, model.Function):
        fh.set_param_types_from_annotations(obj.annotations)
    if pdoc is not None:
        for field in pdoc.fields:
            fh.handle(Field.from_epydoc(field, source))
    if isinstance(obj, model.Function):
        fh.resolve_types()
    ret(fh.format())
    return ret
Exemplo n.º 3
0
        def generateTabsAndContent(results):
            """
            results is a dictionary whose keys are normalized ASCII chars and
            whose values are the original (possible unicode) chars that map to
            the ASCII ones.
            """
            tabs = []
            contents = []
            for asciiLetter in sorted(results.keys()):
                if not asciiLetter:
                    continue
                for letter in sorted(results[asciiLetter]):
                    tab = tags.li(
                        tags.a(
                            letter.upper(),
                            href="#l%s" % letter,
                            **{"data-toggle": "tab"})
                        )
                    tabs.append(tab)
                    content = tags.div(
                        tags.p("holding content"),
                        class_="tab-pane",
                        id="l%s" % letter)
                    contents.append(content)

            return tags.div(
                tags.ul(tabs, class_="nav nav-tabs"),
                tags.div(contents, class_="tab-content"),
                class_="tabbable tabs-left")
Exemplo n.º 4
0
        def generateTabsAndContent(results):
            """
            results is a dictionary whose keys are normalized ASCII chars and
            whose values are the original (possible unicode) chars that map to
            the ASCII ones.
            """
            tabs = []
            contents = []
            for asciiLetter in sorted(results.keys()):
                if not asciiLetter:
                    continue
                for letter in sorted(results[asciiLetter]):
                    tab = tags.li(
                        tags.a(letter.upper(),
                               href="#l%s" % letter,
                               **{"data-toggle": "tab"}))
                    tabs.append(tab)
                    content = tags.div(tags.p("holding content"),
                                       class_="tab-pane",
                                       id="l%s" % letter)
                    contents.append(content)

            return tags.div(tags.ul(tabs, class_="nav nav-tabs"),
                            tags.div(contents, class_="tab-content"),
                            class_="tabbable tabs-left")
Exemplo n.º 5
0
    def render_POST(self, request):
        uri = request.args.get('uri', [])
        if not uri or not tahoeRegex.match(uri[0]):
            return self.render_GET(request)
        ext = request.args.get('ext', [])

        b64uri = base64.urlsafe_b64encode(uri[0])
        extension = ''
        if ext and ext[0]:
            extension = '.' + ext[0].lstrip('.')
        if uri[0] not in self.shortdb:
            while True:
                short = crockford.b32encode(os.urandom(9)).lower()
                if short not in self.shortdb:
                    break
            self.shortdb[short] = uri[0]
            self.shortdb[uri[0]] = short
            self.shortdb.sync()
        else:
            short = self.shortdb[uri[0]]

        if request.args.get('api', []):
            return '/' + short + extension

        body = tags.p(tags.a('long url', href=b64uri + extension), '; ',
                      tags.a('medium url', href='/' + uri[0] + extension),
                      '; ', tags.a('short url', href=short + extension))
        return renderElement(request, body)
Exemplo n.º 6
0
    def render_POST(self, request):
        uri = request.args.get('uri', [])
        if not uri or not tahoeRegex.match(uri[0]):
            return self.render_GET(request)
        ext = request.args.get('ext', [])

        b64uri = base64.urlsafe_b64encode(uri[0])
        extension = ''
        if ext and ext[0]:
            extension = '.' + ext[0].lstrip('.')
        if uri[0] not in self.shortdb:
            while True:
                short = crockford.b32encode(os.urandom(9)).lower()
                if short not in self.shortdb:
                    break
            self.shortdb[short] = uri[0]
            self.shortdb[uri[0]] = short
            self.shortdb.sync()
        else:
            short = self.shortdb[uri[0]]

        if request.args.get('api', []):
            return '/' + short + extension

        body = tags.p(
            tags.a('long url', href=b64uri + extension), '; ',
            tags.a('medium url', href='/' + uri[0] + extension), '; ',
            tags.a('short url', href=short + extension))
        return renderElement(request, body)
Exemplo n.º 7
0
    def extras(self):
        r = [super(ZopeInterfaceClassPage, self).extras()]
        system = self.ob.system

        def tl(s):
            if s in system.allobjects:
                return taglink(system.allobjects[s])
            else:
                return s

        if self.ob.isinterface:
            namelist = sorted(
                [o.fullName() for o in self.ob.implementedby_directly],
                key=lambda x: x.lower())
            label = 'Known implementations: '
        else:
            namelist = sorted(self.ob.implements_directly,
                              key=lambda x: x.lower())
            label = 'Implements interfaces: '
        if namelist:
            l = maybeShortenList(self.ob.system, label, namelist,
                                 "moreInterface")
            if l is not None:
                r.append(tags.p(l))
        return r
Exemplo n.º 8
0
 def render(ign, ored: object) -> Tag:
     return tags.p(
         "hello, ",
         tags.transparent(render="test"),
         " - ",
         tags.transparent(render="test"),
     )
Exemplo n.º 9
0
 def render(ign, ored):
     return tags.p(
         "hello, ",
         tags.transparent(render="test"),
         " - ",
         tags.transparent(render="test"),
     )
Exemplo n.º 10
0
 def test_serializeDeferredSlots(self):
     """
     Test that a slot with a deferred as its value will be flattened using
     the value from the deferred.
     """
     t = tags.p(slot('test'))
     t.fillSlots(test=succeed(tags.em('four>')))
     return self.assertFlattensTo(t, '<p><em>four&gt;</em></p>')
Exemplo n.º 11
0
 def test_serializeDeferredSlots(self):
     """
     Test that a slot with a deferred as its value will be flattened using
     the value from the deferred.
     """
     t = tags.p(slot("test"))
     t.fillSlots(test=succeed(tags.em("four>")))
     return self.assertFlattensTo(t, b"<p><em>four&gt;</em></p>")
Exemplo n.º 12
0
 def test_serializeSlots(self):
     """
     Test that flattening a slot will use the slot value from the tag.
     """
     t1 = tags.p(slot("test"))
     t2 = t1.clone()
     t2.fillSlots(test="hello, world")
     self.assertFlatteningRaises(t1, UnfilledSlot)
     self.assertFlattensImmediately(t2, b"<p>hello, world</p>")
Exemplo n.º 13
0
 def extras(self):
     r = super(ClassPage, self).extras()
     scs = sorted(self.ob.subclasses, key=lambda o: o.fullName().lower())
     if not scs:
         return r
     p = assembleList(self.ob.system, "Known subclasses: ", [o.fullName() for o in scs], "moreSubclasses")
     if p is not None:
         r.append(tags.p(p))
     return r
Exemplo n.º 14
0
 def extras(self):
     r = super(ClassPage, self).extras()
     scs = sorted(self.ob.subclasses, key=lambda o: o.fullName().lower())
     if not scs:
         return r
     p = assembleList(self.ob.system, "Known subclasses: ",
                      [o.fullName() for o in scs], "moreSubclasses")
     if p is not None:
         r.append(tags.p(p))
     return r
Exemplo n.º 15
0
 def test_serializeSlots(self):
     """
     Test that flattening a slot will use the slot value from the tag.
     """
     t1 = tags.p(slot("test"))
     t2 = t1.clone()
     t2.fillSlots(test="hello, world")
     return gatherResults(
         [self.assertFlatteningRaises(t1, UnfilledSlot), self.assertFlattensTo(t2, "<p>hello, world</p>")]
     )
Exemplo n.º 16
0
 def packageInitTable(self):
     init = self.ob.contents['__init__']
     children = sorted(
         [o for o in init.orderedcontents if o.isVisible],
         key=lambda o2:(-o2.privacyClass, o2.fullName()))
     if children:
         return [tags.p("From the __init__.py module:"),
                 ChildTable(self.docgetter, init, self.usesorttable, children)]
     else:
         return ()
Exemplo n.º 17
0
 def packageInitTable(self):
     init = self.ob.contents['__init__']
     children = sorted([o for o in init.orderedcontents if o.isVisible],
                       key=lambda o2: (-o2.privacyClass, o2.fullName()))
     if children:
         return [
             tags.p("From the __init__.py module:"),
             ChildTable(self.docgetter, init, self.usesorttable, children)
         ]
     else:
         return ()
Exemplo n.º 18
0
    def render_GET(self, request):
        applications = []
        for app in self.registry.applications.values():
            link = tags.a(tags.tt(app.name), ' at ', tags.tt(app.path.path),
                          href=app.name)
            applications.append(tags.li(link))

        body = tags.body(
            tags.p('Here are your applications:'),
            tags.ul(*applications))
        return renderElement(request, body)
Exemplo n.º 19
0
 def test_serializeSlots(self):
     """
     Test that flattening a slot will use the slot value from the tag.
     """
     t1 = tags.p(slot('test'))
     t2 = t1.clone()
     t2.fillSlots(test='hello, world')
     return gatherResults([
         self.assertFlatteningRaises(t1, UnfilledSlot),
         self.assertFlattensTo(t2, '<p>hello, world</p>'),
     ])
Exemplo n.º 20
0
 def packageInitTable(self):
     init = self.ob.contents['__init__']
     children = sorted(
         [o for o in init.orderedcontents if o.isVisible],
         key=lambda o2:(-o2.privacyClass.value, o2.fullName()))
     if children:
         return [tags.p("From the ", tags.code("__init__.py"), " module:",
                        class_="fromInitPy"),
                 ChildTable(self.docgetter, init, children)]
     else:
         return ()
Exemplo n.º 21
0
 def packageInitTable(self):
     init = self.ob.contents["__init__"]
     children = sorted(
         [o for o in init.orderedcontents if o.isVisible], key=lambda o2: (-o2.privacyClass, o2.fullName())
     )
     if children:
         return [
             tags.p("From the ", tags.code("__init__.py"), " module:", class_="fromInitPy"),
             ChildTable(self.docgetter, init, children),
         ]
     else:
         return ()
Exemplo n.º 22
0
    def extras(self):
        r = super().extras()

        sourceHref = util.srclink(self.ob)
        if sourceHref:
            source = (" ", tags.a("(source)", href=sourceHref))
        else:
            source = tags.transparent
        r.append(tags.p(tags.code(
            tags.span("class", class_='py-keyword'), " ",
            self.mediumName(self.ob), ":", source
            )))

        scs = sorted(self.ob.subclasses, key=lambda o:o.fullName().lower())
        if not scs:
            return r
        p = assembleList(self.ob.system, "Known subclasses: ",
                         [o.fullName() for o in scs], "moreSubclasses")
        if p is not None:
            r.append(tags.p(p))
        return r
Exemplo n.º 23
0
    def render_GET(self, request):
        applications = []
        for app in self.registry.applications.values():
            link = tags.a(tags.tt(app.name),
                          ' at ',
                          tags.tt(app.path.path),
                          href=app.name)
            applications.append(tags.li(link))

        body = tags.body(tags.p('Here are your applications:'),
                         tags.ul(*applications))
        return renderElement(request, body)
Exemplo n.º 24
0
 def extras(self):
     r = [super(ZopeInterfaceClassPage, self).extras()]
     if self.ob.isinterface:
         namelist = sorted([o.fullName() for o in self.ob.implementedby_directly], key=lambda x:x.lower())
         label = 'Known implementations: '
     else:
         namelist = sorted(self.ob.implements_directly, key=lambda x:x.lower())
         label = 'Implements interfaces: '
     if namelist:
         l = assembleList(self.ob.system, label, namelist, "moreInterface")
         if l is not None:
             r.append(tags.p(l))
     return r
Exemplo n.º 25
0
 def preview(self, request, tag):
     docstring = parse_str(self.docstring)
     stan, errors = epydoc2stan.doc2stan(
         self.ob, docstring=docstring)
     if self.isPreview or errors:
         if errors:
             #print stan, errors
             #assert isinstance(stan, tags.pre)
             [text] = stan.children
             lines = text.replace('\r\n', '\n').split('\n')
             line2err = {}
             for err in errors:
                 if isinstance(err, str):
                     ln = None
                 else:
                     ln = err.linenum()
                 line2err.setdefault(ln, []).append(err)
             w = len(str(len(lines)))
             for i, line in enumerate(lines):
                 i += 1
                 cls = "preview"
                 if i in line2err:
                     cls += " error"
                 tag(tags.pre(class_=cls)("%*s"%(w, i), ' ', line))
                 for err in line2err.get(i, []):
                     tag(tags.p(class_="errormessage")(err.descr()))
             i += 1
             for err in line2err.get(i, []):
                 tag(tags.p(class_="errormessage")(err.descr()))
             items = []
             for err in line2err.get(None, []):
                 items.append(tags.li(str(err)))
             if items:
                 tag(tags.ul(items))
         else:
             tag = tag(stan)
         return tag(tags.h2("Edit"))
     else:
         return ()
Exemplo n.º 26
0
 def extras(self):
     r = [super(ZopeInterfaceClassPage, self).extras()]
     if self.ob.isinterface:
         namelist = sorted([o.fullName() for o in self.ob.implementedby_directly], key=lambda x: x.lower())
         label = "Known implementations: "
     else:
         namelist = sorted(self.ob.implements_directly, key=lambda x: x.lower())
         label = "Implements interfaces: "
     if namelist:
         l = assembleList(self.ob.system, label, namelist, "moreInterface")
         if l is not None:
             r.append(tags.p(l))
     return r
Exemplo n.º 27
0
 def footer_right(self, request, tag):
     """
     '(c) 2014-2016 ',
     tags.a('Open Hive', href='http://open-hive.org/'), ' and ',
     tags.a('Hiveeyes', href='https://hiveeyes.org/docs/system/'), '. ',
     """
     return tag(tags.p(
         'Powered by ',
         tags.a('Kotori', href='https://getkotori.org/'), ', ',
         tags.a('InfluxDB', href='https://github.com/influxdata/influxdb'), ', ',
         tags.a('dygraphs', href='http://dygraphs.com/'), ' and ',
         tags.a('DataTables', href='https://datatables.net/'), '.'
     ))
Exemplo n.º 28
0
 def test_serializeUnicode(self):
     """
     Test that unicode is encoded correctly in the appropriate places, and
     raises an error when it occurs in inappropriate place.
     """
     snowman = "\N{SNOWMAN}"
     self.assertFlattensImmediately(snowman, b"\xe2\x98\x83")
     self.assertFlattensImmediately(tags.p(snowman), b"<p>\xe2\x98\x83</p>")
     self.assertFlattensImmediately(Comment(snowman), b"<!--\xe2\x98\x83-->")
     self.assertFlattensImmediately(CDATA(snowman), b"<![CDATA[\xe2\x98\x83]]>")
     self.assertFlatteningRaises(Tag(snowman), UnicodeEncodeError)
     self.assertFlatteningRaises(
         Tag("p", attributes={snowman: ""}), UnicodeEncodeError
     )
Exemplo n.º 29
0
 def packageInitTable(self) -> "Flattenable":
     children = sorted((o for o in self.ob.contents.values()
                        if not isinstance(o, model.Module) and o.isVisible),
                       key=objects_order)
     if children:
         loader = ChildTable.lookup_loader(self.template_lookup)
         return [
             tags.p("From ",
                    tags.code("__init__.py"),
                    ":",
                    class_="fromInitPy"),
             ChildTable(self.docgetter, self.ob, children, loader)
         ]
     else:
         return ()
Exemplo n.º 30
0
 def test_serializeUnicode(self):
     """
     Test that unicode is encoded correctly in the appropriate places, and
     raises an error when it occurs in inappropriate place.
     """
     snowman = u'\N{SNOWMAN}'
     return gatherResults([
         self.assertFlattensTo(snowman, '\xe2\x98\x83'),
         self.assertFlattensTo(tags.p(snowman), '<p>\xe2\x98\x83</p>'),
         self.assertFlattensTo(Comment(snowman), '<!--\xe2\x98\x83-->'),
         self.assertFlattensTo(CDATA(snowman), '<![CDATA[\xe2\x98\x83]]>'),
         self.assertFlatteningRaises(Tag(snowman), UnicodeEncodeError),
         self.assertFlatteningRaises(Tag('p', attributes={snowman: ''}),
                                     UnicodeEncodeError),
     ])
Exemplo n.º 31
0
 def test_serializeUnicode(self):
     """
     Test that unicode is encoded correctly in the appropriate places, and
     raises an error when it occurs in inappropriate place.
     """
     snowman = u'\N{SNOWMAN}'
     return gatherResults([
         self.assertFlattensTo(snowman, '\xe2\x98\x83'),
         self.assertFlattensTo(tags.p(snowman), '<p>\xe2\x98\x83</p>'),
         self.assertFlattensTo(Comment(snowman), '<!--\xe2\x98\x83-->'),
         self.assertFlattensTo(CDATA(snowman), '<![CDATA[\xe2\x98\x83]]>'),
         self.assertFlatteningRaises(
             Tag(snowman), UnicodeEncodeError),
         self.assertFlatteningRaises(
             Tag('p', attributes={snowman: ''}), UnicodeEncodeError),
     ])
Exemplo n.º 32
0
 def extras(self) -> List["Flattenable"]:
     r = super().extras()
     if self.ob.isinterface:
         namelist = [
             o.fullName() for o in sorted(self.ob.implementedby_directly,
                                          key=objects_order)
         ]
         label = 'Known implementations: '
     else:
         namelist = sorted(self.ob.implements_directly,
                           key=lambda x: x.lower())
         label = 'Implements interfaces: '
     if namelist:
         l = assembleList(self.ob.system, label, namelist, "moreInterface",
                          self.page_url)
         if l is not None:
             r.append(tags.p(l))
     return r
Exemplo n.º 33
0
 def extras(self):
     r = [super(ZopeInterfaceClassPage, self).extras()]
     system = self.ob.system
     def tl(s):
         if s in system.allobjects:
             return taglink(system.allobjects[s])
         else:
             return s
     if self.ob.isinterface:
         namelist = sorted([o.fullName() for o in self.ob.implementedby_directly], key=lambda x:x.lower())
         label = 'Known implementations: '
     else:
         namelist = sorted(self.ob.implements_directly, key=lambda x:x.lower())
         label = 'Implements interfaces: '
     if namelist:
         l = maybeShortenList(self.ob.system, label, namelist, "moreInterface")
         if l is not None:
             r.append(tags.p(l))
     return r
Exemplo n.º 34
0
def format_docstring(obj):
    """Generate an HTML representation of a docstring"""

    doc, source = get_docstring(obj)

    # Use cached or split version if possible.
    pdoc = getattr(obj, 'parsed_docstring', None)

    if pdoc is None:
        if doc is None:
            return tags.div(class_='undocumented')("Undocumented")
        pdoc = parse_docstring(obj, doc, source)
        obj.parsed_docstring = pdoc
    elif source is None:
        # A split field is documented by its parent.
        source = obj.parent

    try:
        stan = pdoc.to_stan(_EpydocLinker(source))
    except Exception as e:
        errs = ['%s: %s' % (e.__class__.__name__, e)]
        if doc is None:
            stan = tags.p(class_="undocumented")('Broken description')
        else:
            pdoc_plain = pydoctor.epydoc.markup.plaintext.parse_docstring(
                doc, errs)
            stan = pdoc_plain.to_stan(_EpydocLinker(source))
        reportErrors(source, errs)

    content = [stan] if stan.tagName else stan.children
    fields = pdoc.fields
    s = tags.div(*content)
    if fields:
        fh = FieldHandler(obj)
        for field in fields:
            fh.handle(Field(field, obj))
        fh.resolve_types()
        s(fh.format())
    return s
Exemplo n.º 35
0
 def render(ign, ored):
     return tags.p("hello, ", tags.transparent(render="test"), " - ", tags.transparent(render="test"))
Exemplo n.º 36
0
 def header(self, request, tag):
     return tag(tags.p('Templated content.'), id='content')
Exemplo n.º 37
0
 def render(ign,ored):
     return tags.p(
         'hello, ',
         tags.transparent(render='test'), ' - ',
         tags.transparent(render='test'))
Exemplo n.º 38
0
 def tags(self, tag):
     author = tags.span(self.author, class_="author")
     timestamp = self.timestamp.asDatetime().strftime("%m/%d/%y(%a)%H:%M")
     number = "No. %d" % self.number
     comment = tags.p(self.comment)
     return tag(author, timestamp, number, comment)
Exemplo n.º 39
0
 def footer(self, request, tag):
     return tag(tags.p('[1, 2, 3, 4, 5, 6].'), id='extra_info')
Exemplo n.º 40
0
 def header(self, request, tag):
     return tag(tags.p('Header'), id='header')
Exemplo n.º 41
0
 def header(self, request, tag):
     return tag(tags.p(tags.b("Header")), id="header")
Exemplo n.º 42
0
 def render(ign, ored):
     return tags.p('hello, ', tags.transparent(render='test'),
                   ' - ', tags.transparent(render='test'))
Exemplo n.º 43
0
 def header(self, request, tag):
     return tag(tags.p('Header.'), id='header')
Exemplo n.º 44
0
 def header(self, request, tag):
     return tag(tags.p(tags.b("Header")), id="header")
Exemplo n.º 45
0
 def footer(self, request, tag):
     return tag(tags.p('Footer.'), id='footer')
Exemplo n.º 46
0
 def header(self, request, tag):
     return tag(tags.p('This is very different'), id='more_info')
Exemplo n.º 47
0
 def to_stan(self, docstring_linker):
     return tags.p(self._text, class_='pre')
Exemplo n.º 48
0
 def footer(self, request, tag):
     return tag(tags.p("Footer."), id="footer")
Exemplo n.º 49
0
 def footer(self, request, tag):
     return tag(tags.p('Footer.'), id='footer')
Exemplo n.º 50
0
 def body(self, request, tag):
     return tag(tags.p('So very different'), id='content')
Exemplo n.º 51
0
 def footer_left(self, request, tag):
     return tag(tags.p('Query expression (times are UTC): ', self.bucket.tdata.expression))