Skip to content

生成 "operator ==" 和 "hashCode" 方法 #19

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion template_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class ${type} {
${properties}

${type}.fromParams({${this.properties}});

${type}.fromJson(jsonRes) {
${construction}
}
Expand All @@ -21,6 +21,17 @@ class ${type} {
String toString() {
return '{${toString}}';
}

@override
bool operator ==(Object other) {
if (identical(other, this)) return true;
return other is ${type}${equals};
}

@override
int get hashCode {
return $jf(${hash});
}
}

"""
Expand Down
17 changes: 16 additions & 1 deletion tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ def add_param_to_code(code, param):
this_properties = 'this.%s, ' % n
construction = ' %s = jsonRes[\'%s\'];\n' % (n, f)
to_string = '"%s": $%s,' % (f, n)
equals = ' &&\n %s == other.%s' % (n, n)

pp = code.find('${properties}')
code = code[:pp] + properties + code[pp:]
Expand All @@ -112,6 +113,11 @@ def add_param_to_code(code, param):
ps = code.find('${toString}')
code = code[:ps] + to_string + code[ps:]

pe = code.find('${equals}')
code = code[:pe + 9] + equals + code[pe + 9:]

code = code.replace('${hash}', '$jc(${hash}, ' + n + '.hashCode)')

t_code = check_level_type(t)

# 字符串类型和Map类型处理,只需要修改toString中的输出方式
Expand Down Expand Up @@ -169,7 +175,15 @@ def build_level_code(level_bean):

# 不管如何,到这里的数据都是目前dict的一级子数据,作为参数传入模板中
code = add_param_to_code(code, (f, t, n))
codes.append(code.replace(',${toString}', '').replace('${construction}', '').replace('${properties}', '').replace('${this.properties}', ''))

codes.append(code
.replace(',${toString}', '')
.replace('${construction}', '')
.replace('${properties}', '')
.replace('${this.properties}', '')
.replace('${equals}', '')
.replace('${hash}', '0')
)


def generate_code(work_bean):
Expand Down Expand Up @@ -211,6 +225,7 @@ def generate_code(work_bean):

# 最终修改,添加json库导包代码,并为顶层对象增加默认构造
out_res = 'import \'dart:convert\' show json;\n'
out_res = out_res + "import 'package:built_value/built_value.dart' show $jc, $jf;\n"
first = True
for line in lines:
if line.startswith('//'):
Expand Down