Exemplo n.º 1
0
    def run_file(self, file: str) -> Union[tuple, str]:
        """Send code form file to the api and return the response."""
        args = helpers.get_args()
        stdin = helpers.get_stdin()

        try:
            with open(file, "r", encoding="utf-8") as f:
                code = f.read()

            if not any(file.endswith("." + ext) for ext in self.extensions):
                CONSOLE.print("File Extension language is not supported!",
                              style="bold red")
                helpers.close()

        except FileNotFoundError:
            CONSOLE.print("Path is invalid; File not found", style="bold red")
            helpers.close()

        language = self.extensions[file[file.rfind(".") + 1:]]

        payload = PistonQuery(
            language=language,
            code=code,
            args=args,
            stdin=stdin,
        )

        data = services.query_piston(CONSOLE, payload)

        if len(data["output"]) == 0:
            return "Your code ran without output.", language

        return data["output"].split("\n"), language
Exemplo n.º 2
0
    def ask_input(self, theme: str) -> Union[tuple, str]:
        """
        Make a multiline prompt for code input and send the code to the api.

        The compiled output from the api is returned.
        """
        language = helpers.get_lang()
        args = helpers.get_args()
        stdin = helpers.get_stdin()

        CONSOLE.print(
            "[green]Enter your code, (press esc + enter to run)[/green]")
        style = helpers.set_style(theme)

        CONSOLE.print()
        code = prompt(
            "",
            lexer=PygmentsLexer(lexers_dict[language]),
            include_default_pygments_style=False,
            style=style,
            multiline=True,
        )
        payload = PistonQuery(language=language,
                              args=args,
                              stdin=stdin,
                              code=code)

        data = services.query_piston(CONSOLE, payload)

        if len(data["output"]) == 0:
            return "Your code ran without output.", language

        return data["output"].split("\n"), language
Exemplo n.º 3
0
def cli_failed_request_cache(ctx: click.Context,
                             timeline: int,
                             clear_cache: bool,
                             cache_path: bool,
                             cache_file: Optional[str] = None) -> None:
    """
    This command allows you to run cached piston-cli queries.

    In case of connection timeout, or network connection relation problems, piston-cli stores
    the query which is being sent to the piston API in cache, currently this is default according
    to the operating system and cannot be changed. You can view the path of the caching directory
    by specifying **--cache-path** option to this command, remember not the root cli group.

    Just got back your internet, and want to run your last piston-cli query. You can use the timeline argument
    it allows you to specify the 'timeline' of the query you want to run, say you want to run your second last
    query, remember this is in respect of request error queries, you can specify it as `2`. For example:

    $ piston cache 2
    """
    config = ctx.obj["config"]
    cache_glob = glob.glob(str(CACHE_LOCATION) + "/*")
    console = ctx.obj["console"]

    if cache_path:
        console.print(f"[blue]Your piston-cli cache is stored at "
                      f"[link={CACHE_LOCATION.as_uri()}]{CACHE_LOCATION}[/]")
        ctx.exit()

    if clear_cache:
        with console.status("Aye Aye! Cleaning your cache",
                            spinner=random.choice(SPINNERS)):
            for f in cache_glob:
                os.remove(f)
        console.print("[blue]Your cache has been clean![/]")
        ctx.exit()

    ordered_cache_files = list(cache_glob)
    ordered_cache_files = [
        file for file in ordered_cache_files if file.endswith(".json")
    ]
    ordered_cache_files.sort(key=lambda x: os.path.getmtime(x))

    cache_file = cache_file or ordered_cache_files[
        timeline - 1]  # Python has zero-based indexing

    with open(cache_file, "r") as fp:
        data = json.load(fp)

    query = PistonQuery(data["language"], data["source"], data["args"],
                        data["stdin"])
    data = query_piston(ctx, console, query, cache_run=True)
    output = [data["output"].split("\n"),
              "Your code ran without output."][len(data["output"]) == 0]

    console.print(f"\nHere is your output for {cache_file.__str__()}:")
    console.print(helpers.print_msg_box(
        output,
        style=config["box_style"],
    ))
Exemplo n.º 4
0
    def prompt(self) -> PistonQuery:
        """Prompt the user for code input."""
        code = self.prompt_session.prompt(style=self.style, )

        args = helpers.get_args(self.console)
        stdin = helpers.get_stdin(self.console)

        return PistonQuery(
            language=self.language,
            code=code,
            args=args,
            stdin=stdin,
        )
Exemplo n.º 5
0
    def ask_input(self) -> Optional[Union[tuple, str]]:
        """
        Make a multiline prompt for code input and send the code to the api.

        The compiled output from the api is returned.
        """
        language = helpers.get_lang()
        args = helpers.get_args()
        stdin = helpers.get_stdin()
        code = self.get_code()

        if not code:
            return

        payload = PistonQuery(language=language, args=args, stdin=stdin, code=code)
        data = services.query_piston(CONSOLE, payload)

        if len(data["output"]) == 0:
            return "Your code ran without output.", language

        return data["output"].split("\n"), language
Exemplo n.º 6
0
def run_link(ctx: click.Context, link: str,
             language: str) -> Optional[Union[list, str]]:
    """
    Make a multiline prompt for code input and send the code to the api.

    The compiled output from the api is returned.
    """
    console = ctx.obj["console"]
    args = helpers.get_args(console)
    stdin = helpers.get_stdin(console)
    code = get_code(console, link)

    if not code:
        return

    payload = PistonQuery(language=language, args=args, stdin=stdin, code=code)
    data = services.query_piston(ctx, console, payload)

    if len(data["output"]) == 0:
        return "Your code ran without output."

    return data["output"].split("\n")
Exemplo n.º 7
0
def run_file(ctx: click.Context,
             file: str,
             args: list[str] = None) -> Union[list, str]:
    """Send code form file to the api and return the response."""
    console = ctx.obj["console"]
    if not args:
        args = helpers.get_args(console)
    stdin = helpers.get_stdin(console)

    try:
        with open(file, "r", encoding="utf-8") as f:
            code = f.read()

        if not any(file.endswith("." + ext) for ext in lang_extensions):
            console.print("File Extension language is not supported!",
                          style="bold red")
            ctx.exit()

    except FileNotFoundError:
        console.print("Path is invalid; File not found", style="bold red")
        ctx.exit()

    language = lang_extensions[file[file.rfind(".") + 1:]]

    payload = PistonQuery(
        language=language,
        code=code,
        args=args,
        stdin=stdin,
    )

    data = services.query_piston(ctx, console, payload)

    if len(data["output"]) == 0:
        return "Your code ran without output."

    return data["output"].split("\n")