繁体   English   中英

git 漂亮格式命令不 output 正确 json 文件

[英]git pretty format command does not output proper json file

我正在执行 git 日志漂亮格式命令,以从 python 的脚本中生成 json 文件。 现在即使 json 文件是用正确的数据生成的,它实际上不是正确的 JSON 格式,因为我无法解析文件,所以这不好。 问题是正在生成的 json 文件的字符串字典格式不正确。 正确的方法是键和值在双引号内。 例如:

{"commit":"b01c255f69f", "merge":"4037e2cc48a 2237c472953", "author":"joe.simmons@eddu.com", "title":"Merge branch into main", "body":"Branch: sync/iap/4c60eb3_infra_409f2907_to_ad"
},

但我的 output 是:

{commit:b01c255f69f, merge:4037e2cc48a 2237c472953, author:joe.simmons@eddu.com, title:Merge branch into main, body:Branch: sync/iap/4c60eb3_infra_409f2907_to_ad
},

结果我无法解析它。

我在脚本中用于获取此 json output 的命令是:

    customer_path = 'git log ' + branch_name + ' ' + '--since="' + log_length + ' days ago"' + ' ' + '--pretty="format:{"commit":"%h", "merge":"%p", "author":"%an", "title":"%s", "body":"%b"}",>' + '"' + json_directory + '"'
    exit_code = os.system(customer_path)
    if exit_code != 0:
        sys.exit(1)

注意:分支名称只是我想要注销的分支,而 log_length 是自那以后的天数,因此假设 30 天前。 主要问题是虽然包含在双引号内的漂亮格式命令没有在双引号内提供 json 字典。 该命令在 windows cmd shell 中执行。

您生成的不是 JSON:

  • 看起来像一个带有非法键和值的 JSON;
  • 它无法处理正确的 escaping (它甚至不关心引号字符);
  • 它更像是 JSON-LD,但由奇怪的总是尾随',\n'分隔(假设您希望它是单个数组,对吗?)。

那么为什么不使用合适的工具来生成 JSON 并让 Git 生成简单的分隔数据,以便可以轻松解析然后正确转换为您想要的任何内容?

在 Python 3 中执行此操作的一种可能的解决方案可能是这样的(假设git命令生成 TSV output 但可能需要一些调整):

#!/usr/bin/env python3

import jsonstreams
import subprocess

branch_name = 'master'
days = '30'
json_output = './log.json'

with subprocess.Popen(['/usr/bin/git', 'log', f'--since="{days} days ago"', '--pretty=format:%h\t%p\t%an\t%s\t%b', branch_name], stdout=subprocess.PIPE) as input:
    with jsonstreams.Stream(jsonstreams.Type.array, filename=json_output) as output:
        while True:
            line = input.stdout.readline()
            if not line:
                break
            record = line.decode("utf-8").split("\t")
            with output.subobject() as output_e:
                output_e.write('commit', record[0])
                output_e.write('merge', record[1])
                output_e.write('author', record[2])
                output_e.write('title', record[3])
                output_e.write('body', record[4])

上面的脚本从 git output 中生成一个合法的 JSON 文档,类似于:

[
    {"commit": "3011203d", "merge": "e84d9feb", "author": "me", "title": "test commit", "body": ""},
    ...
]

(在脚本中打印不漂亮,但仅用于答案片段。)

本例例所示,您需要在format:以确保运行git log命令的 shell 不会解释双引号"xx"

'--pretty="format:\'{"commit":"%h", ....}%n},\''
                  ^^                         ^^

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM