Example #1
0
def read(category=None):
    config = _read_config()

    params = dict(nickname=config['nickname'])
    resp = requests.get(config['url'], params=params, timeout=15)
    if not resp.ok:
        with colorama_text():
            print("%serror:%s %d, %s" %
                  (Fore.RED, Fore.RESET, resp.status_code, resp.reason))
        return

    data = resp.json()
    if not data.get('success'):
        with colorama_text():
            print("%serror:%s %s" % (Fore.RED, Fore.RESET, data.get('msg')))
        return

    with colorama_text():
        post = data['data']
        if not post:
            print("""
No data. How about to write your first post?
Use:
    %sswrite "your text"%s
""" % (Fore.GREEN, Fore.RESET))
        else:
            print("""%snickname:%s %s,
%sdate:%s %s,
%scontent:%s %s
""".strip() % (COLUMN_STYLE, RESET_COLUMN_STYLE, post['nickname'],
               COLUMN_STYLE, RESET_COLUMN_STYLE, post['created_at'],
               COLUMN_STYLE, RESET_COLUMN_STYLE, post['content']))
Example #2
0
def main():
    """automatically reset stdout"""
    with colorama_text():
        print(Fore.GREEN + 'text is green')
        print(Fore.RESET + 'text is back to normal')

    print('text is back to stdout')
Example #3
0
def main():
    """automatically reset stdout"""
    with colorama_text():
        print(Fore.GREEN + 'text is green')
        print(Fore.RESET + 'text is back to normal')

    print('text is back to stdout')
Example #4
0
def main(args=sys.argv[1:]):
    # show deprecation warnings in order to be prepared for backward
    # incompatible changes
    warnings.filterwarnings("always", category=DeprecationWarning)
    arguments = parse_command_line(args)

    # colorama.init() does two great things Holocron depends on. First, it
    # converts ANSI escape sequences printed to standard streams into proper
    # Windows API calls. Second, it strips ANSI colors away from a stream if
    # it's not connected to a tty (e.g. holocron is called from pipe).
    with colorama.colorama_text():
        # initial logger configuration - use custom format for records
        # and print records with WARNING level and higher.
        with configure_logger(arguments.verbosity or logging.WARNING):
            try:
                holocron = create_app_from_yml(arguments.conf)

                for item in holocron.invoke(arguments.pipe):
                    print(
                        termcolor.colored("==>", "green", attrs=["bold"]),
                        termcolor.colored(item["destination"], attrs=["bold"]),
                    )
            except (RuntimeError, IsADirectoryError) as exc:
                print(str(exc), file=sys.stderr)
                sys.exit(1)
            except Exception:
                logging.getLogger().exception("Oops.. something went wrong.")
                sys.exit(1)
Example #5
0
def usage():
    if has_colorama:
        with colorama_text():
            print(Style.BRIGHT + SBD_BANNER + Style.RESET_ALL)
    else:
        print(SBD_BANNER)

    print()
    print("Usage:", sys.argv[0], "<options>")
    print()
    print("Options:")
    print()
    print(
        "-create            Create a project in the current directory and discover source files."
    )
    print(
        "-export            Export the current project to one SQLite database."
    )
    print("-project <file>    Use <file> as the project filename.")
    print(
        "-clang             Use the 'Clang Python bindings' to parse the source files (default)."
    )
    print(
        "--no-parallel      Do not parallelize the compilation process (faster for small code bases)."
    )
    print("--profile-export   Execute the command and show profiling data.")
    print("-test              Test for the availability of exporters")
    print("-help              Show this help.")
    print()
Example #6
0
def run(runner: RefexRunner,
        files: Iterable[Union[str, Tuple[str, str]]],
        bug_report_url: Text,
        version: Text = '<unspecified>'):
    """Performs console setup, and runs.

  Args:
    runner: a :class:`RefexRunner`.
    files: the list of files to rewrite using `runner`. If the output file is
      different from the input file, a pair ``(input, output)`` may be passed
      instead of just ``inout``.
    bug_report_url: if a failure occurs, the URL to report bugs to.
    version: The version to write to debug logs.
  """
    files = ((fname, fname) if isinstance(fname, str) else fname
             for fname in files)
    try:
        with _report_bug_excepthook(bug_report_url):
            with colorama.colorama_text(strip=not runner.renderer.color):
                report_failures(
                    runner.rewrite_files(files),
                    bug_report_url,
                    version,
                    runner.verbose,
                )
    except KeyboardInterrupt:
        pass
Example #7
0
def main():
    """automatically reset stdout"""
    with colorama_text():
        print Fore.GREEN, 'text is green'
        print Fore.RESET, 'text is back to normal'

    print 'text is back to stdout'
Example #8
0
    def print_messages(self, level: str = "all") -> None:
        """Print messages for the current file.

        If level == 'all', both errors and style errors are displayed. Otherwise,
        only errors are displayed.
        """
        # Check if the OS currently running is Windows
        with colorama_text(wrap=(sys.platform == "win32"), strip=False):
            super().print_messages(level)
Example #9
0
def prompt(text):
    prefix = colorama.Fore.CYAN + text + colorama.Fore.RESET

    with colorama.colorama_text():
        try:
            import readline
            return input(prefix)
        except ImportError:
            print(prefix, end="")
            return input()
Example #10
0
def write():
    config = _read_config()

    parser = ArgumentParser()
    parser.add_argument(dest='text', nargs=1, help="what do you want to say?")
    args = parser.parse_args()
    text = args.text[0].decode('utf-8').strip()

    post_data = dict(nickname=config['nickname'], content=text)
    resp = requests.post(config['url'], data=post_data, timeout=15)
    if not resp.ok:
        with colorama_text():
            print("%serror:%s %d, %s" %
                  (Fore.RED, Fore.RESET, resp.status_code, resp.reason))
        return

    data = resp.json()
    with colorama_text():
        if not data.get('success'):
            print("%serror:%s %s" % (Fore.RED, Fore.RESET, data.get('msg')))
        else:
            print("%ssuccess%s" % (Fore.GREEN, Fore.RESET))
def wrong_combo():
    os.system("clear")
    with colorama_text():
        print(Fore.LIGHTRED_EX)
        os.system("cowsay you have...")
        os.system("figlet FAILED!")
        sleep(0.5)
        os.system("clear")
        sleep(0.5)
        os.system("cowsay you have...")
        os.system("figlet FAILED!")
        sleep(0.5)
        os.system("clear")
        sleep(0.5)
        os.system("cowsay you have...")
        os.system("figlet FAILED!")
        sleep(1)
        os.system("clear")
        print(Fore.LIGHTMAGENTA_EX)
        os.system("figlet TRY AGAIN?")
        print(Fore.RESET)
Example #12
0
def export_log(msg):
  tmp = truncate_str(msg)
  print_str = tmp
  if has_colorama:
    apply_colours = False
    substr = None
    for sub in COLOR_SUBSTRS:
      if tmp.find(sub) > -1:
        substr = sub
        apply_colours = True
        break

    if apply_colours:
      with colorama_text():
        pos1 = tmp.find(substr)
        pos2 = pos1 + len(substr)
        print_str = Fore.RESET + tmp[:pos1] + COLOR_SUBSTRS[substr] + tmp[pos1:pos2] + Fore.RESET + tmp[pos2:]

  global print_lock
  print_lock.acquire()
  print(print_str)
  print_lock.release()
Example #13
0
def print_banner():
    from colorama import colorama_text, Fore, Back, Style
    with colorama_text():
        print(Back.WHITE + Fore.BLACK)
        print("""\
           __.---.__                                                                                        
       .-''   ___   ''-.                                                                                    
     .'   _.-' __'-._   '.                                                                                  
   .'   .'     \ \   '.   '.                             _                                          _       
  /    /    /\  \ \    '----'      ___ _ __   ___   ___ | | ___   _        ___ ___  _ __  ___  ___ | | ___  
 /    '----/ /   \ \--------.     / __| '_ \ / _ \ / _ \| |/ / | | |_____ / __/ _ \| '_ \/ __|/ _ \| |/ _ \\ 
 | SPOOKY   /     |  ACTION  |    \__ \ |_) | (_) | (_) |   <| |_| |_____| (_| (_) | | | \__ \ (_) | |  __/ 
 '-------/ /      `-   ---.  |    |___/ .__/ \___/ \___/|_|\_\\\\__, |      \___\___/|_| |_|___/\___/|_|\___| 
  ----  / /    .    \ \  /   /        |_|                     |___/                                         
  \   \ \/   :(o).   \/ /   /                    - Team 7170 console-based control utility -                
   '.  ''._     `    _.'  .'                                                                                
     '.    '-.____.-'    .'                                                                                 
       '-.._ROBOTICS_..-'                                                                                   
            ''----''                                                                                        
""",
              end="")
        print(Style.RESET_ALL)
Example #14
0
def _print(agent, term, intention, _color_map={}, _current_color=[0]):
    if agent in _color_map:
        color = _color_map[agent]
    else:
        color = COLORS[_current_color[0]]
        _current_color[0] = (_current_color[0] + 1) % len(COLORS)
        _color_map[agent] = color

    memo = {}
    text = " ".join(
        pyson_str(pyson.freeze(t, intention.scope, memo)) for t in term.args)

    with colorama.colorama_text():
        print(color[0],
              color[1],
              agent.name,
              colorama.Fore.RESET,
              colorama.Back.RESET,
              " ",
              text,
              sep="")

    yield
Example #15
0
    def render_class(self, klass: Union[str, type[BaseRenderer]]):
        self._render_class = BaseRenderer._render_classes.get(klass, klass)

    def render(self, renderer: Optional[BaseRenderer] = None):
        self.stay_open = self.default_stay_open
        first_run = True
        if renderer is None:
            renderer = self.render_class(self)
        while self.stay_open or first_run:
            first_run = False
            action = renderer.render()
            if action is not None:
                result = action._invoke('click', renderer)
            else:
                result = None
        return result


if __name__ == '__main__':
    import colorama
    options = [
        MenuOption('opt1', lambda menu: print(menu)),
        MenuOption('opt2', lambda menu: exec('raise Exception')),
        MenuOption(),
        MenuOption('abc', lambda menu: print('abc')),
        MenuOption('def', lambda menu: menu.exit()),
    ]
    mymenu = Menu('Main Menu', options=options)
    with colorama.colorama_text():
        mymenu.render()
Example #16
0
def main(args_in=None):  # pylint: disable=too-many-statements
    """The entry point for the CLI."""
    log = None
    try:
        # see docstring of this file
        parser = argparse.ArgumentParser(description=__doc__)
        # the default command just prints the help message
        # subparsers should set their own default commands
        # also need to set verbose here because now it only gets set if a
        # subcommand is run (which is okay, the help doesn't need it)

        def no_command(args):
            if args.version:
                print("cfn", __version__)
            else:
                parser.print_help()

        parser.set_defaults(command=no_command, verbose=0)
        parser.add_argument(
            "--version",
            action="store_true",
            help="Show the executable version and exit.",
        )

        base_subparser = argparse.ArgumentParser(add_help=False)
        # shared arguments
        base_subparser.add_argument(
            "-v",
            "--verbose",
            action="count",
            default=0,
            help="Increase the output verbosity. Can be specified multiple times.",
        )
        parents = [base_subparser]

        subparsers = parser.add_subparsers(dest="subparser_name")
        init_setup_subparser(subparsers, parents)
        validate_setup_subparser(subparsers, parents)
        submit_setup_subparser(subparsers, parents)
        generate_setup_subparser(subparsers, parents)
        test_setup_subparser(subparsers, parents)
        invoke_setup_subparser(subparsers, parents)
        unittest_patch_setup_subparser(subparsers, parents)
        build_image_setup_subparser(subparsers, parents)
        args = parser.parse_args(args=args_in)

        setup_logging(args.verbose)

        log = logging.getLogger(__name__)
        log.debug("Logging set up successfully")
        log.debug("Running %s: %s", args.subparser_name, args)

        with colorama_text():
            args.command(args)

        log.debug("Finished %s", args.subparser_name)
    except SysExitRecommendedError as e:
        # This is to unify exit messages, and avoid throwing SystemExit in
        # library code, which is hard to catch for consumers. (There are still
        # some cases where it makes sense for the commands to raise SystemExit.)
        log.debug("Caught exit recommendation", exc_info=e)
        log.critical(str(e))
        # pylint: disable=W0707
        raise SystemExit(1)
    except DownstreamError as e:
        # For these operations, we don't want to swallow the exception
        log.debug("Caught downstream error", exc_info=e)
        print("=== Caught downstream error ===", file=sys.stderr)
        print(str(e.__cause__), file=sys.stderr)
        print("---", file=sys.stderr)
        print(
            "If debugging indicates this is a possible error with this program,",
            file=sys.stderr,
        )
        print(
            "please report the issue to the team and include the log file 'rpdk.log'.",
            file=sys.stderr,
        )
        print(
            "Issue tracker: "
            "https://github.com/aws-cloudformation/aws-cloudformation-rpdk/issues",
            file=sys.stderr,
        )
        # pylint: disable=W0707
        raise SystemExit(2)
    except Exception:  # pylint: disable=broad-except
        print("=== Unhandled exception ===", file=sys.stderr)
        print("Please report this issue to the team.", file=sys.stderr)
        print(
            "Issue tracker: "
            "https://github.com/aws-cloudformation/aws-cloudformation-rpdk/issues",
            file=sys.stderr,
        )

        if log:
            print("Please include the log file 'rpdk.log'", file=sys.stderr)
            log.debug("Unhandled exception", exc_info=True)
        else:
            print("Please include this information:", file=sys.stderr)
            import traceback  # pylint: disable=import-outside-toplevel

            traceback.print_exc()
        # pylint: disable=W0707
        raise SystemExit(EXIT_UNHANDLED_EXCEPTION)
def reset_term():
    os.system("clear")
    with colorama_text():
        print(Fore.LIGHTMAGENTA_EX)
        os.system("figlet Enter Code!")
        print(Fore.RESET)
Example #18
0
 def colorama_text(self, tty=True):
     with capture_output() as captured:
         captured.stdout.isatty = lambda: tty
         with colorama.colorama_text(**COLORAMA_KWARGS):
             yield captured
Example #19
0
def main(
    ctx: click.Context,
    filepaths: tuple[str, ...],
    check: bool,
    display_diff: bool,
    in_place: bool,
    no_fix_main_to_bottom: bool,
    reverse: bool,
    no_aggressive: bool,
    encoding: str,
    comment_strategy: CommentStrategy,
    py_version: PyVersion,
    quiet: bool,
    verbose: bool,
    color_off: bool,
    bypass_prompt: BypassPromptLevel,
    dfs: bool,
    bfs: bool,
    separate_class_and_function: bool,
) -> None:
    """the CLI entry"""

    options = SimpleNamespace(**ctx.params)
    validate_args(options)

    if not no_aggressive:
        # Optionally use uvloop to boost speed
        try:
            import uvloop  # type: ignore

            uvloop.install()
        except ImportError:
            pass

    # First confirmation prompt
    if BypassPromptLevel.NO < bypass_prompt < BypassPromptLevel.HIGH:
        ans = click.confirm(
            "Are you sure you want to bypass all confirmation prompts? "
            "(Dangerous, not recommended)"
        )
        if not ans:
            bypass_prompt = BypassPromptLevel.NO

    # Second confirmation prompt
    if BypassPromptLevel.NO < bypass_prompt < BypassPromptLevel.MEDIUM:
        ans = click.confirm(
            "Are you REALLY REALLY REALLY sure you want to bypass all confirmation prompts? "
            "(Dangerous, not recommended)"
        )
        if not ans:
            bypass_prompt = BypassPromptLevel.NO

    files = list(collect_python_files(filepaths))
    if not files:
        print("No file is found")
        return
    print(f"Found {len(files)} files")

    format_option = FormatOption(  # type: ignore
        no_aggressive=no_aggressive,
        reverse=reverse,
        no_fix_main_to_bottom=no_fix_main_to_bottom,
        separate_class_and_function=separate_class_and_function,
    )

    if display_diff:
        file_action = FileAction.DIFF
    elif in_place:
        file_action = FileAction.WRITE
    elif check:
        file_action = FileAction.CHECK
    else:
        file_action = FileAction.PRINT

    if dfs:
        sort_order = SortOrder.DEPTH_FIRST
    elif bfs:
        sort_order = SortOrder.BREADTH_FIRST
    else:
        sort_order = SortOrder.TOPOLOGICAL

    verboseness_context_manager = silent_context() if quiet else contextlib.nullcontext()

    # TODO test --color-off under different environments, eg. Linux, macOS, ...
    colorness_context_manager = no_color_context() if color_off else colorama_text()

    with verboseness_context_manager, colorness_context_manager:

        digest = absort_files(
            files,
            encoding,
            bypass_prompt,
            verbose,
            file_action,
            py_version,
            comment_strategy,
            format_option,
            sort_order,
        )

        display_summary(digest)