refactor: 统一CLI输出格式为标准JSON
This commit is contained in:
@@ -565,30 +565,69 @@ Examples:
|
||||
|
||||
if args.url:
|
||||
# Single URL mode
|
||||
result = link_parser.parse(args.url)
|
||||
print(format_output(result, args.format))
|
||||
return 0 if result["success"] else 1
|
||||
parsed = link_parser.parse(args.url)
|
||||
|
||||
# 统一输出格式
|
||||
if parsed["success"]:
|
||||
output = {
|
||||
"success": True,
|
||||
"platform": parsed.get("platform"),
|
||||
"type": parsed.get("type"),
|
||||
"id": parsed.get("id"),
|
||||
"filename": f"{parsed.get('platform')}_{parsed.get('id')}.link.json" if parsed.get("platform") and parsed.get("id") else None,
|
||||
"message": "URL解析成功"
|
||||
}
|
||||
else:
|
||||
output = {
|
||||
"success": False,
|
||||
"error": parsed.get("error", "解析失败"),
|
||||
"detail": f"URL: {args.url}"
|
||||
}
|
||||
|
||||
print(json.dumps(output, ensure_ascii=False, indent=2))
|
||||
return 0 if output["success"] else 1
|
||||
|
||||
elif args.batch:
|
||||
try:
|
||||
with open(args.batch, 'r', encoding='utf-8') as f:
|
||||
urls = [line.strip() for line in f if line.strip()]
|
||||
except Exception as e:
|
||||
print(f"Error reading file: {e}", file=sys.stderr)
|
||||
print(json.dumps({
|
||||
"success": False,
|
||||
"error": "读取文件失败",
|
||||
"detail": str(e)
|
||||
}, ensure_ascii=False, indent=2))
|
||||
return 1
|
||||
|
||||
results = []
|
||||
for url in urls:
|
||||
result = link_parser.parse(url)
|
||||
results.append(result)
|
||||
parsed = link_parser.parse(url)
|
||||
if parsed["success"]:
|
||||
results.append({
|
||||
"success": True,
|
||||
"platform": parsed.get("platform"),
|
||||
"type": parsed.get("type"),
|
||||
"id": parsed.get("id"),
|
||||
"filename": f"{parsed.get('platform')}_{parsed.get('id')}.link.json" if parsed.get("platform") and parsed.get("id") else None
|
||||
})
|
||||
else:
|
||||
results.append({
|
||||
"success": False,
|
||||
"error": parsed.get("error", "解析失败"),
|
||||
"detail": f"URL: {url}"
|
||||
})
|
||||
|
||||
if args.output:
|
||||
with open(args.output, 'w', encoding='utf-8') as f:
|
||||
json.dump(results, f, ensure_ascii=False, indent=2)
|
||||
print(f"Results written to {args.output}")
|
||||
print(json.dumps({
|
||||
"success": True,
|
||||
"message": f"结果已保存到 {args.output}",
|
||||
"total": len(results)
|
||||
}, ensure_ascii=False, indent=2))
|
||||
else:
|
||||
for result in results:
|
||||
print(format_output(result, args.format))
|
||||
print(json.dumps(result, ensure_ascii=False, indent=2))
|
||||
print("-" * 40)
|
||||
|
||||
return 0
|
||||
|
||||
Reference in New Issue
Block a user