好吧,在厌倦了将 VAPI 定义手动复制到自省注释中的乏味之后,我编写了这个(粗略的)脚本来为我做这件事:
#!/bin/env python
import sys
from collections import defaultdict
ANNOTATION = """/**
* %s:
%s *
* Returns:%s
*/
"""
PARAMETER = """ * @%s:%s
"""
methods = defaultdict(set)
attrs = defaultdict(dict)
with open(sys.argv[1]) as vapi:
for line in vapi:
tokens = line.split()
try:
names = tuple(tokens[0].split('.'))
except IndexError:
continue
attrs[names] = {}
for attribute in tokens[1:]:
key, val = attribute.split('=')
if val == '"1"': val = True
if val == '"0"': val = False
attrs[names][key] = val
methods[names[0]]
if len(names) > 1:
methods[names[0]].add(names[-1])
for method in methods:
params = ''
for param in methods[method]:
param_attributes = ''
param_attrs = attrs[(method, param)]
if param_attrs.get('hidden'):
param_attributes += ' (skip)'
if param_attrs.get('is_out'):
param_attributes += ' (out)'
if param_attrs.get('transfer_ownership'):
param_attributes += ' (transfer full)'
elif 'transfer_ownership' in param_attrs:
param_attributes += ' (transfer none)'
if param_attrs.get('array_null_terminated'):
param_attributes += ' (array zero-terminated=1)'
if param_attrs.get('array_length_pos'):
param_attributes += ' (array length=FIXME)'
if param_attributes:
param_attributes += ':'
params += PARAMETER % (param, param_attributes)
attributes = ''
method_attrs = attrs[(method,)]
if method_attrs.get('transfer_ownership'):
attributes += ' (transfer full)'
elif 'transfer_ownership' in method_attrs:
attributes += ' (transfer none)'
if method_attrs.get('nullable'):
attributes += ' (allow-none)'
if method_attrs.get('array_null_terminated'):
attributes += ' (array zero-terminated=1)'
if attributes:
attributes += ':'
print ANNOTATION % (method, params, attributes)
这显然有一些缺点:它不会将注释插入代码中,它只是将它们打印出来,因此您必须进行大量复制和粘贴才能将所有内容放到正确的位置。它也不能很好地处理数组,但它至少可以让您知道何时需要手动修复数组。总而言之,与手动解析相比,运行此脚本然后处理结果的工作量要少得多。我把它贴在这里是希望它被谷歌采纳,并且有一天其他人可能会受益(尽管我非常希望从这里开始的所有基于 GObject 的项目都只是从注释开始,然后使用 vapigen)。