Exemple #1
0
def print_log():
    log = Env.log_file.read_text()
    import ansi2html

    converter = ansi2html.Ansi2HTMLConverter()
    html = converter.convert(log)
    return '<h1>Automate log</h1>' + html
Exemple #2
0
def getDiffHtml(commitHash, paths):
    cmd = ['git', 'show', '--format=', commitHash, '--color-words', '--']
    cmd.extend(paths)
    diff = Utils.call(cmd, cwd=Globals.repositoryDir)
    conv = ansi2html.Ansi2HTMLConverter(font_size="9pt")
    ansi = '\n'.join(diff)
    html = conv.convert(ansi)
    #html = '\n'.join( Utils.call( ['ansi2html.sh', '--bg=dark'], input=ansi ) )
    return html
Exemple #3
0
    def on_message(self, node, message):
        with self.messages_lock:
            if message:
                message = ansi2html.Ansi2HTMLConverter(inline=True).convert(
                    message, full=False)

            self.messages.append([node, message])
            for ev in self.watcher_events:
                ev.set()
Exemple #4
0
    def __generate_command_outputs(self, service):
        """
        Generate HTML code with all command outputs for the specified service.

        :param Service service: Service Model
        """
        req = ResultsRequester(self.sqlsession)
        req.select_mission(self.mission)

        # Filter on service id
        filter_ = Filter(FilterOperator.AND)
        filter_.add_condition(Condition(service.id, FilterData.SERVICE_ID))
        req.add_filter(filter_)
        results = req.get_results()

        html = ''
        i = 0
        for r in results:
            html += """
            <div class="tab-pane{active}" id="{id}">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-lg-12">
                            <h1 class="title-page">{category} > {check}</h1>
            """.format(active=' active' if i == 0 else '',
                       id=r.check,
                       category=r.category,
                       check=r.check)

            for o in r.command_outputs:
                # Convert command output (with ANSI codes) to HTML
                conv = ansi2html.Ansi2HTMLConverter(inline=True,
                                                    scheme='solarized',
                                                    linkify=True)
                output = conv.convert(o.output)
                # Warning: ansi2html generates HTML document with <html>, <style>...
                # tags. We only keep the content inside <pre> ... </pre>
                m = re.search('<pre class="ansi2html-content">(?P<output>.*)' \
                    '</pre>\n</body>', output, re.DOTALL)
                if m:
                    output = m.group('output')

                    html += """
                    <pre class="cmdline">{cmdline}</pre>
                    <pre>{output}</pre>
                    """.format(cmdline=o.cmdline, output=output)

            html += """
                        </div>
                    </div>
                </div>
            </div>
            """
            i += 1

        return html
Exemple #5
0
def getGitLogAll():
    command = [
        "git", "log", "-" + str(nLines), "--graph", "--abbrev-commit",
        "--decorate", "--date=local", "--all",
        "--format=format:%C(bold blue)%h%C(reset) %C(bold green)(%ad)%C(reset) %C(white)%s%C(reset) %C(dim white)- %an%C(reset)%C(bold yellow)%d%C(reset)"
    ]
    gitLogP = subprocess.Popen(command, stdout=subprocess.PIPE)
    (gitLogAnsi, gitLogErr) = gitLogP.communicate()
    converter = ansi2html.Ansi2HTMLConverter()
    gitLogHtml = converter.convert(gitLogAnsi, full=False)
    preamble = "<pre class=\"ansi2html-content\">\n"
    postamble = "</pre>\n"
    return preamble + gitLogHtml + postamble
Exemple #6
0
def terminalize_output(output):
    # Replace "<,&,>" signs
    output = output.replace("&", "&amp;")
    output = output.replace("<", "&lt;")
    output = output.replace(">", "&gt;")
    output = output.replace("\n", "<br/>")
    '''
       Substitute terminal color codes for CSS tags.
       The bold tag can be a modifier on another tag
       and thus sometimes doesn't have its own
       closing tag. Just ignore it in that case.
    '''
    conv = ansi2html.Ansi2HTMLConverter(escaped=False, scheme="xterm")
    return conv.convert(output, full=False)
Exemple #7
0
def main():
	"""CLI."""
	try:
		opts, args = getopt.gnu_getopt(
				sys.argv[1:], '', ['hidecorrectlinks', 'html'])
		opts = dict(opts)
		cmd, goldfile, respfile = args
		if cmd not in ('mentions', 'links'):
			raise ValueError('unknown cmd: %s' % cmd)
	except (ValueError, getopt.GetoptError) as err:
		print(err)
		print(__doc__)
		return
	hidecorrectlinks = '--hidecorrectlinks' in opts
	if '--html' in opts:
		out = io.StringIO()
		compare(cmd, goldfile, respfile,
				hidecorrectlinks=hidecorrectlinks, out=out)
		conv = ansi2html.Ansi2HTMLConverter(scheme='xterm', dark_bg=True)
		print(conv.convert(out.getvalue()))
	else:
		compare(cmd, goldfile, respfile, hidecorrectlinks=hidecorrectlinks)
Exemple #8
0
def get_ansi_to_html_converter():
    return ansi2html.Ansi2HTMLConverter()
def main():
    ansi2html.converter.SCHEME['custom'] = (
        "#000000",
        "#e42e16",
        "#19c518",
        "#e7e71c",
        "#492ee1",
        "#d338d3",
        "#33d6e5",
        "#ffffff",
    )

    backend = sys.argv[1]
    output = sys.stdin.read().rstrip()

    callout_re = re.compile('\x1b\[(\d+)c\n')
    callouts = collections.defaultdict(int)
    for i, line in enumerate(output.splitlines(True)):
        m = callout_re.match(line)
        if m:
            callouts[i + int(m.group(1)) - len(callouts)] += 1

    output = callout_re.sub('', output)

    w = sys.stdout.write

    comment_marker = '###COMMENT###'

    callout_counter = 1
    if backend == 'xhtml11':
        preamble = (
            '</p></div><div class="listingblock"><div class="content"><pre><code>'
        )
        postamble = '</code></pre></div></div><p><div class="paragraph">'
        c = ansi2html.Ansi2HTMLConverter(inline=True, scheme='custom')

        in_code = False
        body = c.convert(output, full=False)
        for i, line in enumerate(body.splitlines()):
            if line.startswith(comment_marker):
                if in_code:
                    w(postamble)
                    in_code = False
                w(line[len(comment_marker):])
            else:
                if not in_code:
                    w(preamble)
                    in_code = True
                ext = ''
                for _ in xrange(callouts[i]):
                    if not ext:
                        ext += '</span>'
                    ext += ' <b>&lt;%d&gt;</b>' % callout_counter
                    callout_counter += 1
                if ext:
                    ext += '<span>'
                w(line + ext + '\n')
        if in_code:
            w(postamble)
    else:
        preamble = '</simpara><literallayout class="monospaced">'
        postamble = '</literallayout><simpara>'

        in_code = False
        body = simpleXML(output)
        for i, line in enumerate(body.splitlines()):
            if line.startswith(comment_marker):
                if in_code:
                    w(postamble)
                    in_code = False
                w(line[len(comment_marker):])
            else:
                if not in_code:
                    w(preamble)
                    in_code = True
                ext = ''
                for _ in xrange(callouts[i]):
                    ext += '  <emphasis role="strong">(%d)</emphasis>' % callout_counter
                    callout_counter += 1
                w(line + ext + '\n')
        if in_code:
            w(postamble)
Exemple #10
0
    def __generate_command_outputs(self, service):
        """
        Generate HTML code with all command outputs for the specified service.

        :param Service service: Service Model
        """
        req = ResultsRequester(self.sqlsession)
        req.select_mission(self.mission)

        # Filter on service id
        filter_ = Filter(FilterOperator.AND)
        filter_.add_condition(Condition(service.id, FilterData.SERVICE_ID))
        req.add_filter(filter_)
        results = req.get_results()

        html = ''
        i = 0
        for r in results:

            # Icon category
            icon = IconsMapping.get_icon_html('category', r.category)

            # Description/Tool of check
            if service.name in self.settings.services:
                check = self.settings.services[
                    service.name]['checks'].get_check(r.check)
                if check is not None:
                    description = check.description
                    tool = check.tool.name
                else:
                    description = tool = ''

            html += """
            <div class="tab-pane{active}" id="{id}">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-lg-12">
                            <h1 class="title-page">{icon}{category} > {check}</h1>
                            <p class="check-description rounded">
                                <span class="mdi mdi-information-outline"></span> 
                                {description} 
                                (using tool: {tool}).
                            </p>
            """.format(active=' active' if i == 0 else '',
                       id=r.check,
                       icon=icon,
                       category=r.category,
                       check=r.check,
                       description=description,
                       tool=tool)

            for o in r.command_outputs:
                # Convert command output (with ANSI codes) to HTML
                conv = ansi2html.Ansi2HTMLConverter(inline=True,
                                                    scheme='solarized',
                                                    linkify=True)
                output = conv.convert(o.output)

                # Warning: ansi2html generates HTML document with <html>, <style>...
                # tags. We only keep the content inside <pre> ... </pre>
                m = re.search('<pre class="ansi2html-content">(?P<output>.*)' \
                    '</pre>\n</body>', output, re.DOTALL)
                if m:
                    output = m.group('output')

                    html += """
                    <pre class="cmdline rounded"># {cmdline}</pre>
                    <pre>{output}</pre>
                    """.format(cmdline=o.cmdline, output=output)

            html += """
                        </div>
                    </div>
                </div>
            </div>
            """
            i += 1

        return html
Exemple #11
0
 def format_ansi(s):
     return ansi2html.Ansi2HTMLConverter(inline=True).convert(s, full=False)
Exemple #12
0
    await asyncio.gather(*[
        run_client(host, exec_cmd, verbose=verbose, name_length=name_length)
        for host in hosts
    ])


###############################################################################
# webserver handlers.
###############################################################################

# monkey-patch ansi2html scheme. TODO: better color codes
import ansi2html
scheme = 'ansi2html'
ansi2html.style.SCHEME[scheme] = list(ansi2html.style.SCHEME[scheme])
#ansi2html.style.SCHEME[scheme][0] = '#555555'
ansi_conv = ansi2html.Ansi2HTMLConverter(dark_bg=False, scheme=scheme)


def render_gpustat_body():
    body = ''
    for host, status in context.host_status.items():
        if not status:
            continue
        body += "<pre class='ansi2html-content body_foreground body_background'>" + ansi_conv.convert(
            status, full=False) + "</pre>"
    return body


async def handler(request):
    '''Renders the html page.'''