Skip to content

Commit

Permalink
Change proto.encode_text() to omit struct fields with None values.
Browse files Browse the repository at this point in the history
```bzl
# omit 'bar' field
proto.encode_text(struct(foo=1, bar=None))
```

PiperOrigin-RevId: 511759002
Change-Id: I65034b9da59039429fb55f2a3205f98d47ad38f0
  • Loading branch information
Googler authored and copybara-github committed Feb 23, 2023
1 parent 9961a75 commit 88346f1
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ static final class Proto implements StarlarkValue {
+ "The data structure must be recursively composed of strings, ints, floats, or"
+ " bools, or structs, sequences, and dicts of these types.\n"
+ "<p>A struct is converted to a message. Fields are emitted in name order.\n"
+ "Each struct field whose value is None is ignored.\n"
+ "<p>A sequence (such as a list or tuple) is converted to a repeated field.\n"
+ "Its elements must not be sequences or dicts.\n"
+ "<p>A dict is converted to a repeated field of messages with fields named 'key'"
Expand All @@ -108,9 +109,10 @@ static final class Proto implements StarlarkValue {
+ "# field: 1\n"
+ "# field: 2\n"
+ "# field: 3\n\n"
+ "proto.encode_text(struct(field='text'))\n"
+ "proto.encode_text(struct(field='text', ignored_field=None))\n"
+ "# field: \"text\"\n\n"
+ "proto.encode_text(struct(field=struct(inner_field='text')))\n"
+ "proto.encode_text(struct(field=struct(inner_field='text',"
+ " ignored_field=None)))\n"
+ "# field {\n"
+ "# inner_field: \"text\"\n"
+ "# }\n\n"
Expand Down Expand Up @@ -206,6 +208,9 @@ private void field(String name, Object v) throws EvalException {
}

// non-repeated field
if (v == Starlark.NONE) {
return;
}
fieldElement(name, v);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1321,6 +1321,16 @@ public void testSimpleTextMessages() throws Exception {
"}");
}

@Test
public void testNoneStructValue() throws Exception {
checkTextMessage(
"proto.encode_text(struct(a=1, b=None, nested=struct(c=2, d=None)))",
"a: 1",
"nested {",
" c: 2",
"}");
}

@Test
public void testProtoFieldsOrder() throws Exception {
checkTextMessage("struct(d=4, b=2, c=3, a=1).to_proto()", "a: 1", "b: 2", "c: 3", "d: 4");
Expand Down

0 comments on commit 88346f1

Please sign in to comment.