Mini Shell

Direktori : /proc/self/root/opt/cloudlinux/venv/lib/python3.11/site-packages/clselect/
Upload File :
Current File : //proc/self/root/opt/cloudlinux/venv/lib/python3.11/site-packages/clselect/clselectprint.py

# -*- coding: utf-8 -*-

# Copyright © Cloud Linux GmbH & Cloud Linux Software, Inc 2010-2019 All Rights Reserved
#
# Licensed under CLOUD LINUX LICENSE AGREEMENT
# http://cloudlinux.com/docs/LICENSE.TXT

from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import csv
import simplejson
import sys
from xml.sax.saxutils import escape as _escape
from past.builtins import basestring  # noqa
from future.utils import iteritems


HTML_ESCAPE_TABLE = {
    '"': """,
    "'": "'"
}


def escape_string(data):
    if isinstance(data, basestring):
        return _escape(data, HTML_ESCAPE_TABLE)
    elif isinstance(data, (tuple, list)):
        new_data = []
        for value in data:
            new_data.append(escape_string(value))
        return new_data
    elif isinstance(data, dict):
        new_dict = {}
        for k, v in iteritems(data):
            new_dict[k] = escape_string(v)
        return new_dict
    return data


def validate_json_message(data):
    # copies message from 'details' to 'message'
    # in case there is no 'message' in json
    if not 'message' in data:
        data['message'] = data['details']


class clprint(object):
    def print_data(cls, fmt, data, escape=None):
        """
        Dispatches data to corresponing routine for printing
        @param fmt: string
        @param data: dict
        """
        dispatcher = {
            'json': cls.print_json,
            'perl': cls.print_perl,
            'csv': cls.print_csv,
            'text': cls.print_text
        }
        try:
            dispatcher[fmt](data, escape=escape)
        except KeyError:
            dispatcher['text'](data)
    print_data = classmethod(print_data)

    def print_diag(cls, fmt, data):
        """
        Dispatches data to corresponing routine for printing
        @param fmt: string
        @param data: dict
        """
        dispatcher = {
            'json': cls.print_diag_json,
            'perl': cls.print_diag_perl,
            'csv': cls.print_diag_csv,
            'text': cls.print_diag_text
        }
        try:
            dispatcher[fmt](data)
        except KeyError:
            dispatcher['text'](data)
    print_diag = classmethod(print_diag)

    def print_csv(data, escape=None):
        """
        Prints data as comma separated values
        @param data: dict
        """
        csv_out = csv.writer(sys.stdout, quoting=csv.QUOTE_ALL)
        for opt in sorted(data.keys()):
            flat_array = [opt]
            for key, value in iteritems(data[opt]):
                if escape:
                    value = escape_string(value)
                flat_array.extend([key, value])
            csv_out.writerow(flat_array)
    print_csv = staticmethod(print_csv)

    def print_diag_csv(data):
        """
        Prints diagnostic messages as comma separated values
        @param data: dict
        """
        validate_json_message(data)
        csv_out = csv.writer(sys.stdout, quoting=csv.QUOTE_ALL)
        csv_out.writerow([data['status'], data['message']])
    print_diag_csv = staticmethod(print_diag_csv)

    def print_json(data, escape=None):
        """
        Prints data as JSON
        @param data: dict
        """
        if data:
            if escape:
                data = escape_string(data)
            print(simplejson.dumps({
                'status': 'OK',
                'data': data}))
        else:
            print(simplejson.dumps({'status': 'OK'}))
    print_json = staticmethod(print_json)

    def print_diag_json(data):
        """
        Prints diagnostic messages as JSON
        @param data: dict
        """
        print(simplejson.dumps(data))
    print_diag_json = staticmethod(print_diag_json)

    def print_text(data, escape=None):
        """
        Prints data as plain text
        @param data: dict
        """
        for opt in sorted(data.keys()):
            print("TITLE:%s" % (opt,))
            for key, v in iteritems(data[opt]):
                if escape:
                    v = escape_string(v)
                print('%s:%s' % (key.upper(), v))
            print('')
    print_text = staticmethod(print_text)

    @staticmethod
    def print_diag_text(data):
        """
        Prints diagnostic messages as plain text
        @param data: dict
        """
        validate_json_message(data)
        print("%s:%s" % (data['status'], data['message']), file=sys.stderr)
        if data.get('details'):
            print("Details:", file=sys.stderr)
            print(data.get('details', '') % data.get('context', {}), file=sys.stderr)

    def print_diag_perl(data):
        """
        Prints diagnostic messages as perl data structure
        @param data: dict
        """
        validate_json_message(data)
        print("{status=>%s,message=>%s}" % (data['status'], data['message']))
    print_diag_perl = staticmethod(print_diag_perl)

    def print_perl(data, escape=None):
        """
        Prints data as perl data structure
        @param data: dict
        """
        out = []
        for opt in sorted(data.keys()):
            structure = []
            structure.append("title=>'%s'" % (opt, ))
            for k, v in iteritems(data[opt]):
                if escape:
                    v = escape_string(v)
                structure.append("%s=>'%s'" % (k, v))
            out.append("{%s}" % (','.join(structure)))
        print('[%s]' % (','.join(out),))
    print_perl = staticmethod(print_perl)

Zerion Mini Shell 1.0