代码之家  ›  专栏  ›  技术社区  ›  thebjorn

如何在python脚本内部的gitlab输出中创建可折叠的部分?

  •  0
  • thebjorn  · 技术社区  · 2 年前

    根据文件,它应该很简单:

    @contextmanager
    def gitlab_section(name, header):
        print(f'\033[0Ksection_start:{int(time.time())}:{name}[collapsed=true]\r\033[0K{header}')
        yield
        print(f'\033[0Ksection_end:{int(time.time())}:{name}:\r\033[0K')
    

    但是,这样使用它:

    with gitlab_section('first', 'First'):
        print('first section')
    
    print("After first section")
    
    with gitlab_section('second', 'Second'):
        print('second section')
    

    使“After..”行折叠到第一部分。

    我用了一个可怕的破解方法,每次破解后都会启动一个虚拟部分 section_end :

    def unique():
        return int(random.random() * 1000000000)
    
    @contextmanager
    def gitlab_section(name, header):
        sys.stdout.flush()
        sectionid = unique()    # in case someone uses the same name twice...
        print(f'\033[0Ksection_start:{int(time.time())}:{name}_{sectionid}[collapsed=true]\r\033[0K{header}')
        yield
        sys.stdout.flush()
        print(f'\nsection_end:{int(time.time())}:{name}_{sectionid}:\r\033[0K')
        # start a dummy section without a header
        print(f'\033[0Ksection_start:{int(time.time())}:dummy_{unique()}\r\033[0K')
        sys.stdout.flush()
    

    这个 \e[0K 上似乎不需要前缀 section_end (gitlab生成的输出不使用它)。

    虽然这是有效的,但它似乎非常粗鲁。我已经彻底阅读了文档,但也许我在第一个例子中遗漏了一些内容。。?

    嵌套的可折叠部分怎么办,这可能吗?

    0 回复  |  直到 2 年前
        1
  •  1
  •   sytech    2 年前

    您的节结束标记中有一个小错误:

        print(f'\033[0Ksection_end:{int(time.time())}:{name}:\r\033[0K')
    

    应为:

        print(f'\033[0Ksection_end:{int(time.time())}:{name}\r\033[0K')
    

    注意,你有一个额外的 : : 不是节名称中的合法字符,因此regex语法分析器缺少节末尾,这就是为什么后面的行被分组到第一个节中。


    关于嵌套的折叠截面: sections are supposed to be able to be nested infinitely 。这是 originally implemented behind the feature flag infinitely_collapsible_sections 该功能标志已在v15中删除了一段时间,但在撰写本文时(v16.4),该功能当前仍不起作用,原因是 bugs 还有待解决。

    根据目前的实施细节,新的一节将意味着上一节的结束。看见 this MR 了解更多信息。因此,在这个时候,似乎无法嵌套节(或者至少它们不会显示为嵌套在UI中)。