Ejemplo n.º 1
0
def console():
    t = Terminal()

    # clear screen
    print(t.clear, end="")

    # retrieve vended display object
    try:
        calculon.disp = Pyro4.Proxy(ENV.main_dir.uri.content)
    except:
        print(t.bold("Failed to connect to display"))
        calculon.disp = None
    repl.disp = calculon.disp

    # connect to voltron
    try:
        calculon.V = VoltronProxy()
        calculon.V.disp = calculon.disp
        calculon.V.update_disp()
    except NameError:
        pass

    # run repl
    code.InteractiveConsole.runsource = repl.CalculonInterpreter().runsource
    code.interact(local=locals())

    # clean up
    if calculon.V:
        calculon.V._disconnect()
    if calculon.disp:
        calculon.disp._pyroRelease()
Ejemplo n.º 2
0
    def render(self,
               t: blessed.Terminal,
               *,
               width: int = 80,
               border_top: bool = True,
               border_bottom: bool = True,
               border_left: bool = True,
               border_right: bool = True) -> List[str]:
        """Renders the contents of the block to a list of lines."""
        lines: List[str] = []

        rule = width * '.'
        left = ': ' if border_left else ' '
        right = ' :' if border_right else ' '
        iw = width - len(left) - len(right)

        if border_top:
            lines.append(rule)

        if self.title:
            header = t.bold(self.title.ljust(iw))
            header = f"{left}{header}{right}"
            lines.append(header)

        lines += [f'{left}{l: <{iw}}{right}' for l in self.contents]
        if border_bottom:
            lines.append(rule)

        return lines
Ejemplo n.º 3
0
def console():
    t = Terminal()

    # clear screen
    print(t.clear, end="")

    # retrieve vended display object
    try:
        calculon.disp = Pyro4.Proxy(env.main_dir.uri.content)
    except:
        print(t.bold("Failed to connect to display"))
        calculon.disp = None
    repl.disp = calculon.disp

    # connect to voltron
    try:
        calculon.V = VoltronProxy()
        calculon.V.disp = calculon.disp
    except NameError:
        pass

    # run repl
    code.InteractiveConsole.runsource = repl.CalculonInterpreter().runsource
    code.interact(local=locals())

    # clean up
    if calculon.disp:
        calculon.disp._pyroRelease()
    if calculon.V:
        calculon.V.stop_watcher()
Ejemplo n.º 4
0
Archivo: scli.py Proyecto: encima/scli
def speed_read(words, speed):
    term = Terminal()
    call(['clear'])
    with term.fullscreen():
        for w in words:
            printable = w.decode('utf-8')
            print(term.move_y(term.height // 2) + term.center(term.bold(printable)).rstrip())
            time.sleep(speed)
            call(["clear"])
Ejemplo n.º 5
0
def day(args, *extra, **kwargs):
    parser = argparse.ArgumentParser()
    parser.add_argument(
        'username',
        help='The MyFitnessPal username for which to delete a stored password.'
    )
    parser.add_argument(
        'date',
        nargs='?',
        default=datetime.now().strftime('%Y-%m-%d'),
        type=lambda datestr: dateparse(datestr).date(),
        help='The date for which to display information.'
    )
    args = parser.parse_args(extra)

    password = get_password_from_keyring_or_interactive(args.username)
    client = Client(args.username, password)
    day = client.get_date(args.date)

    t = Terminal()

    print(t.blue(args.date.strftime('%Y-%m-%d')))
    for meal in day.meals:
        print(t.bold(meal.name.title()))
        for entry in meal.entries:
            print('* {entry.name}'.format(entry=entry))
            print(
                t.italic_bright_black(
                    '  {entry.nutrition_information}'.format(entry=entry)
                )
            )
        print('')

    print(t.bold("Totals"))
    for key, value in day.totals.items():
        print(
            '{key}: {value}'.format(
                key=key.title(),
                value=value,
            )
        )
    print("Water: {amount}".format(amount=day.water))
    if day.notes:
        print(t.italic(day.notes))
Ejemplo n.º 6
0
def day(args, *extra, **kwargs):
    parser = _default_arg_parser()
    parser.add_argument(
        'date',
        nargs='?',
        default=datetime.now().strftime('%Y-%m-%d'),
        type=lambda datestr: dateparse(datestr).date(),
        help=u'The date for which to display information.'
    )
    args = parser.parse_args(extra)

    password = get_password_from_keyring_or_interactive(args.username)
    client = Client(args.username, password)
    day = client.get_date(args.date)

    t = Terminal()

    print(t.green(args.date.strftime('%Y-%m-%d')))
    for meal in day.meals:
        print(t.bold(meal.name.title()))
        for entry in meal.entries:
            print(u'* {entry.name}'.format(entry=entry))
            print(
                t.italic_bright_black(
                    u'  {entry.nutrition_information}'.format(entry=entry)
                )
            )
        print(u'')

    print(t.bold("Totals"))
    for key, value in day.totals.items():
        print(
            u'{key}: {value}'.format(
                key=key.title(),
                value=value,
            )
        )
    print(u'Water: {amount}'.format(amount=day.water))
    if day.notes:
        print(t.italic(day.notes))
Ejemplo n.º 7
0
		shares_marker = ""

		hashrate_change = ""
		hashrate_diff = ""
		hashrate_marker = ""

		shares_A = D(metrics_A["shares"])
		shares_B = D(metrics_B["shares"])
		
		hashrate_A = D(metrics_A["hashrate"])
		hashrate_B = D(metrics_B["hashrate"])
		
		if(shares_A < shares_B):
			shares_change = "UP"
			shares_diff = shares_B - shares_A
			shares_marker = t.bold(t.green('UP')) 
		
		if(shares_B < shares_A):
			shares_change = "DOWN"
			shares_diff = abs(shares_A - shares_B)
			shares_marker = t.bold(t.red('DOWN'))

		if(hashrate_A < hashrate_B):
			hashrate_change = "UP"
			hashrate_diff = hashrate_B - hashrate_A
			hashrate_marker = t.bold(t.green('UP'))

		if(hashrate_A > hashrate_B):
			hashrate_change = "DOWN"
			hashrate_diff = abs(hashrate_A - hashrate_B)
			hashrate_marker = t.bold(t.red('DOWN'))			
Ejemplo n.º 8
0
from blessed import Terminal

t = Terminal()

print(t.bold('Hi there!'))
print(t.bold_red_on_bright_green('It hurts my eyes!'))

with t.location(0, t.height - 3):
    print(t.center(t.blink('press any key to continue.')))

with t.cbreak():
    inp = t.inkey()
print('You pressed ' + repr(inp))
Ejemplo n.º 9
0
def main(argv=None):
    """ Execute the application CLI.

    Arguments are taken from sys.argv by default.

    """

    args = _cmdline(argv)
    logger.start(args.logging_level)
    logger.debug("starting execution")

    #  get repo and initialize GitHeat instance
    try:
        g = Git(os.getcwd())
    except (InvalidGitRepositoryError, GitCommandError, GitCommandNotFound):
        print("Are you sure you're in an initialized git directory?")
        return 0
    githeat = Githeat(g, **vars(args))
    githeat.parse_commits()
    githeat.init_daily_contribution_map()
    githeat.compute_daily_contribution_map()
    githeat.normalize_daily_contribution_map()
    matrix = githeat.compute_graph_matrix()

    term = Terminal()
    matrix_width = githeat.get_matrix_width(matrix)
    if matrix_width > term.width:
        print(
            "Your terminal width is smaller than the heatmap. Please consider using "
            "the --width {thin, reg, thick} argument, resizing your terminal, or "
            "merging months by including --month-merge.")
        return 0
    new_width = (term.width - matrix_width) // 2
    csr = Cursor(term.height // 2 - 3, new_width, term)

    screen = {}
    screen_dates = {}
    with term.hidden_cursor(), \
         term.raw(), \
         term.location(), \
         term.fullscreen(), \
         term.keypad():

        # Print header
        print_header_left(term, unicode(os.getcwd()), screen)
        text = u'GitHeat {}'.format(__version__)
        print_header_center(term, text, screen)
        text = u'ESC, ^c to exit'
        print_header_right(term, text, screen)

        # Print footer
        text = u'Please move cursor to navigate through map'
        print_footer_left(term, term.bold(text), screen)

        graph_right_most_x = term.width  # initialized at terminal width
        graph_left_most_x = csr.x
        graph_top_most_y = csr.y
        graph_x, graph_y = csr.x, csr.y

        #  get graph boundaries
        for i in range(7):
            #  for the week column in the matrix
            for week in matrix:
                if githeat.month_merge:
                    #  check if value in that week is just empty spaces and not colorize
                    if week.col[i][1] == githeat.width:
                        continue
                graph_x += len(githeat.width)

            graph_right_most_x = graph_x
            graph_x = graph_left_most_x  # reset x
            graph_y += 1
        graph_bottom_most_y = graph_y - 1

        #  print graph
        graph_x, graph_y = csr.x, csr.y
        print_graph(term, screen, screen_dates, graph_x, graph_y,
                    graph_left_most_x, matrix, githeat)

        # print legend
        block_separation_width = 4
        legend_x = (term.width -
                    len(githeat.colors) * block_separation_width) // 2
        legend_y = graph_bottom_most_y + 5
        if not githeat.hide_legend:
            print_graph_legend(legend_x, legend_y, githeat.width,
                               block_separation_width, githeat.colors, screen,
                               term)

        while True:
            cursor_color = colorize(githeat.width, ansi=15, ansi_bg=15)
            echo_yx(csr, cursor_color)
            inp = term.inkey()

            if inp in QUIT_KEYS:
                # Esc or ^c pressed
                break
            elif inp == chr(99):
                # c pressed, thus change color
                githeat.switch_to_next_color()
                #  changing colors requires regenerating matrix,
                #  because values there are colorized strings, harder to change
                matrix = githeat.compute_graph_matrix()
                #  print changed color graph
                print_graph(term, screen, screen_dates, graph_x, graph_y,
                            graph_left_most_x, matrix, githeat)

                #  print changed color legend
                if not githeat.hide_legend:
                    print_graph_legend(legend_x, legend_y, githeat.width,
                                       block_separation_width, githeat.colors,
                                       screen, term)

                #  print changed color footer
                new_cursor_date_value = screen_dates.get((csr.y, csr.x))
                if new_cursor_date_value:  # only if it needs changing
                    location = nav.home(nav.bottom(csr))
                    update_most_committers_footer(location, githeat,
                                                  new_cursor_date_value, term,
                                                  screen)
                continue
            elif inp.lower() in ONE_TO_SEVEN_KEYS or inp in Q_TO_QUOTES_KEYS:
                if inp.lower() in ONE_TO_SEVEN_KEYS:
                    #  key from 1 to 7 pressed.
                    githeat.toggle_day(int(inp) - 1)
                else:
                    # key from q to ' pressed
                    githeat.toggle_month(Q_TO_QUOTES_KEYS.index(inp.lower()))

                # re-computing new daily contributions with the specified days/months
                githeat.recompute_daily_contribution_map()
                matrix = githeat.compute_graph_matrix()
                #  print new filtered graph
                print_graph(term, screen, screen_dates, graph_x, graph_y,
                            graph_left_most_x, matrix, githeat)

                continue

            else:
                n_csr = nav.lookup_move(inp.code, csr, term, githeat)

            # only allow moves within the graph boundaries
            if not is_within_boundary(graph_right_most_x, graph_top_most_y,
                                      graph_left_most_x, graph_bottom_most_y,
                                      n_csr):
                continue

            # get value at new cursor block, if it exists
            new_cursor_date_value = screen_dates.get((n_csr.y, n_csr.x))
            if new_cursor_date_value:  # Cursor is on a date block with commits
                location = nav.home(nav.bottom(csr))
                update_most_committers_footer(location, githeat,
                                              new_cursor_date_value, term,
                                              screen)
            else:

                horizontal_empty = False

                #  jump through empty values
                while not new_cursor_date_value and is_within_boundary(
                        graph_right_most_x - 1, graph_top_most_y,
                        graph_left_most_x + 1, graph_bottom_most_y, n_csr):

                    x = n_csr.x
                    y = n_csr.y
                    if n_csr.x > csr.x:  # right move
                        x += 1
                    elif n_csr.x < csr.x:  # left move
                        x -= 1
                    else:
                        horizontal_empty = True
                        break  # skip jumping on up or down moves

                    n_csr = Cursor(y, x, term)
                    new_cursor_date_value = screen_dates.get(
                        (n_csr.y, n_csr.x))
                    if new_cursor_date_value:
                        location = nav.home(nav.bottom(csr))
                        update_most_committers_footer(location, githeat,
                                                      new_cursor_date_value,
                                                      term, screen)

                if horizontal_empty or not new_cursor_date_value:
                    continue

            if n_csr != csr:
                # erase old cursor,
                prev_value = screen.get((csr.y, csr.x), u'  ')
                echo_yx(csr, prev_value)
                csr = n_csr

            if inp == chr(13):
                # ENTER pressed on date block
                commits_on_date = githeat.commits_db.get(new_cursor_date_value)

                if commits_on_date:  # if block has contributions
                    #  open commits desc terminal
                    open_commits_terminal(new_cursor_date_value,
                                          commits_on_date, githeat)
                    # redraw base terminal after exiting commits desc terminal
                    redraw(term=term, screen=screen)
                else:
                    info = u'Please choose a date with contributions \a'
                    text = unicode(new_cursor_date_value) + ' ' + info
                    print_footer_left(term, text, screen)

    logger.debug("successful completion")
    return 0
Ejemplo n.º 10
0
def open_commits_terminal(new_cursor_date_value, commits_on_date, githeat):
    """
    Creates a new terminal window for showing commits info
    :param new_cursor_date_value:
    :param commits_on_date:
    :param githeat: Githeat instance
    :return:
    """
    screen = {}
    term = Terminal()
    with term.keypad():
        redraw(term=term, screen={})

        # Print header
        print_header_left(term, str(new_cursor_date_value), screen)
        text = u'GitHeat {}'.format(__version__)
        print_header_center(term, text, screen)
        text = u'ESC, to return'
        print_header_right(term, text, screen)
        #  hold the commit info that we will display depending on scrolling window edges
        commit_values_holder = []
        for commit in commits_on_date:
            commit_hash, cdate, spaces, subject, author, email, = resize_until_fit(
                [
                    commit.abbr_commit_hash,
                    str(commit.date.strftime("%H:%M:%S %z")),
                    "  ",
                    commit.subject,
                    commit.author,
                    commit.author_email,
                ],
                term.width - 7  # for spaces and '<', '>' between emails
            )

            value = [
                colorize(commit_hash, ansi=githeat.colors[1]),
                cdate,
                spaces,
                term.bold(subject),
                colorize(author, ansi=githeat.colors[2]),
            ]

            if email:
                value.append(
                    colorize("<{}>".format(email), ansi=githeat.colors[3]))

            value = " ".join(value)
            commit_values_holder.append(value)

        starting_y = 2
        x = 0
        range_from = 0
        range_to = term.height - starting_y
        for value in commit_values_holder[range_from:range_to]:
            location = Cursor(starting_y, x, term)
            echo_yx(location, value)
            starting_y += 1

        while True:
            inp = term.inkey()

            if inp in chr(27):  # ESC to return
                break
            elif inp == chr(3):  # ^c to exit
                sys.exit(0)

            # scrolling window on commits
            starting_y = 2  # to not override header text
            if inp.code == term.KEY_UP:
                if range_from == 0:
                    continue
                range_from -= 1
            elif inp.code == term.KEY_DOWN:
                #  skip scrolling if commits fit terminal height
                if len(commit_values_holder[range_from:]) < term.height:
                    continue
                range_from += 1

            redraw(term=term, screen=screen)
            #  echo the commits based on scrolling window
            for value in commit_values_holder[range_from:]:
                if starting_y > term.height:
                    break
                location = Cursor(starting_y, x, term)
                echo_yx(location, value)
                starting_y += 1
Ejemplo n.º 11
0
def monitor(unit, systempath):
    t = Terminal()
    print(t.enter_fullscreen())

    mapping = [
        "[R] Restart service                                                   ",
        "[S] Stop service                                                      ",
        "[T] Enable on startup           [b] Back                              ",
        "[g] Grep (filter) a pattern      [q] Quit view                        ",
    ]

    OFFSET = 12

    resized = [True]
    signal.signal(signal.SIGWINCH, lambda *args: resized.append(True))

    logo = "[sysdm]"
    # seen = set()

    Y_BANNER_OFFSET = len(mapping) + 1 + 2  # mapping, banner, in between lines

    grep = ""

    x_banner_offset = 0
    left_offset = 0
    log_offset = 0
    timer = None

    with t.hidden_cursor():
        try:
            while True:
                print(t.move(0, 0))
                y, x = t.get_location()
                if resized:
                    print(t.clear())
                    resized = []
                    timed = is_unit_running(unit + ".timer")
                    is_running = is_unit_running(unit) or timed
                    is_enabled = is_unit_enabled(unit)
                    if timed:
                        timer_text = ""
                        while not timer_text:
                            status = systemctl("list-timers " + unit + ".timer")
                            timer_text = status.split("\n")[1][4 : status.index("LEFT") - 2]
                        status = "Next: " + t.green(timer_text)
                        timer = datetime.strptime(timer_text[:19], "%Y-%m-%d %H:%M:%S")
                    else:
                        status = "Active: " + (t.green("✓") if is_running else t.red("✗"))
                    with t.location(OFFSET, 0):
                        enabled = t.green("✓") if is_enabled else t.red("✗")
                        line = "Unit: {} {} On Startup: {}".format(t.bold(unit), status, enabled)
                        x_banner_offset = len(line)
                        print(line)

                    with t.location(t.width - len(logo), 0):
                        print(t.bold(logo))

                    with t.location(0, 1):
                        print(t.center("-" * (t.width - 16)))

                    for num, line in enumerate(mapping):
                        with t.location(0, num + 2):
                            if not is_running:
                                line = line.replace("Stop service ", "Start service")
                            if is_enabled:
                                line = line.replace("Enable on startup", "Disable on startup")
                            line = line.replace("[", "[" + t.green).replace("]", t.normal + "]")
                            print(" " * OFFSET + (line + " " * t.width)[: t.width + 3])

                    with t.location(0, 6):
                        print(t.center("-" * (t.width - 16)))

                # if timer just expired, refresh to get the new date
                if timer is not None and datetime.now() > timer:
                    resized = [True]
                if t.width - x_banner_offset > 50:
                    res = "| {} |".format(time.asctime())
                    if is_running:
                        ps_aux = get_output("ps ax -o pid,%cpu,%mem,ppid,args -ww")
                        ps_info = read_ps_aux_by_unit(systempath, unit, ps_aux)
                        if ps_info is not None:
                            res = "| {} | PID={} | CPU {:>4}% | MEM {:>4}%".format(
                                time.asctime(), *ps_info
                            )
                    with t.location(x_banner_offset, 0):
                        print(res)

                with t.location(0, Y_BANNER_OFFSET):
                    n = t.height - Y_BANNER_OFFSET - 1
                    w = t.width
                    g = "--grep " + grep if grep else ""
                    u_sep = "-u" if IS_SUDO else "--user-unit"
                    output = journalctl(
                        "journalctl {u_sep} {u} {u_sep} {u}_monitor {u_sep} {u}.timer -n {n} --no-pager {g}".format(
                            u=unit, n=n + log_offset + 100, g=g, u_sep=u_sep
                        )
                    )
                    outp = []
                    for line in output.split("\n"):
                        # replace e.g. python[pidnum123]: real output
                        line = re.sub("(?<=:\d\d ).+?\[\d+\]: ", "| ", line)
                        if grep:
                            rmatch = re.search(grep, line)
                            if rmatch is not None:
                                s = rmatch.start()
                                e = rmatch.end()
                                line = line[:s] + t.red(line[s:e]) + line[e:]
                        l = (line + " " * 200)[left_offset : w + left_offset - 5]
                        if "Stopped" in l:
                            l = t.bold(l)
                        if "Started" in l:
                            if timed:
                                ln = len(l)
                                white = " " * 200
                                l = (l.split("|")[0] + "| Succesfully ran on timer" + white)[:ln]
                            l = t.green(l)
                        if "WARNING: " in l:
                            l = t.yellow(l)
                        if "ERROR: " in l:
                            l = t.red(l)
                        if "Failed to start " in l:
                            l = t.red(l)
                        if "Triggering OnFailure= " in l:
                            l = t.yellow(l)
                        outp.append(l)
                    if log_offset:
                        print("\n".join(outp[-n - log_offset + 1 : -log_offset]))
                    else:
                        print("\n".join(outp[-n - log_offset + 1 :]))

                with t.cbreak():
                    inp = t.inkey(0.3)

                if inp == "q":
                    if grep:
                        grep = ""
                    else:
                        print(t.clear())
                        sys.exit(0)
                elif inp == "S":
                    print(t.clear())
                    if is_running:
                        print("Stopping unit {unit}".format(unit=unit))
                        systemctl("stop {unit}".format(unit=unit))
                        systemctl("stop {unit}.timer".format(unit=unit))
                    else:
                        print("Starting unit {unit}".format(unit=unit))
                        systemctl("start --no-block {unit}".format(unit=unit))
                        systemctl("start {unit}.timer".format(unit=unit))
                    resized = [True]
                elif inp == "R":
                    print(t.clear())
                    print("Restarting unit {unit}".format(unit=unit))
                    systemctl("restart {unit}".format(unit=unit))
                    resized = [True]
                elif inp == "b" or inp.name == "KEY_DELETE":
                    return
                elif inp == "T":
                    print(t.clear())
                    if is_enabled:
                        print("Disabling unit {unit} on startup".format(unit=unit))
                        systemctl("disable {unit}".format(unit=unit))
                        systemctl("disable {unit}.timer".format(unit=unit))
                    else:
                        print("Enabling unit {unit} on startup".format(unit=unit))
                        systemctl("enable {unit}".format(unit=unit))
                        systemctl("enable {unit}.timer".format(unit=unit))
                    resized = [True]
                elif inp == " ":
                    print(t.clear())
                    resized = [True]
                elif inp == "g":
                    print(t.clear())
                    if grep:
                        grep = ""
                    else:
                        grep = input(
                            "Grep pattern to search for (leave blank for cancel): "
                        ).strip()
                    resized = [True]
                elif inp.name == "KEY_RIGHT":
                    print(t.erase())
                    left_offset = min(left_offset + 5, t.width)
                elif inp.name == "KEY_LEFT":
                    print(t.erase())
                    left_offset = max(0, left_offset - 5)
                elif inp.name == "KEY_UP":
                    print(t.erase())
                    log_offset = min(log_offset + 5, t.height)
                elif inp.name == "KEY_DOWN":
                    print(t.erase())
                    log_offset = max(0, log_offset - 5)
                else:
                    print(t.erase())
        except KeyboardInterrupt:
            pass
        print(t.clear())
Ejemplo n.º 12
0
        msg_queue.pop()

    print(term.bold('Alerts history:'))
    if msg_queue and msg_queue[0].startswith('alert'):
        print(term.red('Warning! Alert not recovered'))

    for msg in msg_queue:
        if msg.startswith('alert'):
            print(term.red_reverse(msg))
        else:
            print(term.green_reverse(msg))


if __name__ == '__main__':
    term = Terminal()
    print(term.bold(f'HTTP log monitoring for {LOG_FILE_PATH}'))
    display_stats(stats, msg_queue, term)

    event_handler = LogFileProcessor(LOG_FILE_PATH,
                                     OFFSET_FILE,
                                     PARANOID,
                                     HIGH_TRAFFIC_LIMIT,
                                     stats,
                                     msg_queue,
                                     patterns=[LOG_FILE_PATH])
    observer = Observer()
    observer.schedule(event_handler, path=LOG_FILE_DIR, recursive=False)
    observer.start()
    try:
        while True:
            time.sleep(1)  # for easy development
Ejemplo n.º 13
0
def main(argv=None):
    """ Execute the application CLI.

    Arguments are taken from sys.argv by default.

    """

    args = _cmdline(argv)
    logger.start(args.logging_level)
    logger.debug("starting execution")

    #  get repo and initialize GitHeat instance
    try:
        g = Git(os.getcwd())
    except (InvalidGitRepositoryError, GitCommandError, GitCommandNotFound):
        print("Are you sure you're in an initialized git directory?")
        return 0
    githeat = Githeat(g, **vars(args))
    githeat.parse_commits()
    githeat.init_daily_contribution_map()
    githeat.compute_daily_contribution_map()
    githeat.normalize_daily_contribution_map()
    matrix = githeat.compute_graph_matrix()

    term = Terminal()
    matrix_width = githeat.get_matrix_width(matrix)
    if matrix_width > term.width:
        print("Your terminal width is smaller than the heatmap. Please consider using "
              "the --width {thin, reg, thick} argument, resizing your terminal, or "
              "merging months by including --month-merge.")
        return 0
    new_width = (term.width - matrix_width) // 2
    csr = Cursor(term.height // 2 - 3, new_width, term)

    screen = {}
    screen_dates = {}
    with term.hidden_cursor(), \
         term.raw(), \
         term.location(), \
         term.fullscreen(), \
         term.keypad():

        # Print header
        print_header_left(term, unicode(os.getcwd()), screen)
        text = u'GitHeat {}'.format(__version__)
        print_header_center(term, text, screen)
        text = u'ESC, ^c to exit'
        print_header_right(term, text, screen)

        # Print footer
        text = u'Please move cursor to navigate through map'
        print_footer_left(term, term.bold(text), screen)

        graph_right_most_x = term.width  # initialized at terminal width
        graph_left_most_x = csr.x
        graph_top_most_y = csr.y
        graph_x, graph_y = csr.x, csr.y

        #  get graph boundaries
        for i in range(7):
            #  for the week column in the matrix
            for week in matrix:
                if githeat.month_merge:
                    #  check if value in that week is just empty spaces and not colorize
                    if week.col[i][1] == githeat.width:
                        continue
                graph_x += len(githeat.width)

            graph_right_most_x = graph_x
            graph_x = graph_left_most_x  # reset x
            graph_y += 1
        graph_bottom_most_y = graph_y - 1

        #  print graph
        graph_x, graph_y = csr.x, csr.y
        print_graph(term, screen, screen_dates, graph_x, graph_y,
                    graph_left_most_x, matrix, githeat)

        # print legend
        block_separation_width = 4
        legend_x = (term.width - len(githeat.colors) * block_separation_width) // 2
        legend_y = graph_bottom_most_y + 5
        if not githeat.hide_legend:
            print_graph_legend(legend_x, legend_y,
                               githeat.width,
                               block_separation_width,
                               githeat.colors,
                               screen,
                               term)

        while True:
            cursor_color = colorize(githeat.width, ansi=15, ansi_bg=15)
            echo_yx(csr, cursor_color)
            inp = term.inkey()

            if inp in QUIT_KEYS:
                # Esc or ^c pressed
                break
            elif inp == chr(99):
                # c pressed, thus change color
                githeat.switch_to_next_color()
                #  changing colors requires regenerating matrix,
                #  because values there are colorized strings, harder to change
                matrix = githeat.compute_graph_matrix()
                #  print changed color graph
                print_graph(term, screen, screen_dates, graph_x, graph_y,
                            graph_left_most_x, matrix, githeat)

                #  print changed color legend
                if not githeat.hide_legend:
                    print_graph_legend(legend_x, legend_y,
                                       githeat.width,
                                       block_separation_width,
                                       githeat.colors,
                                       screen,
                                       term)

                #  print changed color footer
                new_cursor_date_value = screen_dates.get((csr.y, csr.x))
                if new_cursor_date_value:  # only if it needs changing
                    location = nav.home(nav.bottom(csr))
                    update_most_committers_footer(location, githeat,
                                                  new_cursor_date_value, term, screen)
                continue
            elif inp.lower() in ONE_TO_SEVEN_KEYS or inp in Q_TO_QUOTES_KEYS:
                if inp.lower() in ONE_TO_SEVEN_KEYS:
                    #  key from 1 to 7 pressed.
                    githeat.toggle_day(int(inp) - 1)
                else:
                    # key from q to ' pressed
                    githeat.toggle_month(Q_TO_QUOTES_KEYS.index(inp.lower()))

                # re-computing new daily contributions with the specified days/months
                githeat.recompute_daily_contribution_map()
                matrix = githeat.compute_graph_matrix()
                #  print new filtered graph
                print_graph(term, screen, screen_dates, graph_x, graph_y,
                            graph_left_most_x, matrix, githeat)

                continue

            else:
                n_csr = nav.lookup_move(inp.code, csr, term, githeat)

            # only allow moves within the graph boundaries
            if not is_within_boundary(graph_right_most_x, graph_top_most_y,
                                  graph_left_most_x, graph_bottom_most_y,
                                  n_csr):
                continue

            # get value at new cursor block, if it exists
            new_cursor_date_value = screen_dates.get((n_csr.y, n_csr.x))
            if new_cursor_date_value:  # Cursor is on a date block with commits
                location = nav.home(nav.bottom(csr))
                update_most_committers_footer(location, githeat,
                                              new_cursor_date_value, term, screen)
            else:

                horizontal_empty = False

                #  jump through empty values
                while not new_cursor_date_value and is_within_boundary(
                                graph_right_most_x - 1,
                        graph_top_most_y,
                                graph_left_most_x + 1,
                        graph_bottom_most_y,
                        n_csr):

                    x = n_csr.x
                    y = n_csr.y
                    if n_csr.x > csr.x:  # right move
                        x += 1
                    elif n_csr.x < csr.x:  # left move
                        x -= 1
                    else:
                        horizontal_empty = True
                        break  # skip jumping on up or down moves

                    n_csr = Cursor(y, x, term)
                    new_cursor_date_value = screen_dates.get((n_csr.y, n_csr.x))
                    if new_cursor_date_value:
                        location = nav.home(nav.bottom(csr))
                        update_most_committers_footer(location, githeat,
                                                      new_cursor_date_value, term, screen)

                if horizontal_empty or not new_cursor_date_value:
                    continue

            if n_csr != csr:
                # erase old cursor,
                prev_value = screen.get((csr.y, csr.x), u'  ')
                echo_yx(csr, prev_value)
                csr = n_csr

            if inp == chr(13):
                # ENTER pressed on date block
                commits_on_date = githeat.commits_db.get(new_cursor_date_value)

                if commits_on_date:  # if block has contributions
                    #  open commits desc terminal
                    open_commits_terminal(new_cursor_date_value,
                                          commits_on_date,
                                          githeat)
                    # redraw base terminal after exiting commits desc terminal
                    redraw(term=term, screen=screen)
                else:
                    info = u'Please choose a date with contributions \a'
                    text = unicode(new_cursor_date_value) + ' ' + info
                    print_footer_left(term, text, screen)

    logger.debug("successful completion")
    return 0
Ejemplo n.º 14
0
def open_commits_terminal(new_cursor_date_value, commits_on_date, githeat):
    """
    Creates a new terminal window for showing commits info
    :param new_cursor_date_value:
    :param commits_on_date:
    :param githeat: Githeat instance
    :return:
    """
    screen = {}
    term = Terminal()
    with term.keypad():
        redraw(term=term, screen={})

        # Print header
        print_header_left(term, str(new_cursor_date_value), screen)
        text = u'GitHeat {}'.format(__version__)
        print_header_center(term, text, screen)
        text = u'ESC, to return'
        print_header_right(term, text, screen)
        #  hold the commit info that we will display depending on scrolling window edges
        commit_values_holder = []
        for commit in commits_on_date:
            commit_hash, cdate, spaces, subject, author, email, = resize_until_fit(
                    [
                        commit.abbr_commit_hash,
                        str(commit.date.strftime("%H:%M:%S %z")),
                        "  ",
                        commit.subject,
                        commit.author,
                        commit.author_email,
                    ],
                    term.width - 7  # for spaces and '<', '>' between emails
            )

            value = [
                colorize(commit_hash, ansi=githeat.colors[1]),
                cdate,
                spaces,
                term.bold(subject),
                colorize(author, ansi=githeat.colors[2]),
            ]

            if email:
                value.append(colorize("<{}>".format(email), ansi=githeat.colors[3]))

            value = " ".join(value)
            commit_values_holder.append(value)

        starting_y = 2
        x = 0
        range_from = 0
        range_to = term.height - starting_y
        for value in commit_values_holder[range_from:range_to]:
            location = Cursor(starting_y, x, term)
            echo_yx(location, value)
            starting_y += 1

        while True:
            inp = term.inkey()

            if inp in chr(27):  # ESC to return
                break
            elif inp == chr(3):  # ^c to exit
                sys.exit(0)

            # scrolling window on commits
            starting_y = 2  # to not override header text
            if inp.code == term.KEY_UP:
                if range_from == 0:
                    continue
                range_from -= 1
            elif inp.code == term.KEY_DOWN:
                #  skip scrolling if commits fit terminal height
                if len(commit_values_holder[range_from:]) < term.height:
                    continue
                range_from += 1

            redraw(term=term, screen=screen)
            #  echo the commits based on scrolling window
            for value in commit_values_holder[range_from:]:
                if starting_y > term.height:
                    break
                location = Cursor(starting_y, x, term)
                echo_yx(location, value)
                starting_y += 1
Ejemplo n.º 15
0
class Baker(Workstream):
    def __init__(self):
        Workstream.__init__(self)
        self.terminal = Terminal()
        self.moved = 0
        self.spincount = 0

    def clear(self):
        del self.items[:]
        self.moved = 0

    def prompt(self, msg, default=None, loader=None, echo=True):
        prompt = "%s: " % msg if default is None else "%s[%s]: " % (msg,
                                                                    default)
        prompter = raw_input if echo else getpass.getpass

        while True:
            self.clear()
            value = prompter(prompt) or default
            if value is None: continue
            if loader is not None:
                loaded = loader(value)
                if loaded is None:
                    continue
            if loader:
                return value, loaded
            else:
                return value

    def setup(self):
        print self.terminal.bold("== Checking Kubernetes Setup ==")
        print

        try:
            self.call("kubectl", "version", "--short", verbose=True)
            self.call("kubectl",
                      "get",
                      "service",
                      "kubernetes",
                      "--namespace",
                      "default",
                      verbose=True)
        except WorkError, e:
            print
            raise CLIError(
                self.terminal.red("== Kubernetes Check Failed ==") +
                "\n\nPlease make sure kubectl is installed/configured correctly."
            )

        registry = "registry.hub.docker.com"
        repo = None
        user = os.environ["USER"]
        password = None
        json_key = None

        test_image = "registry.hub.docker.com/library/alpine:latest"

        def validate():
            self.call("docker", "login", "-u", user, "-p", Secret(password),
                      registry)
            self.call("docker", "pull", test_image)
            img = image(registry, repo, "forge_test", "dummy")
            self.call("docker", "tag", test_image, img)
            self.call("docker", "push", img)
            assert self.pushed("forge_test",
                               "dummy",
                               registry=registry,
                               repo=repo,
                               user=user,
                               password=password)

        print
        print self.terminal.bold("== Setting up Docker ==")

        while True:
            print
            registry = self.prompt("Docker registry", registry)
            repo = self.prompt("Docker repo", repo)
            user = self.prompt("Docker user", user)
            if user == "_json_key":
                json_key, password = self.prompt("Path to json key",
                                                 json_key,
                                                 loader=file_contents)
            else:
                password = self.prompt("Docker password", echo=False)

            try:
                print
                validate()
                break
            except WorkError, e:
                print
                print self.terminal.red("-- please try again --")
                continue
            finally:
        match = re.search(WarningLine.regex, line)
        # print len(match.groups())
        if match and len(match.groups()) == 4:
            output_lines.append({
                'log_level': t.yellow('WARN'),
                'file': match.group(WarningLine.filename),
                'line': int(match.group(WarningLine.line)),
                'text': match.group(WarningLine.text),
                'rule': match.group(WarningLine.rule),
            })

# print len(output_lines)

# The output from ansible-review is sorted by filename, but it's nicer
# if we sort it by filename & line_no
sorted_output = sorted(output_lines, key=itemgetter('file', 'line'))

#
# Print the output_lines list, to the console, in markdown format
#
print(t.dim('# ') + t.bold('Ansible Review Checklist'))

curr_file = ''

for line in sorted_output:
    if line['file'] != curr_file:
        curr_file = line['file']
        print(t.dim('\n## ') + t.bold(curr_file))

    print t.dim('- []') + ' {l[log_level]}: Line: {l[line]:>3}: {l[text]}, rule: {l[rule]}'.format(l=line)
Ejemplo n.º 17
0
)
print(
    "dP\"  ,8P      Y8     88      `8i       88      ,8P  88   I8P    8I  I8P     88   i8'    ,8I ,I8,  I8P    I8  I8, ,8I  I8P' \"Yb,"
)
print(
    "Yb,_,dP       `8b,   88       Yb,      88_____,d8'_,88,_,d8b,  ,8I ,d8b,_ _,88,_,d8,   ,d8',d88b,,d8     I8, `YbadP' ,d8    `Yb,"
)
print(
    " \"Y8P\"         `Y8   88        Y8     88888888P\"  8P\"\"Y88P'\"Y88P\"' 8P'\"Y888P\"\"Y8P\"Y8888P\"  8P\"\"Y888P     `Y8888P\"Y88888P      Y8"
)

print("Drücke CTRL + D um zu beenden...")

while True:
    try:
        barcode = input(term.bold("Bitte gib einen Barcode ein: "))
        barcode = term.strip(barcode)
        print(term.clear())
    except (EOFError, KeyboardInterrupt):
        log.info("Program end.")
        sys.exit(0)

    if checkBarcode(barcode):
        log.debug("User input {0} was valid!".format(barcode))
        try:
            mediumDataFromApi = makeRequest(
                barcode)  # Make the request to the API
        except RuntimeWarning:
            continue

        medium = mediumData(mediumDataFromApi, term)
Ejemplo n.º 18
0
client = soundcloud.Client(client_id=client_id)
user = client.get('/resolve', url=base_url)

sc_user = user.username
sc_user_id = user.id
sc_playlist_ct = user.playlist_count
sc_likes = user.public_favorites_count
dl_path = os.path.dirname(os.path.realpath(__file__))

print("press 'q' to quit.")
with t.cbreak():
    val = None
    while val not in (u'q', u'Q', u'\x1b[3~'):  #exit if KEY_DELETE is pressed
        with t.fullscreen():
            print(
                t.bold(t.standout(' Soundcloud Archive Tool 0.01 ')) +
                '  ~  %s  ~  ' % time)  #title bar
            #top information section
            print(t.bold(' User ----------> ') + ' %s' % sc_user
                  )  #soundcloud user
            print(t.bold(' User ID -------> ') + ' %s' % sc_user_id)  #user ID
            print(t.bold(' Playlists ct.--> ') + ' %s' % sc_playlist_ct
                  )  #user playlist count
            print(t.bold(' Likes ct. -----> ') + ' %s' % sc_likes
                  )  #user likes count
            print(t.bold(' Download Path -> ') + ' %s' % dl_path
                  )  #path to download files to
            print(' API id: %s' % client_id)

            print(
                t.move_y(t.height / 4) + t.bold(t.standout(' Current Sets ')))