Commit Graph

1094 Commits (main)

Author SHA1 Message Date
Jie Luo 6c91de9de9 Nextgen Proto Pythonic API: “Add-on” proto for JSON serialize/parse
- add google.protobuf.proto_json module
- wrap json_format's MessageToDict/ParseDict to the new module:

def serialize(
    message: Message,
    always_print_fields_with_no_presence: bool=False,
    preserving_proto_field_name: bool=False,
    use_integers_for_enums: bool=False,
    descriptor_pool: Optional[DescriptorPool]=None,
    float_precision: int=None,
) -> dict

def parse(
    message_class: Type[Message],
    js_dict: dict,
    ignore_unknown_fields: bool=False,
    descriptor_pool: Optional[DescriptorPool]=None,
    max_recursion_depth: int=100
) -> Message

PiperOrigin-RevId: 634490919
2024-05-16 12:25:01 -07:00
Jie Luo 5a9170701e internal change
PiperOrigin-RevId: 633669104
2024-05-14 12:25:32 -07:00
Jie Luo e7fdab4a2c Add Nextgen python proto_test to github
PiperOrigin-RevId: 632595087
2024-05-10 14:00:10 -07:00
Jie Luo 495ba7bcdb Nextgen Proto Pythonic API: “Add-on” proto for serialize/parse
- add google.protobuf.proto module
- wrap generated SerializeToString and ParseFromString to the new module:

def serialize(message: Message, deterministic: bool=None) -> bytes:
        """Return the serialized proto."""
def parse(message_class: typing.Type[Message], payload: bytes) -> Message:
        """Given a serialized proto, deserialize it into a Message."""

PiperOrigin-RevId: 632223409
2024-05-09 11:53:56 -07:00
Jie Luo 9de810acdc use struct instead of ctype. allows the protobuf python library to work on cpython 3.11's new wasm target [1]
For https://github.com/protocolbuffers/protobuf/pull/12212

PiperOrigin-RevId: 631237602
2024-05-06 17:35:32 -07:00
Jie Luo 24f27c3b88 Nextgen Proto Pythonic API: Add 'in' operator
(Second attempt. The first attempt missed ListValue)

The “in” operator will be consistent with HasField but a little different with Proto Plus.

The detail behavior of “in” operator in Nextgen

* For WKT Struct (to be consist with old Struct behavior):
    -Raise TypeError if not pass a string
    -Check if the key is in the struct.fields

* For WKT ListValue (to be consist with old behavior):
    -Check if the key is in the list_value.values

* For other messages:
    -Raise ValueError if not pass a string
    -Raise ValueError if the string is not a field
    -For Oneof: Check any field under the oneof is set
    -For has-presence field: check if set
    -For non-has-presence field (include repeated fields): raise ValueError

PiperOrigin-RevId: 631143378
2024-05-06 12:13:09 -07:00
Kyle Montemayor c4bf83b534 Automated rollback of commit f799af8bf5.
PiperOrigin-RevId: 629760811
2024-05-01 10:25:29 -07:00
Protobuf Team Bot b3e7a00774 Add unit test enum showing allocation in repeated enum lists
TestPackedTypes' field is unused, it's just there to make the messages symmetric between packed and unpacked versions.

PiperOrigin-RevId: 628913968
2024-04-28 17:27:02 -07:00
Jie Luo 9cc5be12ed Catch all the exceptions in python JSON ParseDict and raise
json_format.ParseError

PiperOrigin-RevId: 627794381
2024-04-24 11:34:41 -07:00
Protobuf Team Bot 1a7aa2c4e8 Internal changes.
PiperOrigin-RevId: 627188953
2024-04-22 16:24:17 -07:00
Protobuf Team Bot 971f88aa63 Improve C++, Python, Java runtime version representations to avoid merge conflicts during release.
PiperOrigin-RevId: 626480269
2024-04-19 15:21:27 -07:00
Mike Kruskal 95877d8569 Updating version.json and repo version numbers to: 28-dev (#16555)
Closes #16555

PiperOrigin-RevId: 626081638
2024-04-18 10:47:14 -07:00
Jie Luo f799af8bf5 Automated rollback of commit 57772cdae7.
PiperOrigin-RevId: 625554434
2024-04-16 21:46:35 -07:00
Mike Kruskal db5814e4ff Use newly split feature defaults in plugins and runtimes.
The new fields fixed_features and overridable_features can be simply merged to recover the old aggregate defaults.  By splitting them though, plugins and runtimes get some extra information about lifetimes for enforcement.

PiperOrigin-RevId: 625527117
2024-04-16 19:18:40 -07:00
Mike Kruskal ea81024ddf Refactor editions infrastructure to a top-level directory.
The only public target here is the edition defaults helper macro, which can be used by external runtimes and plugins.  None of this code is C++-specific though, and should be organized higher up.  Appropriate aliases are also placed at the top level for public targets

PiperOrigin-RevId: 625392504
2024-04-16 11:13:19 -07:00
Kyle Montemayor 57772cdae7 Add __or__ to enum_type_wrapper so they can be used in type unions
PiperOrigin-RevId: 625381202
2024-04-16 10:49:04 -07:00
Mike Kruskal b3b4497d61 Implement feature lifetime validation in protoc and the C++ runtime.
Features need to be validated within the pool being built, since the generated pool only contains extensions linked into the binary (e.g. protoc or a runtime building dynamic protos).  The generated pool may be missing extensions used in this proto or it may have version skew.  Moving to the build pool requires reflective parsing, which in general can't be done from inside the pool's database lock.  This required some refactoring to add a post-build validation phase outside of the lock.

For now, the feature support spec is optional and the checks only are only applied when it's present.  Follow-up changes will add these specs to our existing features and then require them for all FeatureSet extensions.

PiperOrigin-RevId: 623630219
2024-04-10 15:56:20 -07:00
Protobuf Team Bot 8257c4469d Copy py_proto_library from rules_python to protobuf
https://github.com/bazelbuild/rules_python/blob/main/python/private/proto/py_proto_library.bzl

Contributors:
d96214f tpudlik@google.com      Wed Nov 15 02:48:06 2023 -0800  fix: py_proto_library: transitive strip_import_prefix (#1558)
85e50d2 tpudlik@gmail.com       Tue Nov 14 06:04:59 2023 -0800  fix: py_proto_library: append to PYTHONPATH less (#1553)
bee35ef zplin@uber.com  Wed Oct 11 20:59:34 2023 -0700  fix: allowing to import code generated from proto with strip_import_prefix (#1406)
1a333ce ilist@google.com        Tue Jun 20 19:36:39 2023 +0200  fix: plugin_output in py_proto_library rule (#1280)
6905e63 ignas.anikevicius@woven-planet.global   Sat Feb 11 14:02:33 2023 +0900  fix: make py_proto_library respect PyInfo imports (#1046)
0d3c4f7 ilist@google.com        Wed Jan 18 23:15:52 2023 +0000  Implement py_proto_library (#832)
PiperOrigin-RevId: 623401031
2024-04-10 00:35:29 -07:00
Eric Salo 3d21bc26c9 upb: define kUpb_CompareOption_IncludeUnknownFields flag for upb_Message_IsEqual()
PiperOrigin-RevId: 622335300
2024-04-05 18:44:54 -07:00
Mike Kruskal 29c69ff00b Fix text-format delimited field handling
This updates all our text parsers and serializers to better handle tag-delimited fields under editions.  Under proto2, groups were the only tag-delimited fields possible, and the group name (i.e. the message type) was guaranteed to be unique.  Text-format and various generators used this instead of the synthetic field name (lower-cased group name) to represent these fields.

Under editions, we've removed group syntax and allowed any message field to be tag-delimited.  This breaks those cases when adding new tag-delimited fields where the message type might not be unique or correspond to the field name.  Code generators have already been fixed to treat "group-like" fields using the old behavior, and treat new fields like any other sub-message.

This change addresses the text-format issue.  Text parsers will accept *either* the type or field name for "group-like" fields, and only the field name for every other message field.  Text serializers will continue to emit the message name for "group-like" fields, but also use the field name for everything else.

This creates some awkward capitalization behavior for fields that happen to *look* like proto2 groups, but it won't lead to any conflicts or invalid encodings.  A feature will likely be added to edition 2024 to allow for migration off this legacy behavior.

PiperOrigin-RevId: 622260327
2024-04-05 13:08:43 -07:00
Protobuf Team Bot 21d75f861c Remove references to rules_proto
They are not needed after the rules are move into protobuf repo.
Except for the reference to toolchain type, which is currently in rules_proto and can be moved after the implementation is moved into protobuf repo.

PiperOrigin-RevId: 622176865
2024-04-05 07:50:25 -07:00
zhangzibao f6bcf9c78f bugfix json_format.py (#16382)
In the _RegularMessageToJsonObject method, there is no str type conversion for non-bytes type values in the repeated content. This causes an exception in the MessageToJson method, as the jsons data does not allow for the occurrence of byte array type property values.

BUG EG (contains proto and python code):

------------common.proto------------
message SafetyInfo{//
  repeated LoginDevice deviceList = 1;
}

message LoginDevice {
  optional string uuid = 1 [default = ""];
  optional string deviceName = 2 [default = ""];
  optional string deviceType = 3 [default = ""];
  required uint32 lastTime = 4;
}

------------test code(python)------------
from google.protobuf.json_format import MessageToJson

import common_pb2 # generate by common.proto

pb = common_pb2.SafetyInfo()
pb_hex = "0a4e0a2039323833663530356533363332396338356638623866343832613561323061651211636d4a38426c307a4d20446576696365731a0f6950686f6e6520694f532031332e3720dc85a9b00628010a410a206233356161326632366236343966313536393466663761336263303434323163120950432dcdacd0cbb4ef1a0a57696e646f777320313020d5d2c6e705280010001800200028003001" pb.ParseFromString(bytes.fromhex(pb_hex))
print(pb)
print(MessageToJson(pb))

Closes #16382

COPYBARA_INTEGRATE_REVIEW=https://github.com/protocolbuffers/protobuf/pull/16382 from zhangzibao:main 3af2569265
PiperOrigin-RevId: 622156823
2024-04-05 06:06:19 -07:00
Sandy Zhang ed965bd140 Update python_tag select to include python limited_api
This is needed after python/dist:dist's limited_api_wheels was updated from 3.7->3.8 and was causing us to mislabel the python_tag for our 3.8 limited api wheels as the system python version of 3.7.

Also:
* Add LINT to prevent next time
* Clean up some documentation
PiperOrigin-RevId: 621915013
2024-04-04 11:20:37 -07:00
Protobuf Team Bot d7f032ad15 Move private definitions out of //bazel
This is needed to make protobuf/bazel package minimal for other proto rules.

Keep 4 public bzl files in upb/bazel. They end up under protobuf/bazel, and they are legitimately used by other repositories.

Move upb_proto_library_internal/* under bazel/private. Those are utilities used in the rules. Moving them one level deeper makes protobuf/bazel package clean for other rules.

Move build_defs.bzl and amalgamation under /upb/bazel. Those are utilities used in the build.

Move lua.BUILD and python* uner /python/dist. Those are used in the WORKSPACE dependency setup.

PiperOrigin-RevId: 621442236
2024-04-03 01:37:51 -07:00
Jie Luo baf211bf63 Automated rollback of commit de8e550e90.
PiperOrigin-RevId: 621326794
2024-04-02 16:28:26 -07:00
Jie Luo de8e550e90 Nextgen Proto Pythonic API: Add 'in' operator
The “in” operator will be consistent with HasField but a little different with Proto Plus.

The detail behavior of “in” operator in Nextgen for Struct (to be consist with old Struct behavior):
-Raise TypeError if not pass a string
-Check if the key is in the struct.fields

The detail behavior of “in” operator in Nextgen(for other message):
-Raise ValueError if not pass a string
-Raise ValueError if the string is not a field
-For Oneof: Check any field under the oneof is set
-For has-presence field: check if set
-For non-has-presence field (include repeated fields): raise ValueError

PiperOrigin-RevId: 621240977
2024-04-02 11:32:18 -07:00
Protobuf Team Bot 83ec410d30 Internal change
PiperOrigin-RevId: 619377672
2024-03-27 05:50:55 -07:00
Anton Grbin 86abf35ef5 Python JSON parser: Ignore invalid enum string values if ignore_unknown_fields is set (#15887)
# Motivation

This PR fixes failing conformance tests for python with name `IgnoreUnknownEnumStringValue`.

The JSON parsing spec was discussed in https://github.com/protocolbuffers/protobuf/issues/7392.

Recent equivalent changes for other languages:
* Swift: https://github.com/apple/swift-protobuf/pull/1345
* C#: https://github.com/protocolbuffers/protobuf/pull/15758

# Changes

- 1st commit is a noop  refactoring to make relevant _ConvertScalarFieldValue invocations localized
- 2nd commit introduces the child exception of `ParseError` named `EnumStringValueParseError` which is suppressed if `ignore_unknown_fields` is set
- 3rd commit updates the conformance test failure lists

Closes #15887

COPYBARA_INTEGRATE_REVIEW=https://github.com/protocolbuffers/protobuf/pull/15887 from noom:anton/7392/fix-python-test fbcc93a232
PiperOrigin-RevId: 619288323
2024-03-26 13:22:12 -07:00
Jie Luo 7e033c0be1 internal chnge
PiperOrigin-RevId: 619287040
2024-03-26 13:17:46 -07:00
Jie Luo a2cc9f7b62 internal change
PiperOrigin-RevId: 619038132
2024-03-25 20:02:03 -07:00
Jie Luo 7cf02389b3 fix upb python: DO NOT create empty optional field after sorting empty repeated field
PiperOrigin-RevId: 618350866
2024-03-22 20:00:05 -07:00
Eric Salo d452a16b8c upb: fix textformat encoder to print group name instead of field name
PiperOrigin-RevId: 618228797
2024-03-22 10:59:29 -07:00
Mike Kruskal 0e167e796f Disallow all feature types except enum and boolean.
Features are designed as temporary migration tools, and any unbounded type leaves the system open to unexpected use.  Features should have a fixed set of values, with well defined behaviors.

PiperOrigin-RevId: 617933544
2024-03-21 12:51:15 -07:00
Protobuf Team Bot 0442ed62cb Enable Protobuf Python version check.
PiperOrigin-RevId: 617626372
2024-03-20 14:35:37 -07:00
Tiago Quelhas 774627235e Automated Code Change
PiperOrigin-RevId: 617586334
2024-03-20 12:09:39 -07:00
Protobuf Team Bot dca05ea1cd Add a go/pytype annotation on Duration.toTimedelta.
PiperOrigin-RevId: 616938980
2024-03-18 14:03:02 -07:00
Eric Salo e1a19ba8bb upb: add 'options' arg to upb_Message_IsEqual()
PiperOrigin-RevId: 614707625
2024-03-11 10:16:13 -07:00
Jie Luo eee53125c4 internal change
PiperOrigin-RevId: 613982814
2024-03-08 10:55:53 -08:00
Mike Kruskal d5543304d5 Fix has_presence to account for proto3 extensions in Python.
PiperOrigin-RevId: 613361074
2024-03-06 15:32:16 -08:00
Protobuf Team Bot 554a00c40a Introduce Python Protobuf runtime version.
PiperOrigin-RevId: 613224059
2024-03-06 08:26:18 -08:00
Sandy Zhang 5b32936822 Register Scalar/MessageMapContainerTypes as virtual subclasses of MutableMapping instead of inheriting directly.
This prevents these from using abc.ABCMeta metaclass to avoid deprecation warning:
```
DeprecationWarning: Type google._upb._message.MessageMapContainer uses PyType_Spec with a metaclass that has custom tp_new. This is deprecated and will no longer be allowed in Python 3.14.
```

Fixes #15077
Fixes #12186

PiperOrigin-RevId: 613029479
2024-03-05 17:56:32 -08:00
aiuto 3ab1276bbb Update Bazel references to rules_pkg to the supported file locations. (#15780)
WIP:  I want to see this pass CI first.

Fixes: #15779

3 scripted transforms:
```
  -load("@rules_pkg//:mappings.bzl", ...)
  +load("@rules_pkg//pkg:mappings.bzl", ...)
```
```
  -load("@rules_pkg//:pkg.bzl", "pkg_tar")
  +load("@rules_pkg//pkg:tar.bzl", "pkg_tar")
```
```
  -load("@rules_pkg//:pkg.bzl", "pkg_zip")
  +load("@rules_pkg//pkg:zip.bzl", "pkg_zip")
```

Closes #15780

COPYBARA_INTEGRATE_REVIEW=https://github.com/protocolbuffers/protobuf/pull/15780 from aiuto:rules_pkg a630276341
PiperOrigin-RevId: 606641398
2024-02-13 09:08:42 -08:00
Joshua Haberman 776d072fa1 Removed obsolete TODO.
PiperOrigin-RevId: 606317655
2024-02-12 11:48:35 -08:00
Eric Salo c69ed472cd upb: implement minitable-based field iterators
PiperOrigin-RevId: 605718863
2024-02-09 13:39:18 -08:00
Protobuf Team Bot 2fc7022879 Adds string view fields whose accessors are absl::string_view based.
PiperOrigin-RevId: 605368710
2024-02-08 11:04:02 -08:00
Protobuf Team Bot 2699579875 Breaking change: Remove the deprecated always_print_primitive_fields option from Java, Python and C++ JSON parsers.
The replacement always_print_without_presence_fields should be used instead, which is very similar but has consistent handling of optional fields by not affecting them.

PiperOrigin-RevId: 604381178
2024-02-05 11:35:16 -08:00
Protobuf Team Bot 7d43131a0a Rename the 'includingDefaultValueWithoutPresenceFields' and 'always_print_without_presence_fields' to 'alwaysPrintFieldsWithNoPresence' in the Cpp, Py and Java JSON serializers for consistency.
PiperOrigin-RevId: 604292220
2024-02-05 05:53:59 -08:00
Protobuf Team Bot 461b50b180 Stop using including_default_value_fields as a positional argument in json_format_test.py
PiperOrigin-RevId: 603713528
2024-02-02 09:57:56 -08:00
Joshua Haberman 8135fca851 Breaking Change: Removed obsolete/duplicate `setup.py` from Python.
This copy of `setup.py` is obsolete, as it builds the old C++ backend for Protobuf, which has been deprecated and
unused since 4.21.0 when
[the backend was switch to upb](https://protobuf.dev/news/2022-05-06/#python-updates).

The `setup.py` that we actually distribute in our source packages is located in [`python/dist/setup.py`](https://github.com/protocolbuffers/protobuf/blob/main/python/dist/setup.py).  It is not possible to build this `setup.py` directly from the GitHub repo or GitHub release tarball, because it depends on the file layout of our Python source package ([as distributed on PyPI](https://pypi.org/project/protobuf/#files)).  The Python source package uses a layout that pulls together all of the things Python needs:

|Python Source Package Path|GitHub Repo Path|Description|
|-----|-----|-----|
|`setup.py`|`python/dist/setup.py`|
|`google/protobuf/*`|`python/google/protobuf/*`|pure Python sources|
|`python/*`|`python/*`|C extension sources|
|`utf8_range/*`|`third_party/utf8_range`|C UTF-8 Validation Library|
|`upb/*`|`upb/upb/*`|C Protobuf Library|

Users who want to build their own Python packages should build from our source package on PyPI, not from our GitHub repo or our GitHub release tarball.

It is also possible to build our source package from GitHub using the following command (this requires Bazel):

```
$ bazel build //python/dist:source_wheel
```

PiperOrigin-RevId: 603162788
2024-01-31 14:40:41 -08:00
Mike Kruskal 9a020c4a7b Unify behavior of deprecated_legacy_json_field_conflicts across upb and syntax.
This disables all checks of json_name for upb and protoc under both proto2 and proto3.  This option is deprecated that will be removed in future versions, and is only meant as a temporary solution.  This also fixes a latent bug in the calculation of camelcase name in Python/upb.

Fixes #12525

PiperOrigin-RevId: 603158026
2024-01-31 14:21:54 -08:00