Beispiel #1
0
 def replace(self, a, b, comments=None):
     if isinstance(b, type('')):
         b = self.element(b)
     if comments is None:
         if b is None:
             comments = ['Removed deprecated tag <%s/>' % (a.tag, )]
         else:
             comments = ['Replaced <%s/> with <%s/>' % (a.tag, b.tag)]
     if not isinstance(comments, list):
         comments = [comments]
     p = a.getparent()
     if p != None:
         i = p.index(a)
         c = None
         if self.options.verbose:
             for comment in comments:
                 c = Comment(" v2v3: %s " % comment.strip())
                 c.tail = ''
                 p.insert(i, c)
                 i += 1
         if not b is None:
             if a.text and a.text.strip():
                 b.text = a.text
             if a.tail != None:
                 b.tail = a.tail
             if a.sourceline:
                 b.sourceline = a.sourceline
             copyattr(a, b)
             for child in a.iterchildren():
                 b.append(child)  # moves child from a to b
             p.replace(a, b)
         else:
             if iscomment(a):
                 a.text = ''
             for text in [a.text, a.tail]:
                 if text:
                     if c is None:
                         p.text = p.text + text if p.text else text
                     else:
                         c.tail += text
             p.remove(a)
     if b != None and a.sourceline:
         b.sourceline = a.sourceline
     return b
Beispiel #2
0
    def start_library(self):
        console = self.console

        from ...tools import get_moya_dir
        from os.path import join, abspath
        project_path = None
        if self.args.location is not None:
            library_path = self.args.location
        else:
            try:
                project_path = get_moya_dir(self.args.project_location)
            except:
                console.error("Please run 'moya start library' inside your project directory, or specifiy the -o switch")
                return False
            library_path = abspath(join(project_path, './local/'))

        cfg = None
        if not self.args.location and project_path:
            from ... import build
            cfg = build.read_config(project_path, self.get_settings())

        if not self.args.acceptdefaults:
            console.table([[Cell("Moya Library Wizard", bold=True, fg="green", center=True)],
                          ["""This will ask you a few questions, then create a new library in your Moya project based on your answers.

Default values are shown in grey (simply hit return to accept defaults). Some defaults may be taken from your ".bashrc" file, if it exists.
"""]])
        author = self.get_author_details()
        library = {}
        library["title"] = LibraryTitle.ask(console, default=self.args.title)
        longname = self.args.longname or make_name(author["organization"], library["title"])
        longname = library["longname"] = LibraryLongName.ask(console, default=longname)
        library["url"] = LibraryURL.ask(console, default="")
        library["namespace"] = LibraryNamespace.ask(console, default="")
        mount = None
        appname = None

        do_mount = DoMount.ask(console, default="yes")
        if do_mount:
            mount = Mount.ask(console, default=self.args.mount or "/{}/".format(make_name(library["title"])))
            appname = AppName.ask(console, default=self.args.name or make_name(library["title"]))

        data = dict(author=author,
                    library=library,
                    timezone=self.get_timezone())

        actions = []

        from ...command.sub import library_template
        from fs.memoryfs import MemoryFS
        from fs.opener import fsopendir
        memfs = MemoryFS()
        templatebuilder.compile_fs_template(memfs,
                                            library_template.template,
                                            data=data)
        dest_fs = fsopendir(join(library_path, library["longname"]), create_dir=True, writeable=True)

        continue_overwrite = 'overwrite'
        if not dest_fs.isdirempty('.'):
            if self.args.force:
                continue_overwrite = 'overwrite'
            elif self.args.new:
                continue_overwrite = 'new'
            else:
                continue_overwrite = DirNotEmpty.ask(console, default="cancel")

        if continue_overwrite != 'cancel':
            if continue_overwrite == 'overwrite':
                from fs.utils import copydir
                copydir(memfs, dest_fs)
                actions.append("Written library files to {}".format(dest_fs.getsyspath('.')))
            elif continue_overwrite == 'new':
                files_copied = copy_new(memfs, dest_fs)
                table = [[
                         Cell("{} new file(s) written".format(len(files_copied)), fg="green", bold=True, center=True),
                         ]]
                for path in files_copied:
                    table.append([Cell(dest_fs.desc(path), bold=True, fg="black")])
                console.table(table)
                return 0

            if cfg:
                project_cfg = cfg['project']
                location = project_cfg['location']
                server_name = "main"

                if location:
                    with fsopendir(project_path) as project_fs:
                        with project_fs.opendir(location) as server_fs:
                            from lxml.etree import fromstring, ElementTree, parse
                            from lxml.etree import XML, Comment
                            server_xml_path = server_fs.getsyspath(project_cfg['startup'])
                            root = parse(server_xml_path)
                            import_tag = XML('<import location="./local/{longname}" />\n\n'.format(**library))
                            import_tag.tail = "\n"
                            install_tag = None

                            if mount:
                                tag = '<install name="{appname}" lib="{longname}" mount="{mount}" />'
                            else:
                                tag = '<install name="{appname}" lib="{longname}" />'
                            install_tag = XML(tag.format(appname=appname,
                                                         longname=longname,
                                                         mount=mount))
                            install_tag.tail = "\n\n"

                            def has_child(node, tag, **attribs):
                                for el in node.findall(tag):
                                    #items = dict(el.items())
                                    if all(el.get(k, None) == v for k, v in attribs.items()):
                                        return True
                                return False

                            for server in root.findall("{{http://moyaproject.com}}server[@docname='{}']".format(server_name)):
                                add_import_tag = not has_child(server, "{http://moyaproject.com}import", location="./local/{}".format(longname))
                                add_install_tag = not has_child(server, "{http://moyaproject.com}install", lib=longname) and install_tag is not None

                                if add_import_tag or add_install_tag:
                                    comment = Comment("Added by 'moya start library'")
                                    comment.tail = "\n"
                                    server.append(comment)
                                if add_import_tag:
                                    server.append(import_tag)
                                    actions.append("Added <import> tag")
                                if add_install_tag:
                                    server.append(install_tag)
                                    actions.append("Added <install> tag")
                                    if mount:
                                        actions.append("Mounted application on {}".format(mount))

                            root.write(server_xml_path)

            table = [[Cell("Library files written successfully!", fg="green", bold=True, center=True)]]

            actions_text = "\n".join(" * " + action for action in actions)
            table.append([Cell(actions_text, fg="blue", bold=True)])
            table.append(["""A new library has been added to the project, containing some simple example functionality.\nSee http://moyaproject.com/docs/creatinglibraries/ for more information."""])
            console.table(table)

            return 0

        console.text("No project files written.", fg="red", bold=True).nl()
        return -1
Beispiel #3
0
    def convert2to3(self):
        if self.root.get('version') in [
                '3',
        ]:
            return self.tree
        log.note(' Converting v2 to v3: %s' % self.xmlrfc.source)

        selectors = [
            # we need to process list before block elements that might get
            # promoted out of their surrounding <t/>, as <list/> uses one <t/>
            # per list item, and if we promote block elements earlier, they
            # will not be picked up as part of the list items
            './/list',  # 3.4.  <list>
            #
            './/artwork',  # 2.5.  <artwork>
            # 2.5.4.  "height" Attribute
            # 2.5.8.  "width" Attribute
            # 2.5.9.  "xml:space" Attribute
            './/back',
            './/code',
            './/date',
            # We need to process preamble and postamble before figure,
            # because artwork or sourcecode within a figure could later be
            # promoted and the figure discarded.
            './/postamble',  # 3.5.  <postamble>
            './/preamble',  # 3.6.  <preamble>
            './/figure',  # 2.25.  <figure>
            # 2.25.1.  "align" Attribute
            # 2.25.2.  "alt" Attribute
            # 2.25.4.  "height" Attribute
            # 2.25.5.  "src" Attribute
            # 2.25.6.  "suppress-title" Attribute
            # 2.25.8.  "width" Attribute
            './/relref',  # Deprecated after 7991
            './/reference',  #        <reference>
            '.',  # 2.45.  <rfc>
            # 2.45.1.  "category" Attribute
            # 2.45.2.  "consensus" Attribute
            # 2.45.3.  "docName" Attribute
            # 2.45.7.  "number" Attribute
            # 2.45.10.  "seriesNo" Attribute
            #Disabled
            #'.//seriesInfo',                # 2.47.  <seriesInfo>
            './/t',  # 2.53.  <t>
            # 2.53.2.  "hangText" Attribute
            './/xref',  # 2.66.  <xref>
            # 2.66.1.  "format" Attribute
            # 2.66.2.  "pageno" Attribute
            './/facsimile',  # 3.2.  <facsimile>
            './/format',  # 3.3.  <format>
            './/spanx',  # 3.7.  <spanx>
            './/texttable',  # 3.8.  <texttable>
            './/vspace',  # 3.10.  <vspace>
            # attribute selectors
            './/*[@title]',
            # 2.25.7.  "title" Attribute
            # 2.33.2.  "title" Attribute
            # 2.42.2.  "title" Attribute
            # 2.46.4.  "title" Attribute
            './/*[@anchor]',
            './/xref[@target]',
            '//processing-instruction()',  # 1.3.2
            # handle mixed block/non-block content surrounding all block nodes
            './/*[self::artwork or self::dl or self::figure or self::ol or self::sourcecode or self::t or self::ul]',
            './/*[@*="yes" or @*="no"]',  # convert old attribute false/true
            '.;pretty_print_prep()',
            '.;wrap_non_ascii()',
        ]

        # replace the vocabulary v2 dtd, but keep some entity definitions.
        tree = self.tree
        tree.docinfo.system_url = "rfc2629-xhtml.ent"

        for s in selectors:
            slug = slugify(
                s.replace('self::', '').replace(' or ', '_').replace(';', '_'))
            if '@' in s:
                func_name = 'attribute_%s' % slug
            elif "()" in s:
                func_name = slug
            else:
                if not slug:
                    slug = 'rfc'
                func_name = 'element_%s' % slug
            # get rid of selector annotation
            ss = s.split(';')[0]
            func = getattr(self, func_name, None)
            if func:
                if self.options.debug:
                    log.note("Calling %s()" % func_name)
                for e in self.root.xpath(ss):
                    func(e, e.getparent())
            else:
                log.warn("No handler for function %s, slug %s" % (
                    func_name,
                    slug,
                ))

        self.root.set('version', '3')

        # Add a comment about the converter version
        conversion_version = Comment(' xml2rfc v2v3 conversion %s ' %
                                     xml2rfc.__version__)
        conversion_version.tail = '\n  '
        self.root.insert(0, conversion_version)

        # This is a workaround for not being able to do anything about
        # namespaces other than when creating an element.  It lets us retain
        # a namespace declaration for xi: in the root element.
        #         dummy = self.element('{http://www.w3.org/2001/XInclude}include', nsmap=self.xmlrfc.nsmap)
        #         self.root.insert(0, dummy)
        #         lxml.etree.cleanup_namespaces(self.root, top_nsmap=self.xmlrfc.nsmap, keep_ns_prefixes='xi')
        #         self.root.remove(dummy)
        log.note(' Completed v2 to v3 conversion')
        return self.tree
Beispiel #4
0
    def start_library(self):
        console = self.console

        from ...tools import get_moya_dir
        from os.path import join, abspath
        project_path = None
        if self.args.location is not None:
            library_path = self.args.location
        else:
            try:
                project_path = get_moya_dir(self.args.project_location)
            except:
                console.error("Please run 'moya start library' inside your project directory, or specifiy the -o switch")
                return False
            library_path = abspath(join(project_path, './local/'))

        cfg = None
        if not self.args.location and project_path:
            from ... import build
            cfg = build.read_config(project_path, self.get_settings())

        if not self.args.acceptdefaults:
            console.table([[Cell("Moya Library Wizard", bold=True, fg="green", center=True)],
                          ["""This will ask you a few questions, then create a new library in your Moya project based on your answers.

Default values are shown in grey (simply hit return to accept defaults). Some defaults may be taken from your ".bashrc" file, if it exists.
"""]])
        author = self.get_author_details()
        library = {}
        library["title"] = LibraryTitle.ask(console, default=self.args.title)
        longname = self.args.longname or make_name(author["organization"], library["title"])
        longname = library["longname"] = LibraryLongName.ask(console, default=longname)
        library["url"] = LibraryURL.ask(console, default="")
        library["namespace"] = LibraryNamespace.ask(console, default="")
        mount = None
        appname = None

        do_mount = DoMount.ask(console, default="yes")
        if do_mount:
            mount = Mount.ask(console, default=self.args.mount or "/{}/".format(make_name(library["title"])))
            appname = AppName.ask(console, default=self.args.name or make_name(library["title"]))

        data = dict(author=author,
                    library=library,
                    timezone=self.get_timezone())

        actions = []

        from ...command.sub import library_template
        from fs.memoryfs import MemoryFS
        from fs.opener import fsopendir
        memfs = MemoryFS()
        templatebuilder.compile_fs_template(memfs,
                                            library_template.template,
                                            data=data)
        dest_fs = fsopendir(join(library_path, library["longname"]), create_dir=True, writeable=True)

        continue_overwrite = 'overwrite'
        if not dest_fs.isdirempty('.'):
            if self.args.force:
                continue_overwrite = 'overwrite'
            elif self.args.new:
                continue_overwrite = 'new'
            else:
                continue_overwrite = DirNotEmpty.ask(console, default="cancel")

        if continue_overwrite != 'cancel':
            if continue_overwrite == 'overwrite':
                from fs.utils import copydir
                copydir(memfs, dest_fs)
                actions.append("Written library files to {}".format(dest_fs.getsyspath('.')))
            elif continue_overwrite == 'new':
                files_copied = copy_new(memfs, dest_fs)
                table = [[
                         Cell("{} new file(s) written".format(len(files_copied)), fg="green", bold=True, center=True),
                         ]]
                for path in files_copied:
                    table.append([Cell(dest_fs.desc(path), bold=True, fg="black")])
                console.table(table)
                return 0

            if cfg:
                project_cfg = cfg['project']
                location = project_cfg['location']
                server_name = "main"

                if location:
                    with fsopendir(project_path) as project_fs:
                        with project_fs.opendir(location) as server_fs:
                            from lxml.etree import fromstring, ElementTree, parse
                            from lxml.etree import XML, Comment
                            server_xml_path = server_fs.getsyspath(project_cfg['startup'])
                            root = parse(server_xml_path)
                            import_tag = XML('<import location="./local/{longname}" />\n\n'.format(**library))
                            import_tag.tail = "\n"
                            install_tag = None

                            if mount:
                                tag = '<install name="{appname}" lib="{longname}" mount="{mount}" />'
                            else:
                                tag = '<install name="{appname}" lib="{longname}" />'
                            install_tag = XML(tag.format(appname=appname,
                                                         longname=longname,
                                                         mount=mount))
                            install_tag.tail = "\n\n"

                            def has_child(node, tag, **attribs):
                                for el in node.findall(tag):
                                    #items = dict(el.items())
                                    if all(el.get(k, None) == v for k, v in attribs.items()):
                                        return True
                                return False

                            for server in root.findall("{{http://moyaproject.com}}server[@docname='{}']".format(server_name)):
                                add_import_tag = not has_child(server, "{http://moyaproject.com}import", location="./local/{}".format(longname))
                                add_install_tag = not has_child(server, "{http://moyaproject.com}install", lib=longname) and install_tag is not None

                                if add_import_tag or add_install_tag:
                                    comment = Comment("Added by 'moya start library'")
                                    comment.tail = "\n"
                                    server.append(comment)
                                if add_import_tag:
                                    server.append(import_tag)
                                    actions.append("Added <import> tag")
                                if add_install_tag:
                                    server.append(install_tag)
                                    actions.append("Added <install> tag")
                                    if mount:
                                        actions.append("Mounted application on {}".format(mount))

                            root.write(server_xml_path)

            table = [[Cell("Library files written successfully!", fg="green", bold=True, center=True)]]

            actions_text = "\n".join(" * " + action for action in actions)
            table.append([Cell(actions_text, fg="blue", bold=True)])
            table.append(["""A new library has been added to the project, containing some simple example functionality.\nSee http://moyaproject.com/docs/creatinglibraries/ for more information."""])
            console.table(table)

            return 0

        console.text("No project files written.", fg="red", bold=True).nl()
        return -1