python Github评论中的渲染表问题

jvlzgdj9  于 2023-10-14  发布在  Python
关注(0)|答案(1)|浏览(108)

所以我用Python代码在Github上发布我的PR提交评论

# Create a table
table = f"""
        
| File Changed | Summary |
|--------------|---------|
{"".join(commit_summary)}
"""

# comment body for review comment
comment_body = f"""
{"".join([f"{line}" for line in summary])}

## Files Changed and Summaries

{table}
"""

comment_data = {
        "commit_id": commit_sha,
        "body": comment_body,
        }
comment_url = f'https://api.github.com/repos/{owner}/{repo_name}/pulls/{pr_number}/reviews'

然而,在github的评论中,这个表是一个普通的文本,而不是一个好看的表,我打算显示
尝试问gpt和检查github文档,但我卡住了

rbpvctlc

rbpvctlc1#

生成markdown表的泛型函数.

from __future__ import annotations

def build_row(field_widths: dict[str, int], row: dict[str, str]) -> str:
    pipe_escape = '\|'
    inner = '|'.join(f'{row[header].replace("|", pipe_escape).ljust(width)}' for header, width in field_widths.items())
    return f'|{inner}|'

def make_table(headers: list[str], rows: list[dict[str, str]]) -> str:
    field_widths = {}
    for header in headers:
        field_widths[header] = len(header) + header.count('|')

    for row in rows:
        for field_name, value in row.items():
            if field_name not in headers:
                raise ValueError(f"field name {field_name!r} not in headers")
            current_width = field_widths[field_name]
            this_width = len(value) + value.count('|')
            if this_width > current_width:
                field_widths[field_name] = this_width

    header_sep = build_row(field_widths, {h: '-' * field_widths[h] for h in headers})
    header_row = {h:h for h in headers}
    header = build_row(field_widths, header_row)
    table_rows = [build_row(field_widths, row) for row in rows]
    newline = '\n'
    table = f'{header}\n{header_sep}\n{newline.join(table_rows)}'
    return table

然后你可以使用这个函数来创建一个你想要的带有你特定的标题和数据的表:

field_names = ['File changed', 'Summary']
rows = [
    {'File changed': '/path/to/foo/bar/baz', 'Summary': '-100 +200'},
    {'File changed': '/path/to/bacon/eggs/spam', 'Summary': '-1 +2'},
    {'File changed': '/path/to/buzz/crash/split', 'Summary': '-1234 +1234'},
]

print(make_table(headers=field_names, rows=rows))

将输出:

|File changed             |Summary    |
|-------------------------|-----------|
|/path/to/foo/bar/baz     |-100 +200  |
|/path/to/bacon/eggs/spam |-1 +2      |
|/path/to/buzz/crash/split|-1234 +1234|

在GitHub markdown中查看时,看起来像:

当将正文发送到GitHub API时,您需要确保其格式正确。也就是说:请求的主体需要进行JSON编码。如果你使用requests库,当你使用json关键字传递comment_data时,这会为你完成,例如。requests.post(comment_url, json=comment_data),否则您需要正确编码您的有效负载。
有关详细信息,请参阅:Posting a markdown table as Pull Request comment to GitHub using GitHub API

相关问题