Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
Size: Mime:
import os
import six
import sys
import curses
import logging
import textwrap
from cliff import show

from workloadmgrclient import utils
from workloadmgrclient.v1 import WorkloadmgrCommand

EULA_AGREEMENT_FILE_NAME = 'EULA.txt'

class LicenseCommand(WorkloadmgrCommand):
    resource = "workloads"


class ListLicense(LicenseCommand, show.ShowOne):
    """List the license. (Admin only)"""

    def take_action(self, parsed_args):
        client = self.get_client()
        license_data = client.license_list() or {}
        metadata = {}
        for meta in license_data.get("metadata", []):
            if meta["key"] == "filename":
                metadata["filename"] = meta["value"]
        license_data["metadata"] = metadata
        # Removing "Licensed For" from the license data as per JIRA-5602
        license_data.pop("Licensed For", None)
        return zip(*sorted(six.iteritems(license_data)))


class CheckLicense(LicenseCommand):
    """Check the license. (Admin only)"""

    def take_action(self, parsed_args):
        client = self.get_client()
        message = client.license_check()
        print(message)


class CreateLicense(LicenseCommand, show.ShowOne):
    """Creates a license. (Admin only)"""

    @staticmethod
    def _add_arguments(parser):
        parser.add_argument(
            "license_file",
            metavar="<license_file>",
            type=open,
            help="Provide file path(relative or absolute) including file name of license file.",
        )

    def display(self, filename):
        # Initialize the curses library and get the size of the terminal window
        screen = curses.initscr()
        rows, cols = screen.getmaxyx()

        max_len = cols * 3 // 4
        with open(filename, 'r') as f:
            file_content = ""
            for line in f:
                # Remove newlines and carriage returns from the line
                line = line.replace("\n", "").replace("\r", "")
                # Split the line into chunks of 3/4th of the screen length or less
                chunks = [line[i:i+max_len] for i in range(0, len(line), max_len)]
                # Join the chunks back into a single line with newlines
                file_content += "\n".join(chunks) + "\n"

        # Define the help text that will be displayed at the bottom of the screen
        help_text = "Press 'q' to quit, 'y' to respond 'Yes', 'n' to repond 'No', Up/Down arrow keys to scroll"
        wrapped_text = textwrap.wrap(help_text, max_len - 2)

        # Calculate the maximum number of rows that can be displayed
        max_rows = rows - len(wrapped_text)  # Subtract 2 for the command prompt line and help text line

        # Set the initial start and end positions of the page
        step_pos = 10  # The stepping value of the scroll
        start_pos = 0
        end_pos = min(max_rows, file_content.count("\n"))

        # Define the color pair for highlighting the help text
        curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE)

        # Loop until the user quits or presses 'y' or 'n'
        while True:
            # Clear the screen and print the current page to the terminal
            screen.clear()
            lines = file_content.split("\n")[start_pos:end_pos]
            for line_num, line in enumerate(lines):
                try:
                    # Truncate long lines to 3/4th of the screen width
                    if len(line) > max_len:
                        line = line[:max_len - 1] + "..."
                    screen.addstr(line_num, 0, line)
                except curses.error:
                    pass
            try:
                for i, line in enumerate(wrapped_text):
                    screen.addstr(rows - len(wrapped_text) +i, 1, line, curses.color_pair(1))
            except Exception as ex:
                logging.exception("An error occurred: %s",str(ex))
            screen.refresh()

            # Capture a single character of input from the user
            input_char = screen.getch()

            # If the user pressed the up arrow key, move the current page up by one line
            if input_char == curses.KEY_UP:
                start_pos = max(0, start_pos - step_pos)
                end_pos = min(file_content.count("\n"), max(end_pos - step_pos, max_rows))

            # If the user pressed the down arrow key, move the current page down by one line
            elif input_char == curses.KEY_DOWN:
                start_pos = min(start_pos + step_pos, file_content.count("\n") - max_rows)
                end_pos = min(end_pos + step_pos, file_content.count("\n"))

            # If the user pressed the y key, exit with return value 1
            elif input_char == ord('y'):
                curses.endwin()
                return True

            # If the user pressed the n key, exit with return value 0
            elif input_char == ord('n'):
                curses.endwin()
                return False

            # If the user pressed the q key, exit the program
            elif input_char == ord('q'):
                curses.endwin()
                break

        # Clear the screen before exiting
        screen.clear()
        curses.endwin()

    def take_action(self, parsed_args):
        client = self.get_client()
        # initialize curses
        eula_file_path = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), EULA_AGREEMENT_FILE_NAME)
        stdscr = curses.initscr()
        curses.noecho()
        curses.cbreak()
        stdscr.keypad(True)
        curses.start_color()
        curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK)
        result = None
        # Call the function to display the file
        try:
            result = self.display(eula_file_path)
        except Exception as ex:
            logging.exception("An error occurred: %s",str(ex))
        finally:
            # clean up curses
            curses.nocbreak()
            stdscr.keypad(False)
            curses.echo()
            curses.endwin()

        if result:
            lic_text = utils.read_file(parsed_args.license_file)
            file_name = os.path.split(parsed_args.license_file.name)[1]
            license_data = {"lic_txt": lic_text, "file_name": file_name}
            license = client.license_create(license_data)
            return zip(*sorted(six.iteritems(license)))

        else:
            print("Skipping license application as product's EULA is not agreed upon.")
            sys.exit(1)