Coverage for aipyapp/cli/command/cmd_block.py: 0%

1#!/usr/bin/env python

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

3

4 from rich.syntax import Syntax

5

6 from .utils import print_records

7 from .base import CommandMode, Completable

8 from .base_parser import ParserCommand

9 from ... import T

10

11 class BlockCommand(ParserCommand):

12 """Block command"""

13 name = "block"

14 description = T("Manage code blocks")

15 modes = [CommandMode.TASK]

16

17 def get_arg_values(self, arg, subcommand=None, partial_value=''):

18 if arg.name == 'index':

19 ctx = self.manager.context

20 return [Completable(str(block.Index), f"{block.Name} ({block.Language})") for block in ctx.task.list_code_blocks()]

21 return None

22

23 def add_subcommands(self, subparsers):

24 subparsers.add_parser('list', help=T('List code blocks'))

25 parser = subparsers.add_parser('show', help=T('Show code block source'))

26 parser.add_argument('index', type=int, help=T('Index of the code block'))

27 parser = subparsers.add_parser('run', help=T('Run code block'))

28 parser.add_argument('index', type=int, help=T('Index of the code block'))

29

30 def cmd(self, args, ctx):

31 return self.cmd_list(args, ctx)

32

33 def cmd_show(self, args, ctx):

34 """显示代码块源码"""

35 task = ctx.task

36 block = task.get_code_block(args.index)

37 if not block:

38 ctx.console.print(T("Code block not found"))

39 return False

40

41 syntax = Syntax(block.code, block.lang, theme="github-dark", line_numbers=False)

42

43 ctx.console.print(f"\n[bold]{T('Code Block')}: {block.name} (v{block.version})[/bold]")

44 if block.path:

45 ctx.console.print(f"[dim]{T('Path')}: {block.path}[/dim]")

46 ctx.console.print("")

47 ctx.console.print(syntax)

48 return True

49

50 def cmd_run(self, args, ctx):

51 """运行代码块"""

52 task = ctx.task

53 block = task.get_code_block(args.index)

54 if not block:

55 ctx.console.print(T("Code block not found"))

56 return False

57 task.run_code_block(block)

58 return True

59

60 def cmd_list(self, args, ctx):

61 """列出所有代码块"""

62 task = ctx.task

63 blocks = task.list_code_blocks()

64 print_records(blocks, title=T("Code Blocks"))