Skip to content

Commit 4478320

Browse files
mrjerryjohnsandy31415
authored andcommitted
Python Cluster Object - Field Defaults (#12381)
* Python Cluster Object - Field Defaults This initializes the various fields in a cluster object to type-specific default values. This correclty handles nullable and optional types as well. * Missed a couple of places... * Re-run codegen * Re-gen Python cluster objects * Restyle after regen * Remove Objects.py from restyle * Completely disable auto restyle for generated pyhon files Co-authored-by: Andrei Litvin <andy314@gmail.com>
1 parent 1994670 commit 4478320

File tree

6 files changed

+8511
-8958
lines changed

6 files changed

+8511
-8958
lines changed

.restyled.yaml

+2
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,8 @@ exclude:
6767
- "third_party/nanopb/repo/**/*"
6868
- "src/android/CHIPTool/gradlew" # gradle wrapper generated file
6969
- "third_party/android_deps/gradlew" # gradle wrapper generated file
70+
- "src/controller/python/chip/clusters/Objects.py" # generated file, no point to restyle
71+
- "src/controller/python/chip/clusters/CHIPClusters.py" # generated file, no point to restyle
7072

7173

7274
changed_paths:

scripts/tools/zap/generate.py

-18
Original file line numberDiff line numberDiff line change
@@ -146,23 +146,6 @@ def runJavaPrettifier(templates_file, output_dir):
146146
print('google-java-format error:', err)
147147

148148

149-
def runPythonPrettifier(templates_file, output_dir):
150-
try:
151-
jsonData = json.loads(Path(templates_file).read_text())
152-
outputs = [(os.path.join(output_dir, template['output']))
153-
for template in jsonData['templates']]
154-
pyOutputs = list(
155-
filter(lambda filepath: os.path.splitext(filepath)[1] == ".py", outputs))
156-
157-
if not pyOutputs:
158-
return
159-
args = ['autopep8', '--in-place']
160-
args.extend(pyOutputs)
161-
subprocess.check_call(args)
162-
except Exception as err:
163-
print('autopep8 error:', err)
164-
165-
166149
def main():
167150
checkPythonVersion()
168151

@@ -172,7 +155,6 @@ def main():
172155
prettifiers = [
173156
runClangPrettifier,
174157
runJavaPrettifier,
175-
runPythonPrettifier,
176158
]
177159

178160
for prettifier in prettifiers:

src/app/zap-templates/templates/app/helper.js

+81
Original file line numberDiff line numberDiff line change
@@ -516,6 +516,86 @@ function zapTypeToPythonClusterObjectType(type, options)
516516
return _zapTypeToPythonClusterObjectType.call(this, type, options)
517517
}
518518

519+
async function _getPythonFieldDefault(type, options)
520+
{
521+
async function fn(pkgId)
522+
{
523+
const ns = options.hash.ns;
524+
const typeChecker = async (method) => zclHelper[method](this.global.db, type, pkgId).then(zclType => zclType != 'unknown');
525+
526+
if (await typeChecker('isEnum')) {
527+
return '0';
528+
}
529+
530+
if (await typeChecker('isBitmap')) {
531+
return '0';
532+
}
533+
534+
if (await typeChecker('isStruct')) {
535+
return 'field(default_factory=lambda: ' + ns + '.Structs.' + type + '())';
536+
}
537+
538+
if (StringHelper.isCharString(type)) {
539+
return '""';
540+
}
541+
542+
if (StringHelper.isOctetString(type)) {
543+
return 'b""';
544+
}
545+
546+
if ([ 'single', 'double' ].includes(type.toLowerCase())) {
547+
return '0.0';
548+
}
549+
550+
if (type.toLowerCase() == 'boolean') {
551+
return 'False'
552+
}
553+
554+
// #10748: asUnderlyingZclType will emit wrong types for int{48|56|64}(u), so we process all int values here.
555+
if (type.toLowerCase().match(/^int\d+$/)) {
556+
return '0'
557+
}
558+
559+
if (type.toLowerCase().match(/^int\d+u$/)) {
560+
return '0'
561+
}
562+
563+
resolvedType = await zclHelper.asUnderlyingZclType.call({ global : this.global }, type, options);
564+
{
565+
basicType = ChipTypesHelper.asBasicType(resolvedType);
566+
if (basicType.match(/^int\d+_t$/)) {
567+
return '0'
568+
}
569+
if (basicType.match(/^uint\d+_t$/)) {
570+
return '0'
571+
}
572+
}
573+
}
574+
575+
let promise = templateUtil.ensureZclPackageId(this).then(fn.bind(this));
576+
if ((this.isList || this.isArray || this.entryType) && !options.hash.forceNotList) {
577+
promise = promise.then(typeStr => `field(default_factory=lambda: [])`);
578+
}
579+
580+
const isNull = (this.isNullable && !options.hash.forceNotNullable);
581+
const isOptional = (this.isOptional && !options.hash.forceNotOptional);
582+
583+
if (isNull && isOptional) {
584+
promise = promise.then(typeStr => `None`);
585+
} else if (isNull) {
586+
promise = promise.then(typeStr => `NullValue`);
587+
} else if (isOptional) {
588+
promise = promise.then(typeStr => `None`);
589+
}
590+
591+
return templateUtil.templatePromise(this.global, promise)
592+
}
593+
594+
function getPythonFieldDefault(type, options)
595+
{
596+
return _getPythonFieldDefault.call(this, type, options)
597+
}
598+
519599
async function getResponseCommandName(responseRef, options)
520600
{
521601
let pkgId = await templateUtil.ensureZclPackageId(this);
@@ -620,3 +700,4 @@ exports.zapTypeToDecodableClusterObjectType = zapTypeToDecodableClusterObjectTyp
620700
exports.zapTypeToPythonClusterObjectType = zapTypeToPythonClusterObjectType;
621701
exports.getResponseCommandName = getResponseCommandName;
622702
exports.isWeaklyTypedEnum = isWeaklyTypedEnum;
703+
exports.getPythonFieldDefault = getPythonFieldDefault;

0 commit comments

Comments
 (0)