[
  {
    "path": ".gitignore",
    "content": "target\nrust\n*.tar.gz\n*~\n*.bk\npq\n"
  },
  {
    "path": "Cargo.toml",
    "content": "[package]\nname = \"pq\"\nversion = \"1.4.4\"\nauthors = [\"Sevag Hanssian <sevag.hanssian@gmail.com>\"]\ndescription = \"jq for protobuf\"\nrepository = \"https://github.com/sevagh/pq\"\ndocumentation = \"https://github.com/sevagh/pq\"\nreadme = \"README.md\"\nlicense = \"MIT\"\nkeywords = [\"protobuf\", \"serde\"]\nexclude = [\"pq-bin.tar.gz\", \"pq\", \"target/**\"]\nedition = \"2021\"\n\n[dependencies]\nopenssl = { version = \"0.10\", features = [\"vendored\"] }\nserde = \"1.0\"\nerased_serde_json = { path = \"erased-serde-json\", version = \"0.1.3\" }\nserde_json = \"1.0\"\nserde-protobuf = \"0.8\"\nprotobuf = \"2.3\"\nstream_delimit = { path = \"stream-delimit\", version = \"0.5.7\" }\nclap = \"2\"\nlibc = \"0.2\"\ndirs = \"2.0\"\nserde-transcode = \">= 1.1, <2\"\ndefault-env = \"0.1.1\"\n\n[dev-dependencies]\nassert_cli = \"0.6\"\n\n[features]\ndefault = [\"stream_delimit/with_kafka\"]\n\n[workspace]\nmembers = [\"stream-delimit\", \"erased-serde-json\"]\ndefault-members = [\".\", \"stream-delimit\", \"erased-serde-json\"]\n\n[profile.release]\ndebug = true\nlto = true\npanic = \"abort\"\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2017 Sevag Hanssian\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "Makefile",
    "content": "WORKSPACES=\"./\" \"./stream-delimit/\"\nDOCKER_BIN ?= docker\nDOCKER_IMAGE=docker.io/clux/muslrust\nDOCKER_ARGS=run -v $(PWD):/volume:Z -w /volume -t $(DOCKER_IMAGE)\nCARGO_TOKEN:=$(shell grep 'token' ~/.cargo/credentials.toml | cut -d'\"' -f2)\n\nall: debug\n\ndocker:\n\t$(DOCKER_BIN) pull $(DOCKER_IMAGE)\n\ndebug: docker\n\t$(DOCKER_BIN) $(DOCKER_ARGS) sh -c \"cargo build --verbose\"\n\nrelease: docker\n\t$(DOCKER_BIN) $(DOCKER_ARGS) sh -c \"cargo build --verbose --release\"\n\ntest: docker\n\t$(DOCKER_BIN) $(DOCKER_ARGS) sh -c \"cargo test --verbose\"\n\npublish: docker\n\t$(DOCKER_BIN) $(DOCKER_ARGS) sh -c \"cargo login $(CARGO_TOKEN) && cd stream-delimit && cargo publish ; cd ../ && cd erased-serde-json && cargo publish ; cd ../ && cargo publish\"\n\nfmt:\n\t-cargo fmt --all\n\t-black utils/*.py\n\nclippy:\n\t-cargo clippy --all\n\npackage: release\n\ttar -C target/x86_64-unknown-linux-musl/release -czvf pq-bin.tar.gz pq\n\n.PHONY: all debug release package\n"
  },
  {
    "path": "README.md",
    "content": "# pq [![license](https://img.shields.io/github/license/sevagh/pq.svg)](https://github.com/sevagh/pq/blob/master/LICENSE) [![Crates.io](https://img.shields.io/crates/v/pq.svg)](https://crates.io/crates/pq)\n\n### protobuf to json deserializer, written in Rust\n\n`pq` is a tool which deserializes protobuf messages given a set of pre-compiled `.fdset` files. It can understand varint/leb128-delimited/i32be streams, and it can connect to Kafka.\n\n`pq` will pretty-print when outputting to a tty, but you should pipe it to `jq` for more fully-featured json handling.\n\n### Download\n\npq is on [crates.io](https://crates.io/crates/pq): `cargo install pq`. You can also download a static binary from the [releases page](https://github.com/sevagh/pq/releases).\n\n### Usage\n\n**new** You can now pass in a proto file and have pq compile it on the fly using `protoc`:\n\n```\n$ pq --protofile ./tests/protos/dog.proto  --msgtype com.example.dog.Dog <./tests/samples/dog\n{\n  \"breed\": \"gsd\",\n  \"age\": 3,\n  \"temperament\": \"excited\"\n}\n```\n\nUse PROTOC and PROTOC_INCLUDE to control the executed protoc binary and configure the `-I=/proto/path` argument (design copied from [prost](https://github.com/danburkert/prost/blob/master/prost-build/src/lib.rs)).\n\nTo set up, put your `*.fdset` files in `~/.pq`, `/etc/pq`, or a different directory specified with the `FDSET_PATH` env var:\n\n```\n$ protoc -o dog.fdset dog.proto\n$ protoc -o person.fdset person.proto\n$ cp *.fdset ~/.pq/\n```\n\nYou can specify additional fdset directories or files via options:\n\n```\n$ pq --msgtype com.example.dog.Dog --fdsetdir ./tests/fdsets <./tests/samples/dog\n$ pq --msgtype com.example.dog.Dog --fdsetfile ./tests/fdsets/dog.fdset <./tests/samples/dog\n```\n\nPipe a single compiled protobuf message:\n\n```\n$ pq --msgtype com.example.dog.Dog <./tests/samples/dog\n{\n  \"age\": 4,\n  \"breed\": \"poodle\",\n  \"temperament\": \"excited\"\n}\n```\n\nPipe a `varint` or `leb128` delimited stream:\n\n```\n$ pq --msgtype com.example.dog.Dog --stream varint <./tests/samples/dog_stream\n{\n  \"age\": 10,\n  \"breed\": \"gsd\",\n  \"temperament\": \"aggressive\"\n}\n```\n\nConsume from a Kafka stream:\n\n```\n$ pq kafka my_topic --brokers 192.168.0.1:9092 --beginning --count 1 --msgtype com.example.dog.Dog\n{\n  \"age\": 10,\n  \"breed\": \"gsd\",\n  \"temperament\": \"aggressive\"\n}\n```\n\nConvert a Kafka stream to varint-delimited:\n\n```\n$ pq kafka my_topic --brokers=192.168.0.1:9092 --count 1 --convert varint |\\\n> pq --msgtype com.example.dog.Dog --stream varint\n{\n  \"age\": 10,\n  \"breed\": \"gsd\",\n  \"temperament\": \"aggressive\"\n}\n```\n\nPipe `kafkacat` output to it:\n```\n$ kafkacat -b 192.168.0.1:9092 -C -u -q -f \"%R%s\" -t my_topic |\\\n> pq --msgtype=com.example.dog.Dog --stream i32be\n{\n  \"age\": 10,\n  \"breed\": \"gsd\",\n  \"temperament\": \"aggressive\"\n}\n```\n\n### Compile without kafka\n\nTo compile `pq` without kafka support, run:\n\n```\n$ cargo build --no-default-features\n```\n\n### Compile for Windows\n\n1. Install [Visual Studio Installer](https://visualstudio.microsoft.com/downloads/) Community edition\n2. Run the installer and install `Visual Studio Build Tools 2019`. You need the `C++ Build Tools` workload. Note that you can't just install the minimal package, you also need `MSVC C++ x64/86 Build Tools` and `Windows 10 SDK`.\n3. Open `x64 Native Tools Command Prompt` from the start menu.\n4. Download and run [`rustup-init.exe`](https://win.rustup.rs/x86_64)\n5. Close and reopen your terminal (so `cargo` will be in your path)\n6. Run `cargo install --no-default-features pq`\n\nNote that this will disable the Kafka feature, which is not currently supported on Windows.\n"
  },
  {
    "path": "erased-serde-json/.gitignore",
    "content": "target/\n**/*.rs.bk\n*.sw[po]\nCargo.lock\n"
  },
  {
    "path": "erased-serde-json/Cargo.toml",
    "content": "[package]\nname = \"erased_serde_json\"\nversion = \"0.1.3\"\nauthors = [\"Sevag Hanssian <sevag.hanssian@gmail.com>\"]\nlicense = \"MIT/Apache-2.0\"\ndescription = \"Type-erased Formatter trait for serde_json::ser::Formatter\"\nrepository = \"https://github.com/sevagh/erased-serde-json\"\ndocumentation = \"https://github.com/sevagh/erased-serde-json\"\nkeywords = [\"json\", \"serde\", \"serialization\"]\ncategories = [\"encoding\"]\nreadme = \"README.md\"\ninclude = [\"Cargo.toml\", \"src/**/*.rs\", \"README.md\", \"LICENSE-APACHE\", \"LICENSE-MIT\"]\nedition = \"2018\"\n\n[dependencies]\nserde = \"1.0\"\nserde_json = \"1.0.2\"\n"
  },
  {
    "path": "erased-serde-json/LICENSE-APACHE",
    "content": "                              Apache License\n                        Version 2.0, January 2004\n                     http://www.apache.org/licenses/\n\nTERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n1. Definitions.\n\n   \"License\" shall mean the terms and conditions for use, reproduction,\n   and distribution as defined by Sections 1 through 9 of this document.\n\n   \"Licensor\" shall mean the copyright owner or entity authorized by\n   the copyright owner that is granting the License.\n\n   \"Legal Entity\" shall mean the union of the acting entity and all\n   other entities that control, are controlled by, or are under common\n   control with that entity. For the purposes of this definition,\n   \"control\" means (i) the power, direct or indirect, to cause the\n   direction or management of such entity, whether by contract or\n   otherwise, or (ii) ownership of fifty percent (50%) or more of the\n   outstanding shares, or (iii) beneficial ownership of such entity.\n\n   \"You\" (or \"Your\") shall mean an individual or Legal Entity\n   exercising permissions granted by this License.\n\n   \"Source\" form shall mean the preferred form for making modifications,\n   including but not limited to software source code, documentation\n   source, and configuration files.\n\n   \"Object\" form shall mean any form resulting from mechanical\n   transformation or translation of a Source form, including but\n   not limited to compiled object code, generated documentation,\n   and conversions to other media types.\n\n   \"Work\" shall mean the work of authorship, whether in Source or\n   Object form, made available under the License, as indicated by a\n   copyright notice that is included in or attached to the work\n   (an example is provided in the Appendix below).\n\n   \"Derivative Works\" shall mean any work, whether in Source or Object\n   form, that is based on (or derived from) the Work and for which the\n   editorial revisions, annotations, elaborations, or other modifications\n   represent, as a whole, an original work of authorship. For the purposes\n   of this License, Derivative Works shall not include works that remain\n   separable from, or merely link (or bind by name) to the interfaces of,\n   the Work and Derivative Works thereof.\n\n   \"Contribution\" shall mean any work of authorship, including\n   the original version of the Work and any modifications or additions\n   to that Work or Derivative Works thereof, that is intentionally\n   submitted to Licensor for inclusion in the Work by the copyright owner\n   or by an individual or Legal Entity authorized to submit on behalf of\n   the copyright owner. For the purposes of this definition, \"submitted\"\n   means any form of electronic, verbal, or written communication sent\n   to the Licensor or its representatives, including but not limited to\n   communication on electronic mailing lists, source code control systems,\n   and issue tracking systems that are managed by, or on behalf of, the\n   Licensor for the purpose of discussing and improving the Work, but\n   excluding communication that is conspicuously marked or otherwise\n   designated in writing by the copyright owner as \"Not a Contribution.\"\n\n   \"Contributor\" shall mean Licensor and any individual or Legal Entity\n   on behalf of whom a Contribution has been received by Licensor and\n   subsequently incorporated within the Work.\n\n2. Grant of Copyright License. Subject to the terms and conditions of\n   this License, each Contributor hereby grants to You a perpetual,\n   worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n   copyright license to reproduce, prepare Derivative Works of,\n   publicly display, publicly perform, sublicense, and distribute the\n   Work and such Derivative Works in Source or Object form.\n\n3. Grant of Patent License. Subject to the terms and conditions of\n   this License, each Contributor hereby grants to You a perpetual,\n   worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n   (except as stated in this section) patent license to make, have made,\n   use, offer to sell, sell, import, and otherwise transfer the Work,\n   where such license applies only to those patent claims licensable\n   by such Contributor that are necessarily infringed by their\n   Contribution(s) alone or by combination of their Contribution(s)\n   with the Work to which such Contribution(s) was submitted. If You\n   institute patent litigation against any entity (including a\n   cross-claim or counterclaim in a lawsuit) alleging that the Work\n   or a Contribution incorporated within the Work constitutes direct\n   or contributory patent infringement, then any patent licenses\n   granted to You under this License for that Work shall terminate\n   as of the date such litigation is filed.\n\n4. Redistribution. You may reproduce and distribute copies of the\n   Work or Derivative Works thereof in any medium, with or without\n   modifications, and in Source or Object form, provided that You\n   meet the following conditions:\n\n   (a) You must give any other recipients of the Work or\n       Derivative Works a copy of this License; and\n\n   (b) You must cause any modified files to carry prominent notices\n       stating that You changed the files; and\n\n   (c) You must retain, in the Source form of any Derivative Works\n       that You distribute, all copyright, patent, trademark, and\n       attribution notices from the Source form of the Work,\n       excluding those notices that do not pertain to any part of\n       the Derivative Works; and\n\n   (d) If the Work includes a \"NOTICE\" text file as part of its\n       distribution, then any Derivative Works that You distribute must\n       include a readable copy of the attribution notices contained\n       within such NOTICE file, excluding those notices that do not\n       pertain to any part of the Derivative Works, in at least one\n       of the following places: within a NOTICE text file distributed\n       as part of the Derivative Works; within the Source form or\n       documentation, if provided along with the Derivative Works; or,\n       within a display generated by the Derivative Works, if and\n       wherever such third-party notices normally appear. The contents\n       of the NOTICE file are for informational purposes only and\n       do not modify the License. You may add Your own attribution\n       notices within Derivative Works that You distribute, alongside\n       or as an addendum to the NOTICE text from the Work, provided\n       that such additional attribution notices cannot be construed\n       as modifying the License.\n\n   You may add Your own copyright statement to Your modifications and\n   may provide additional or different license terms and conditions\n   for use, reproduction, or distribution of Your modifications, or\n   for any such Derivative Works as a whole, provided Your use,\n   reproduction, and distribution of the Work otherwise complies with\n   the conditions stated in this License.\n\n5. Submission of Contributions. Unless You explicitly state otherwise,\n   any Contribution intentionally submitted for inclusion in the Work\n   by You to the Licensor shall be under the terms and conditions of\n   this License, without any additional terms or conditions.\n   Notwithstanding the above, nothing herein shall supersede or modify\n   the terms of any separate license agreement you may have executed\n   with Licensor regarding such Contributions.\n\n6. Trademarks. This License does not grant permission to use the trade\n   names, trademarks, service marks, or product names of the Licensor,\n   except as required for reasonable and customary use in describing the\n   origin of the Work and reproducing the content of the NOTICE file.\n\n7. Disclaimer of Warranty. Unless required by applicable law or\n   agreed to in writing, Licensor provides the Work (and each\n   Contributor provides its Contributions) on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n   implied, including, without limitation, any warranties or conditions\n   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n   PARTICULAR PURPOSE. You are solely responsible for determining the\n   appropriateness of using or redistributing the Work and assume any\n   risks associated with Your exercise of permissions under this License.\n\n8. Limitation of Liability. In no event and under no legal theory,\n   whether in tort (including negligence), contract, or otherwise,\n   unless required by applicable law (such as deliberate and grossly\n   negligent acts) or agreed to in writing, shall any Contributor be\n   liable to You for damages, including any direct, indirect, special,\n   incidental, or consequential damages of any character arising as a\n   result of this License or out of the use or inability to use the\n   Work (including but not limited to damages for loss of goodwill,\n   work stoppage, computer failure or malfunction, or any and all\n   other commercial damages or losses), even if such Contributor\n   has been advised of the possibility of such damages.\n\n9. Accepting Warranty or Additional Liability. While redistributing\n   the Work or Derivative Works thereof, You may choose to offer,\n   and charge a fee for, acceptance of support, warranty, indemnity,\n   or other liability obligations and/or rights consistent with this\n   License. However, in accepting such obligations, You may act only\n   on Your own behalf and on Your sole responsibility, not on behalf\n   of any other Contributor, and only if You agree to indemnify,\n   defend, and hold each Contributor harmless for any liability\n   incurred by, or claims asserted against, such Contributor by reason\n   of your accepting any such warranty or additional liability.\n\nEND OF TERMS AND CONDITIONS\n\nAPPENDIX: How to apply the Apache License to your work.\n\n   To apply the Apache License to your work, attach the following\n   boilerplate notice, with the fields enclosed by brackets \"[]\"\n   replaced with your own identifying information. (Don't include\n   the brackets!)  The text should be enclosed in the appropriate\n   comment syntax for the file format. We also recommend that a\n   file or class name and description of purpose be included on the\n   same \"printed page\" as the copyright notice for easier\n   identification within third-party archives.\n\nCopyright [yyyy] [name of copyright owner]\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n\thttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n"
  },
  {
    "path": "erased-serde-json/LICENSE-MIT",
    "content": "Copyright (c) 2014 The Rust Project Developers\n\nPermission is hereby granted, free of charge, to any\nperson obtaining a copy of this software and associated\ndocumentation files (the \"Software\"), to deal in the\nSoftware without restriction, including without\nlimitation the rights to use, copy, modify, merge,\npublish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software\nis furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice\nshall be included in all copies or substantial portions\nof the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF\nANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\nTO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\nSHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR\nIN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n"
  },
  {
    "path": "erased-serde-json/README.md",
    "content": "Inspired by https://github.com/dtolnay/erased-serde\n\n# erased-serde-json [![Crates.io](https://img.shields.io/crates/v/erased_serde_json.svg)](https://crates.io/crates/erased_serde_json) [![Crates.io](https://img.shields.io/crates/d/erased_serde_json.svg)](https://github.com/sevagh/pq/tree/master/erased-serde-json)\n\nA helper crate for pq.\n"
  },
  {
    "path": "erased-serde-json/src/lib.rs",
    "content": "extern crate serde;\nextern crate serde_json;\n\npub use self::ser::Formatter;\n\npub mod ser;\n"
  },
  {
    "path": "erased-serde-json/src/ser.rs",
    "content": "use std::io;\n\nuse serde_json::ser::CharEscape;\n\npub trait Formatter {\n    fn erased_write_null(&mut self, writer: &mut dyn io::Write) -> Result<(), io::Error>;\n    fn erased_write_bool(\n        &mut self,\n        writer: &mut dyn io::Write,\n        value: bool,\n    ) -> Result<(), io::Error>;\n    fn erased_write_i8(&mut self, writer: &mut dyn io::Write, value: i8) -> Result<(), io::Error>;\n    fn erased_write_i16(&mut self, writer: &mut dyn io::Write, value: i16)\n        -> Result<(), io::Error>;\n    fn erased_write_i32(&mut self, writer: &mut dyn io::Write, value: i32)\n        -> Result<(), io::Error>;\n    fn erased_write_i64(&mut self, writer: &mut dyn io::Write, value: i64)\n        -> Result<(), io::Error>;\n    fn erased_write_u8(&mut self, writer: &mut dyn io::Write, value: u8) -> Result<(), io::Error>;\n    fn erased_write_u16(&mut self, writer: &mut dyn io::Write, value: u16)\n        -> Result<(), io::Error>;\n    fn erased_write_u32(&mut self, writer: &mut dyn io::Write, value: u32)\n        -> Result<(), io::Error>;\n    fn erased_write_u64(&mut self, writer: &mut dyn io::Write, value: u64)\n        -> Result<(), io::Error>;\n    fn erased_write_f32(&mut self, writer: &mut dyn io::Write, value: f32)\n        -> Result<(), io::Error>;\n    fn erased_write_f64(&mut self, writer: &mut dyn io::Write, value: f64)\n        -> Result<(), io::Error>;\n    fn erased_begin_string(&mut self, writer: &mut dyn io::Write) -> Result<(), io::Error>;\n    fn erased_end_string(&mut self, writer: &mut dyn io::Write) -> Result<(), io::Error>;\n    fn erased_write_string_fragment(\n        &mut self,\n        writer: &mut dyn io::Write,\n        fragment: &str,\n    ) -> Result<(), io::Error>;\n    fn erased_write_char_escape(\n        &mut self,\n        writer: &mut dyn io::Write,\n        char_escape: CharEscape,\n    ) -> Result<(), io::Error>;\n    fn erased_begin_array(&mut self, writer: &mut dyn io::Write) -> Result<(), io::Error>;\n    fn erased_end_array(&mut self, writer: &mut dyn io::Write) -> Result<(), io::Error>;\n    fn erased_begin_array_value(\n        &mut self,\n        writer: &mut dyn io::Write,\n        first: bool,\n    ) -> Result<(), io::Error>;\n    fn erased_end_array_value(&mut self, writer: &mut dyn io::Write) -> Result<(), io::Error>;\n    fn erased_begin_object(&mut self, writer: &mut dyn io::Write) -> Result<(), io::Error>;\n    fn erased_end_object(&mut self, writer: &mut dyn io::Write) -> Result<(), io::Error>;\n    fn erased_begin_object_key(\n        &mut self,\n        writer: &mut dyn io::Write,\n        first: bool,\n    ) -> Result<(), io::Error>;\n    fn erased_end_object_key(&mut self, writer: &mut dyn io::Write) -> Result<(), io::Error>;\n    fn erased_begin_object_value(&mut self, writer: &mut dyn io::Write) -> Result<(), io::Error>;\n    fn erased_end_object_value(&mut self, writer: &mut dyn io::Write) -> Result<(), io::Error>;\n}\n\nimpl<T> Formatter for T\nwhere\n    T: serde_json::ser::Formatter,\n{\n    fn erased_write_null(&mut self, w: &mut dyn io::Write) -> Result<(), io::Error> {\n        self.write_null(w)\n    }\n    fn erased_write_bool(&mut self, w: &mut dyn io::Write, v: bool) -> Result<(), io::Error> {\n        self.write_bool(w, v)\n    }\n    fn erased_write_i8(&mut self, w: &mut dyn io::Write, v: i8) -> Result<(), io::Error> {\n        self.write_i8(w, v)\n    }\n    fn erased_write_i16(&mut self, w: &mut dyn io::Write, v: i16) -> Result<(), io::Error> {\n        self.write_i16(w, v)\n    }\n    fn erased_write_i32(&mut self, w: &mut dyn io::Write, v: i32) -> Result<(), io::Error> {\n        self.write_i32(w, v)\n    }\n    fn erased_write_i64(&mut self, w: &mut dyn io::Write, v: i64) -> Result<(), io::Error> {\n        self.write_i64(w, v)\n    }\n    fn erased_write_u8(&mut self, w: &mut dyn io::Write, v: u8) -> Result<(), io::Error> {\n        self.write_u8(w, v)\n    }\n    fn erased_write_u16(&mut self, w: &mut dyn io::Write, v: u16) -> Result<(), io::Error> {\n        self.write_u16(w, v)\n    }\n    fn erased_write_u32(&mut self, w: &mut dyn io::Write, v: u32) -> Result<(), io::Error> {\n        self.write_u32(w, v)\n    }\n    fn erased_write_u64(&mut self, w: &mut dyn io::Write, v: u64) -> Result<(), io::Error> {\n        self.write_u64(w, v)\n    }\n    fn erased_write_f32(&mut self, w: &mut dyn io::Write, v: f32) -> Result<(), io::Error> {\n        self.write_f32(w, v)\n    }\n    fn erased_write_f64(&mut self, w: &mut dyn io::Write, v: f64) -> Result<(), io::Error> {\n        self.write_f64(w, v)\n    }\n    fn erased_begin_string(&mut self, w: &mut dyn io::Write) -> Result<(), io::Error> {\n        self.begin_string(w)\n    }\n    fn erased_end_string(&mut self, w: &mut dyn io::Write) -> Result<(), io::Error> {\n        self.end_string(w)\n    }\n    fn erased_write_string_fragment(\n        &mut self,\n        w: &mut dyn io::Write,\n        fragment: &str,\n    ) -> Result<(), io::Error> {\n        self.write_string_fragment(w, fragment)\n    }\n    fn erased_write_char_escape(\n        &mut self,\n        w: &mut dyn io::Write,\n        char_escape: CharEscape,\n    ) -> Result<(), io::Error> {\n        self.write_char_escape(w, char_escape)\n    }\n    fn erased_begin_array(&mut self, w: &mut dyn io::Write) -> Result<(), io::Error> {\n        self.begin_array(w)\n    }\n    fn erased_end_array(&mut self, w: &mut dyn io::Write) -> Result<(), io::Error> {\n        self.end_array(w)\n    }\n    fn erased_begin_array_value(\n        &mut self,\n        w: &mut dyn io::Write,\n        first: bool,\n    ) -> Result<(), io::Error> {\n        self.begin_array_value(w, first)\n    }\n    fn erased_end_array_value(&mut self, w: &mut dyn io::Write) -> Result<(), io::Error> {\n        self.end_array_value(w)\n    }\n    fn erased_begin_object(&mut self, w: &mut dyn io::Write) -> Result<(), io::Error> {\n        self.begin_object(w)\n    }\n    fn erased_end_object(&mut self, w: &mut dyn io::Write) -> Result<(), io::Error> {\n        self.end_object(w)\n    }\n    fn erased_begin_object_key(\n        &mut self,\n        w: &mut dyn io::Write,\n        first: bool,\n    ) -> Result<(), io::Error> {\n        self.begin_object_key(w, first)\n    }\n    fn erased_end_object_key(&mut self, w: &mut dyn io::Write) -> Result<(), io::Error> {\n        self.end_object_key(w)\n    }\n    fn erased_begin_object_value(&mut self, w: &mut dyn io::Write) -> Result<(), io::Error> {\n        self.begin_object_value(w)\n    }\n    fn erased_end_object_value(&mut self, w: &mut dyn io::Write) -> Result<(), io::Error> {\n        self.end_object_value(w)\n    }\n}\n\nmacro_rules! impl_formatter_for_trait_object {\n    ($ty:ty) => {\n        impl<'a> serde_json::ser::Formatter for $ty {\n            fn write_null<W: ?Sized + io::Write>(\n                &mut self,\n                mut w: &mut W,\n            ) -> Result<(), io::Error> {\n                self.erased_write_null(&mut w)\n            }\n            fn write_bool<W: ?Sized + io::Write>(\n                &mut self,\n                mut w: &mut W,\n                v: bool,\n            ) -> Result<(), io::Error> {\n                self.erased_write_bool(&mut w, v)\n            }\n            fn write_i8<W: ?Sized + io::Write>(\n                &mut self,\n                mut w: &mut W,\n                v: i8,\n            ) -> Result<(), io::Error> {\n                self.erased_write_i8(&mut w, v)\n            }\n            fn write_i16<W: ?Sized + io::Write>(\n                &mut self,\n                mut w: &mut W,\n                v: i16,\n            ) -> Result<(), io::Error> {\n                self.erased_write_i16(&mut w, v)\n            }\n            fn write_i32<W: ?Sized + io::Write>(\n                &mut self,\n                mut w: &mut W,\n                v: i32,\n            ) -> Result<(), io::Error> {\n                self.erased_write_i32(&mut w, v)\n            }\n            fn write_i64<W: ?Sized + io::Write>(\n                &mut self,\n                mut w: &mut W,\n                v: i64,\n            ) -> Result<(), io::Error> {\n                self.erased_write_i64(&mut w, v)\n            }\n            fn write_u8<W: ?Sized + io::Write>(\n                &mut self,\n                mut w: &mut W,\n                v: u8,\n            ) -> Result<(), io::Error> {\n                self.erased_write_u8(&mut w, v)\n            }\n            fn write_u16<W: ?Sized + io::Write>(\n                &mut self,\n                mut w: &mut W,\n                v: u16,\n            ) -> Result<(), io::Error> {\n                self.erased_write_u16(&mut w, v)\n            }\n            fn write_u32<W: ?Sized + io::Write>(\n                &mut self,\n                mut w: &mut W,\n                v: u32,\n            ) -> Result<(), io::Error> {\n                self.erased_write_u32(&mut w, v)\n            }\n            fn write_u64<W: ?Sized + io::Write>(\n                &mut self,\n                mut w: &mut W,\n                v: u64,\n            ) -> Result<(), io::Error> {\n                self.erased_write_u64(&mut w, v)\n            }\n            fn write_f32<W: ?Sized + io::Write>(\n                &mut self,\n                mut w: &mut W,\n                v: f32,\n            ) -> Result<(), io::Error> {\n                self.erased_write_f32(&mut w, v)\n            }\n            fn write_f64<W: ?Sized + io::Write>(\n                &mut self,\n                mut w: &mut W,\n                v: f64,\n            ) -> Result<(), io::Error> {\n                self.erased_write_f64(&mut w, v)\n            }\n            fn begin_string<W: ?Sized + io::Write>(\n                &mut self,\n                mut w: &mut W,\n            ) -> Result<(), io::Error> {\n                self.erased_begin_string(&mut w)\n            }\n            fn end_string<W: ?Sized + io::Write>(\n                &mut self,\n                mut w: &mut W,\n            ) -> Result<(), io::Error> {\n                self.erased_end_string(&mut w)\n            }\n            fn write_string_fragment<W: ?Sized + io::Write>(\n                &mut self,\n                mut w: &mut W,\n                fragment: &str,\n            ) -> Result<(), io::Error> {\n                self.erased_write_string_fragment(&mut w, fragment)\n            }\n            fn write_char_escape<W: ?Sized + io::Write>(\n                &mut self,\n                mut w: &mut W,\n                char_escape: CharEscape,\n            ) -> Result<(), io::Error> {\n                self.erased_write_char_escape(&mut w, char_escape)\n            }\n            fn begin_array<W: ?Sized + io::Write>(\n                &mut self,\n                mut w: &mut W,\n            ) -> Result<(), io::Error> {\n                self.erased_begin_array(&mut w)\n            }\n            fn end_array<W: ?Sized + io::Write>(&mut self, mut w: &mut W) -> Result<(), io::Error> {\n                self.erased_end_array(&mut w)\n            }\n            fn begin_array_value<W: ?Sized + io::Write>(\n                &mut self,\n                mut w: &mut W,\n                first: bool,\n            ) -> Result<(), io::Error> {\n                self.erased_begin_array_value(&mut w, first)\n            }\n            fn end_array_value<W: ?Sized + io::Write>(\n                &mut self,\n                mut w: &mut W,\n            ) -> Result<(), io::Error> {\n                self.erased_end_array_value(&mut w)\n            }\n            fn begin_object<W: ?Sized + io::Write>(\n                &mut self,\n                mut w: &mut W,\n            ) -> Result<(), io::Error> {\n                self.erased_begin_object(&mut w)\n            }\n            fn end_object<W: ?Sized + io::Write>(\n                &mut self,\n                mut w: &mut W,\n            ) -> Result<(), io::Error> {\n                self.erased_end_object(&mut w)\n            }\n            fn begin_object_key<W: ?Sized + io::Write>(\n                &mut self,\n                mut w: &mut W,\n                first: bool,\n            ) -> Result<(), io::Error> {\n                self.erased_begin_object_key(&mut w, first)\n            }\n            fn end_object_key<W: ?Sized + io::Write>(\n                &mut self,\n                mut w: &mut W,\n            ) -> Result<(), io::Error> {\n                self.erased_end_object_key(&mut w)\n            }\n            fn begin_object_value<W: ?Sized + io::Write>(\n                &mut self,\n                mut w: &mut W,\n            ) -> Result<(), io::Error> {\n                self.erased_begin_object_value(&mut w)\n            }\n            fn end_object_value<W: ?Sized + io::Write>(\n                &mut self,\n                mut w: &mut W,\n            ) -> Result<(), io::Error> {\n                self.erased_end_object_value(&mut w)\n            }\n        }\n    };\n}\n\nimpl_formatter_for_trait_object!(dyn Formatter);\nimpl_formatter_for_trait_object!(&'a mut dyn Formatter);\nimpl_formatter_for_trait_object!(&'a mut (dyn Formatter + Send));\nimpl_formatter_for_trait_object!(&'a mut (dyn Formatter + Sync));\nimpl_formatter_for_trait_object!(&'a mut (dyn Formatter + Send + Sync));\n"
  },
  {
    "path": "src/commands.rs",
    "content": "use clap::ArgMatches;\nuse protobuf::descriptor::FileDescriptorSet;\nuse serde_json::ser::Serializer;\n\nuse std::io::{self, Write};\nuse std::path::PathBuf;\n\nuse crate::decode::PqDecoder;\nuse crate::discovery::{compile_descriptors_from_proto, get_loaded_descriptors};\nuse crate::formatter::CustomFormatter;\n\nuse stream_delimit::byte_consumer::ByteConsumer;\nuse stream_delimit::converter::Converter;\nuse stream_delimit::stream::*;\n\npub struct CommandRunner {\n    descriptors: Vec<FileDescriptorSet>,\n    prettyjson: bool,\n}\n\n#[cfg(feature = \"default\")]\nuse stream_delimit::kafka_consumer::KafkaConsumer;\n\nimpl CommandRunner {\n    pub fn new(\n        additional_fdset_dirs: Vec<PathBuf>,\n        mut additional_fdset_files: Vec<PathBuf>,\n        additional_proto_file: Option<&str>,\n        prettyjson: bool,\n    ) -> Self {\n        if let Some(x) = additional_proto_file {\n            let compiled_descriptor_path = compile_descriptors_from_proto(x);\n            additional_fdset_files.push(compiled_descriptor_path);\n        }\n\n        let descriptors = get_loaded_descriptors(additional_fdset_dirs, additional_fdset_files);\n\n        CommandRunner {\n            descriptors,\n            prettyjson,\n        }\n    }\n\n    #[cfg(feature = \"default\")]\n    pub fn run_kafka(self, matches: &ArgMatches<'_>) {\n        if let (Some(brokers), Some(topic)) =\n            (matches.value_of(\"BROKERS\"), matches.value_of(\"TOPIC\"))\n        {\n            let consumer = match KafkaConsumer::new(brokers, topic, matches.is_present(\"FROMBEG\")) {\n                Ok(x) => x,\n                Err(e) => panic!(\"Couldn't initialize kafka consumer: {}\", e),\n            };\n            decode_or_convert(consumer, matches, self.descriptors, self.prettyjson).unwrap();\n        } else {\n            panic!(\"Kafka needs broker[s] and topic\");\n        }\n    }\n\n    #[cfg(not(feature = \"default\"))]\n    pub fn run_kafka(self, _: &ArgMatches) {\n        unimplemented!(\"This version of pq has been compiled without kafka support\");\n    }\n\n    pub fn run_byte(self, matches: &ArgMatches<'_>) {\n        if unsafe { libc::isatty(0) != 0 } {\n            panic!(\"pq expects input to be piped from stdin\");\n        }\n        let stream_type = str_to_streamtype(matches.value_of(\"STREAM\").unwrap_or(\"single\"))\n            .expect(\"Couldn't convert str to streamtype\");\n        decode_or_convert(\n            ByteConsumer::new(io::stdin(), stream_type),\n            matches,\n            self.descriptors,\n            self.prettyjson,\n        )\n        .unwrap()\n    }\n}\n\nfn decode_or_convert<T: Iterator<Item = Vec<u8>> + FramedRead>(\n    mut consumer: T,\n    matches: &ArgMatches<'_>,\n    descriptors: Vec<FileDescriptorSet>,\n    prettyjson: bool,\n) -> io::Result<()> {\n    let count = value_t!(matches, \"COUNT\", i32).unwrap_or(-1);\n\n    let stdout = io::stdout();\n\n    let use_pretty_json = if prettyjson {\n        prettyjson\n    } else {\n        unsafe { libc::isatty(1) != 0 }\n    };\n    if let Some(convert_type) = matches.value_of(\"CONVERT\") {\n        let converter = Converter::new(\n            &mut consumer,\n            str_to_streamtype(convert_type).expect(\"Couldn't convert str to streamtype\"),\n        );\n        let stdout_ = &mut stdout.lock();\n        for (ctr, item) in converter.enumerate() {\n            if count >= 0 && ctr >= count as usize {\n                break;\n            }\n            stdout_.write_all(&item).expect(\"Couldn't write to stdout\");\n        }\n        Ok(())\n    } else {\n        let msgtype = format!(\n            \".{}\",\n            matches\n                .value_of(\"MSGTYPE\")\n                .expect(\"Must supply --msgtype or --convert\")\n        );\n\n        let decoder = PqDecoder::new(descriptors, &msgtype);\n        let mut formatter = CustomFormatter::new(use_pretty_json);\n        let stdout_ = stdout.lock();\n        let mut serializer = Serializer::with_formatter(stdout_, &mut formatter);\n        let mut buffer = Vec::new();\n        let mut ctr = 0;\n        while let Some(item) = consumer.read_next_frame(&mut buffer)? {\n            if count >= 0 && ctr >= count {\n                break;\n            }\n            ctr += 1;\n            decoder.transcode_message(item, &mut serializer);\n        }\n        Ok(())\n    }\n}\n"
  },
  {
    "path": "src/decode.rs",
    "content": "use protobuf::descriptor::FileDescriptorSet;\nuse protobuf::CodedInputStream;\nuse serde::Serializer;\n\nuse serde_protobuf::de::Deserializer;\nuse serde_protobuf::descriptor::Descriptors;\n\npub struct PqDecoder<'a> {\n    pub descriptors: Descriptors,\n    pub message_type: &'a str,\n}\n\nimpl<'a> PqDecoder<'a> {\n    pub fn new(loaded_descs: Vec<FileDescriptorSet>, message_type: &str) -> PqDecoder<'_> {\n        let mut descriptors = Descriptors::new();\n        for fdset in loaded_descs {\n            descriptors.add_file_set_proto(&fdset);\n        }\n        descriptors.resolve_refs();\n        PqDecoder {\n            descriptors,\n            message_type,\n        }\n    }\n\n    pub fn transcode_message<S: Serializer>(&self, data: &[u8], out: S) {\n        let stream = CodedInputStream::from_bytes(data);\n        let mut deserializer =\n            Deserializer::for_named_message(&self.descriptors, self.message_type, stream)\n                .expect(\"could not init deserializer\");\n\n        serde_transcode::transcode(&mut deserializer, out).unwrap();\n    }\n}\n"
  },
  {
    "path": "src/discovery.rs",
    "content": "use protobuf::descriptor::FileDescriptorSet;\nuse protobuf::parse_from_reader;\nuse std::{\n    env,\n    fs::{read_dir, File},\n    path::{Path, PathBuf},\n    process::Command,\n};\n\npub fn get_loaded_descriptors(\n    additional_fdset_dirs: Vec<PathBuf>,\n    mut additional_fdset_files: Vec<PathBuf>,\n) -> Vec<FileDescriptorSet> {\n    let (mut fdsets, mut tested_things) = discover_fdsets(additional_fdset_dirs);\n    fdsets.append(&mut additional_fdset_files);\n    tested_things.append(\n        &mut additional_fdset_files\n            .iter()\n            .map(|x| format!(\"File: {:?}\", x))\n            .collect::<Vec<_>>(),\n    );\n\n    let mut descriptors: Vec<FileDescriptorSet> = Vec::new();\n\n    for fdset_path in fdsets {\n        let mut fdset_file = match File::open(fdset_path.as_path()) {\n            Ok(x) => x,\n            Err(e) => panic!(\"Couldn't open fdset file: {}\", e),\n        };\n        match parse_from_reader(&mut fdset_file) {\n            Err(_) => continue,\n            Ok(x) => descriptors.push(x),\n        }\n    }\n\n    if descriptors.is_empty() {\n        panic!(\"No valid fdset files found. Checked: {:#?}\", tested_things);\n    }\n    descriptors\n}\n\nfn discover_fdsets(additional_fdset_dirs: Vec<PathBuf>) -> (Vec<PathBuf>, Vec<String>) {\n    let mut tested_things = Vec::new();\n    let mut fdset_files = Vec::new();\n\n    if let Ok(x) = env::var(\"FDSET_PATH\") {\n        tested_things.push(format!(\"Directory: {:?}\", x));\n        let p = PathBuf::from(x);\n        fdset_files.append(&mut get_fdset_files_from_path(&p));\n    }\n\n    if let Some(mut x) = dirs::home_dir() {\n        x.push(\".pq\");\n        tested_things.push(format!(\"Directory: {:?}\", x));\n        fdset_files.append(&mut get_fdset_files_from_path(&x));\n    }\n\n    for x in additional_fdset_dirs {\n        tested_things.push(format!(\"Directory: {:?}\", x));\n        fdset_files.append(&mut get_fdset_files_from_path(&x));\n    }\n\n    let x = PathBuf::from(\"/etc/pq\");\n    tested_things.push(format!(\"Directory: {:?}\", x));\n    fdset_files.append(&mut get_fdset_files_from_path(&x));\n\n    (fdset_files, tested_things)\n}\n\npub fn compile_descriptors_from_proto(proto_file: &str) -> PathBuf {\n    let fdset_path = env::temp_dir().join(\"tmp-pq.fdset\");\n\n    let mut cmd = Command::new(protoc());\n    cmd.arg(\"--include_imports\")\n        .arg(\"--include_source_info\")\n        .arg(\"-o\")\n        .arg(&fdset_path)\n        .arg(proto_file);\n\n    cmd.arg(\"-I\").arg(protoc_include());\n\n    let output = cmd.output().expect(\"failed to execute protoc\");\n    if !output.status.success() {\n        panic!(\"protoc failed: {}\", String::from_utf8_lossy(&output.stderr));\n    }\n\n    fdset_path\n}\n\nfn get_fdset_files_from_path(path: &Path) -> Vec<PathBuf> {\n    let mut ret = vec![];\n    if let Ok(paths) = read_dir(path) {\n        for p in paths {\n            let path = p.expect(\"error iterating through paths\").path();\n            if !path.is_dir() {\n                ret.push(path);\n            }\n        }\n    }\n    ret\n}\n\nfn protoc() -> PathBuf {\n    match env::var_os(\"PROTOC\") {\n        Some(protoc) => PathBuf::from(protoc),\n        None => PathBuf::from(default_env!(\"PROTOC\", \"protoc\")),\n    }\n}\n\nfn protoc_include() -> PathBuf {\n    match env::var_os(\"PROTOC_INCLUDE\") {\n        Some(include) => PathBuf::from(include),\n        None => PathBuf::from(default_env!(\"PROTOC_INCLUDE\", \"\")),\n    }\n}\n"
  },
  {
    "path": "src/formatter.rs",
    "content": "use erased_serde_json::Formatter as ErasedFormatter;\nuse serde_json::ser::{CompactFormatter, Formatter, PrettyFormatter};\nuse std::boxed::Box;\nuse std::io::{self, Write};\n\npub struct CustomFormatter {\n    formatter: Box<dyn ErasedFormatter>,\n    depth: usize,\n}\n\nimpl CustomFormatter {\n    pub fn new(use_pretty_json: bool) -> Self {\n        let f: Box<dyn ErasedFormatter> = if use_pretty_json {\n            Box::<PrettyFormatter<'_>>::default()\n        } else {\n            Box::new(CompactFormatter)\n        };\n        CustomFormatter {\n            formatter: f,\n            depth: 0,\n        }\n    }\n}\n\nimpl<'a> Formatter for &'a mut CustomFormatter {\n    fn begin_array<W: ?Sized + Write>(&mut self, w: &mut W) -> io::Result<()> {\n        self.formatter.begin_array(w)\n    }\n    fn end_array<W: ?Sized + Write>(&mut self, w: &mut W) -> io::Result<()> {\n        self.formatter.end_array(w)\n    }\n    fn begin_array_value<W: ?Sized + Write>(&mut self, w: &mut W, first: bool) -> io::Result<()> {\n        self.formatter.begin_array_value(w, first)\n    }\n    fn end_array_value<W: ?Sized + Write>(&mut self, w: &mut W) -> io::Result<()> {\n        self.formatter.end_array_value(w)\n    }\n    fn begin_object<W: ?Sized + Write>(&mut self, w: &mut W) -> io::Result<()> {\n        self.depth += 1;\n        self.formatter.begin_object(w)\n    }\n    fn end_object<W: ?Sized + Write>(&mut self, w: &mut W) -> io::Result<()> {\n        self.formatter.end_object(w).and_then(|()| {\n            self.depth -= 1;\n            if self.depth == 0 {\n                w.write_all(b\"\\n\")\n            } else {\n                Ok(())\n            }\n        })\n    }\n    fn begin_object_key<W: ?Sized + Write>(&mut self, w: &mut W, first: bool) -> io::Result<()> {\n        self.formatter.begin_object_key(w, first)\n    }\n    fn begin_object_value<W: ?Sized + Write>(&mut self, w: &mut W) -> io::Result<()> {\n        self.formatter.begin_object_value(w)\n    }\n    fn end_object_value<W: ?Sized + Write>(&mut self, w: &mut W) -> io::Result<()> {\n        self.formatter.end_object_value(w)\n    }\n}\n"
  },
  {
    "path": "src/main.rs",
    "content": "#![crate_type = \"bin\"]\n\n#[macro_use]\nextern crate clap;\n\n#[macro_use]\nextern crate default_env;\n\nmod commands;\nmod decode;\nmod discovery;\nmod formatter;\n\nuse crate::commands::*;\n\nfn main() {\n    let matches = clap_app!(\n        @app (app_from_crate!())\n        (@arg MSGTYPE: --msgtype +takes_value +global conflicts_with[CONVERT]\n            \"Sets protobuf message type\")\n        (@arg STREAM: --stream +takes_value \"Enables stream + sets stream type\")\n        (@arg COUNT: --count +takes_value +global \"Stop after count messages\")\n        (@arg CONVERT: --convert +takes_value +global \"Convert to different stream type\")\n        (@arg EXTRA_FDSET_DIRS: --fdsetdir +takes_value +global +multiple\n             \"[repeatable] Specify dirs to load fdset files from\")\n        (@arg EXTRA_FDSET_FILES: --fdsetfile +takes_value +global +multiple\n             \"[repeatable] Specify an fdset file\")\n        (@arg EXTRA_PROTO_FILE: --protofile +takes_value +global\n             \"Specify a proto file\")\n        (@arg PRETTY_JSON: --prettyjson +global\n            \"Force pretty json formatter. Default is pretty for a tty, otherwise compact\")\n        (@subcommand kafka =>\n            (@arg TOPIC: +required \"Sets the kafka topic\")\n            (@arg BROKERS: +required --brokers +takes_value \"Comma-separated kafka brokers\")\n            (@arg FROMBEG: --beginning \"Consume topic from beginning\")\n        )\n    )\n    .get_matches();\n\n    let extra_fdset_dirs = match matches.values_of(\"EXTRA_FDSET_DIRS\") {\n        Some(dirs) => dirs.map(std::path::PathBuf::from).collect::<Vec<_>>(),\n        None => vec![],\n    };\n\n    let extra_fdset_files = match matches.values_of(\"EXTRA_FDSET_FILES\") {\n        Some(files) => files.map(std::path::PathBuf::from).collect::<Vec<_>>(),\n        None => vec![],\n    };\n\n    let extra_proto_file = matches.value_of(\"EXTRA_PROTO_FILE\");\n    let prettyjson = matches.is_present(\"PRETTY_JSON\");\n\n    let cmd = CommandRunner::new(\n        extra_fdset_dirs,\n        extra_fdset_files,\n        extra_proto_file,\n        prettyjson,\n    );\n\n    match matches.subcommand() {\n        (\"kafka\", Some(m)) => cmd.run_kafka(m),\n        _ => cmd.run_byte(&matches),\n    }\n}\n"
  },
  {
    "path": "stream-delimit/Cargo.toml",
    "content": "[package]\nname = \"stream_delimit\"\nversion = \"0.5.7\"\nauthors = [\"Sevag Hanssian <sevag.hanssian@gmail.com>\"]\ndescription = \"length delimited protobuf stream separator\"\nrepository = \"https://github.com/sevagh/pq/tree/master/stream_delimit\"\ndocumentation = \"http://docs.rs/stream_delimit/\"\nreadme = \"README.md\"\nlicense = \"MIT\"\nkeywords = [\"protobuf\", \"serde\"]\nedition = \"2018\"\n\n[dependencies]\nkafka = { version = \"0.8\", optional = true }\nbyteorder = \"1.3\"\n\n[features]\ndefault = []\nwith_kafka = [\"kafka\"]\n"
  },
  {
    "path": "stream-delimit/LICENSE",
    "content": "MIT License\n\nCopyright (c) 2017 Sevag Hanssian\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "stream-delimit/README.md",
    "content": "# stream_delimit [![Crates.io](https://img.shields.io/crates/v/stream_delimit.svg)](https://crates.io/crates/stream_delimit) [![Crates.io](https://img.shields.io/crates/d/stream_delimit.svg)](https://github.com/sevagh/pq/tree/master/stream-delimit)\n\nA helper crate for pq.\n\n\n### Varints\n\nhttps://developers.google.com/protocol-buffers/docs/encoding#varints\n"
  },
  {
    "path": "stream-delimit/src/byte_consumer.rs",
    "content": "#![deny(missing_docs)]\n\nuse crate::stream::*;\nuse crate::{error::StreamDelimitError, varint::decode_varint};\nuse byteorder::{BigEndian, ReadBytesExt};\nuse std::{\n    io::{self, Read},\n    num::NonZeroUsize,\n};\n\n/// A consumer for a byte stream\npub struct ByteConsumer<T: Read> {\n    read: T,\n    type_: StreamType,\n}\n\nimpl<T: Read> ByteConsumer<T> {\n    /// Return a ByteConsumer from for single messages, varint or leb128-delimited\n    pub fn new(read: T, type_: StreamType) -> ByteConsumer<T> {\n        ByteConsumer { read, type_ }\n    }\n\n    fn read_next_frame_length(&mut self) -> io::Result<Option<NonZeroUsize>> {\n        let r = match self.type_ {\n            StreamType::Leb128 | StreamType::Varint => decode_varint(&mut self.read)\n                .map_err(|e| {\n                    // For unified error handling we force everything into io::Error\n                    match e {\n                        StreamDelimitError::VarintDecodeError(i) => i,\n                        e => io::Error::new(io::ErrorKind::InvalidData, format!(\"{}\", e)),\n                    }\n                })\n                .map(|v| NonZeroUsize::new(v as usize)),\n            StreamType::I32BE => self\n                .read\n                .read_i32::<BigEndian>()\n                .map(|v| NonZeroUsize::new(v as usize)),\n            StreamType::Single => Ok(None),\n        };\n\n        // In the cases where we have hit the end of the stream, read_i32 will return UnexpectedEof\n        // we treat this as no more data\n        match r {\n            Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => Ok(None),\n            a => a,\n        }\n    }\n}\n\nimpl<T: Read> Iterator for ByteConsumer<T> {\n    type Item = Vec<u8>;\n\n    fn next(&mut self) -> Option<Self::Item> {\n        let mut buffer = Vec::new();\n        self.read_next_frame(&mut buffer).ok()??;\n        Some(buffer)\n    }\n}\n\nimpl<T: Read> FramedRead for ByteConsumer<T> {\n    fn read_next_frame<'a>(&mut self, buffer: &'a mut Vec<u8>) -> io::Result<Option<&'a [u8]>> {\n        let r = match self.read_next_frame_length()? {\n            Some(length) => {\n                buffer.clear();\n                let mut take = (&mut self.read).take(length.get() as u64);\n                take.read_to_end(buffer)?;\n                Some(&buffer[..])\n            }\n            // the single stream type does not have a defined length, so read_next_frame_length will return None\n            // and we catch that special case here\n            None if self.type_ == StreamType::Single => {\n                buffer.clear();\n                if self.read.read_to_end(buffer)? > 0 {\n                    Some(&buffer[..])\n                } else {\n                    None\n                }\n            }\n            _ => None,\n        };\n        Ok(r)\n    }\n}\n"
  },
  {
    "path": "stream-delimit/src/converter.rs",
    "content": "#![deny(missing_docs)]\n\nuse crate::stream::*;\nuse crate::varint::encode_varint;\n\n/// A Converter struct to convert from a stream iterator to another `StreamType`\n/// Useful for example to dump Kafka messages to a varint-delimited text file\npub struct Converter<'a> {\n    stream_src: &'a mut dyn Iterator<Item = Vec<u8>>,\n    stream_dest: StreamType,\n}\n\nimpl<'a> Converter<'a> {\n    /// Return a converter from a stream iterator\n    pub fn new<T: Iterator<Item = Vec<u8>>>(\n        stream_src: &'a mut T,\n        stream_dest: StreamType,\n    ) -> Converter<'a> {\n        Converter {\n            stream_src,\n            stream_dest,\n        }\n    }\n}\n\nimpl<'a> Iterator for Converter<'a> {\n    type Item = Vec<u8>;\n\n    fn next(&mut self) -> Option<Vec<u8>> {\n        match self.stream_dest {\n            StreamType::Varint | StreamType::Leb128 => match self.stream_src.next() {\n                Some(ref mut x) => {\n                    let mut lead_varint = encode_varint(x.len() as u64);\n                    lead_varint.append(x);\n                    Some(lead_varint)\n                }\n                None => None,\n            },\n            _ => unimplemented!(),\n        }\n    }\n}\n"
  },
  {
    "path": "stream-delimit/src/error.rs",
    "content": "use std::error::Error;\nuse std::fmt;\nuse std::io;\nuse std::result;\n\npub type Result<T> = result::Result<T, StreamDelimitError>;\n\n#[derive(Debug)]\npub enum StreamDelimitError {\n    #[cfg(feature = \"with_kafka\")]\n    KafkaInitializeError(::kafka::error::Error),\n    VarintDecodeError(io::Error),\n    InvalidStreamTypeError(String),\n    VarintDecodeMaxBytesError,\n}\n\nimpl fmt::Display for StreamDelimitError {\n    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n        match *self {\n            #[cfg(feature = \"with_kafka\")]\n            StreamDelimitError::KafkaInitializeError(ref e) => {\n                write!(f, \"Couldn't initialize kafka consumer: {}\", e)\n            }\n            StreamDelimitError::VarintDecodeError(ref e) => {\n                write!(f, \"Couldn't decode leading varint: {}\", e)\n            }\n            StreamDelimitError::InvalidStreamTypeError(ref t) => write!(\n                f,\n                \"Invalid stream type: {} (only support single,leb128,varint)\",\n                t\n            ),\n            StreamDelimitError::VarintDecodeMaxBytesError => {\n                write!(f, \"Exceeded max attempts to decode leading varint\")\n            }\n        }\n    }\n}\n\nimpl Error for StreamDelimitError {\n    fn description(&self) -> &str {\n        match *self {\n            #[cfg(feature = \"with_kafka\")]\n            StreamDelimitError::KafkaInitializeError(_) => \"couldn't initialize kafka consumer\",\n            StreamDelimitError::VarintDecodeError(_)\n            | StreamDelimitError::VarintDecodeMaxBytesError => \"couldn't decode leading varint\",\n            StreamDelimitError::InvalidStreamTypeError(_) => \"invalid stream type\",\n        }\n    }\n\n    fn cause(&self) -> Option<&dyn Error> {\n        match *self {\n            #[cfg(feature = \"with_kafka\")]\n            StreamDelimitError::KafkaInitializeError(ref e) => Some(e),\n            StreamDelimitError::VarintDecodeError(ref e) => Some(e),\n            StreamDelimitError::InvalidStreamTypeError(_)\n            | StreamDelimitError::VarintDecodeMaxBytesError => None,\n        }\n    }\n}\n"
  },
  {
    "path": "stream-delimit/src/kafka_consumer.rs",
    "content": "#![deny(missing_docs)]\n\nuse crate::error::*;\nuse crate::stream::FramedRead;\nuse kafka::consumer::{Consumer, FetchOffset};\nuse std::collections::VecDeque;\n\n/// A consumer from Kafka\npub struct KafkaConsumer {\n    consumer: Consumer,\n    messages: VecDeque<Vec<u8>>,\n}\n\nimpl FramedRead for KafkaConsumer {\n    fn read_next_frame<'a>(\n        &mut self,\n        buffer: &'a mut Vec<u8>,\n    ) -> std::io::Result<Option<&'a [u8]>> {\n        let res = self.next().map(move |mut v| {\n            std::mem::swap(&mut v, buffer);\n            &buffer[..]\n        });\n        Ok(res)\n    }\n}\n\nimpl Iterator for KafkaConsumer {\n    type Item = Vec<u8>;\n\n    fn next(&mut self) -> Option<Vec<u8>> {\n        if self.messages.is_empty() {\n            let kafka_consumer = &mut self.consumer;\n            loop {\n                match kafka_consumer.poll() {\n                    Ok(mss) => {\n                        for ms in mss.iter() {\n                            self.messages.append(\n                                &mut ms\n                                    .messages()\n                                    .iter()\n                                    .map(|z| z.value.to_vec())\n                                    .collect::<VecDeque<_>>(),\n                            );\n                            kafka_consumer\n                                .consume_messageset(ms)\n                                .expect(\"Couldn't mark messageset as consumed\");\n                        }\n                        kafka_consumer\n                            .commit_consumed()\n                            .expect(\"Couldn't commit consumption\");\n                        if !self.messages.is_empty() {\n                            break;\n                        }\n                    }\n                    Err(e) => {\n                        eprintln!(\"{}\", e);\n                        return None;\n                    }\n                }\n            }\n        }\n        self.messages.pop_front()\n    }\n}\n\nimpl KafkaConsumer {\n    /// Return a KafkaConsumer with some basic kafka connection properties\n    pub fn new(brokers: &str, topic: &str, from_beginning: bool) -> Result<KafkaConsumer> {\n        let fetch_offset = if from_beginning {\n            FetchOffset::Earliest\n        } else {\n            FetchOffset::Latest\n        };\n        match Consumer::from_hosts(\n            brokers\n                .split(',')\n                .map(std::borrow::ToOwned::to_owned)\n                .collect::<Vec<String>>(),\n        )\n        .with_topic(topic.to_owned())\n        .with_fallback_offset(fetch_offset)\n        .with_fetch_max_bytes_per_partition(1024 * 1024)\n        .create()\n        {\n            Ok(consumer) => Ok(KafkaConsumer {\n                consumer,\n                messages: VecDeque::new(),\n            }),\n            Err(e) => Err(StreamDelimitError::KafkaInitializeError(e)),\n        }\n    }\n}\n"
  },
  {
    "path": "stream-delimit/src/lib.rs",
    "content": "extern crate byteorder;\n#[cfg(feature = \"with_kafka\")]\nextern crate kafka;\n\nmod varint;\n\npub mod error;\n\n/// Utilities to consume from a byte stream\npub mod byte_consumer;\n\n/// Utilities to convert between stream types\npub mod converter;\n\n/// Define stream types\npub mod stream;\n\n#[cfg(feature = \"with_kafka\")]\n/// Utilities to consume from Kafka\npub mod kafka_consumer;\n"
  },
  {
    "path": "stream-delimit/src/stream.rs",
    "content": "#![deny(missing_docs)]\n\nuse std::io;\n\nuse crate::error::*;\n\n/// An enum type for byte streams\n#[derive(PartialEq, Eq)]\npub enum StreamType {\n    /// Protobuf messages with leading length encoded in leb128\n    Leb128,\n    /// Protobuf messages with leading length encoded in varint\n    Varint,\n    /// Protobuf messages with leading length encoded as\n    /// binary big endian 32-bit signed integer\n    I32BE,\n    /// Single protobuf messages with no separators/delimiters\n    Single,\n}\n\n/// Convert &str to associated `StreamType`\npub fn str_to_streamtype(input: &str) -> Result<StreamType> {\n    match input {\n        \"single\" => Ok(StreamType::Single),\n        \"varint\" => Ok(StreamType::Varint),\n        \"leb128\" => Ok(StreamType::Leb128),\n        \"i32be\" => Ok(StreamType::I32BE),\n        _ => Err(StreamDelimitError::InvalidStreamTypeError(\n            input.to_string(),\n        )),\n    }\n}\n\n/// A trait for a stream that can be read in clearly defined chunks\npub trait FramedRead {\n    /// should read the next available frame into the provided buffer.\n    /// clear() will be called before the buffer is filled\n    fn read_next_frame<'a>(&mut self, buffer: &'a mut Vec<u8>) -> io::Result<Option<&'a [u8]>>;\n}\n"
  },
  {
    "path": "stream-delimit/src/varint.rs",
    "content": "#![deny(missing_docs)]\n\nuse crate::error::*;\nuse std::io::Read;\n\nconst VARINT_MAX_BYTES: usize = 10;\n\npub fn decode_varint(read: &mut dyn Read) -> Result<u64> {\n    let mut varint_buf: Vec<u8> = Vec::new();\n    for i in 0..VARINT_MAX_BYTES {\n        varint_buf.push(0u8);\n        match read.read_exact(&mut varint_buf[i..]) {\n            Ok(_) => (),\n            Err(e) => return Err(StreamDelimitError::VarintDecodeError(e)),\n        }\n        if (varint_buf[i] & 0x80) == 0 {\n            let mut concat: u64 = 0;\n            for (j, &byte) in varint_buf[..=i].iter().enumerate() {\n                concat |= u64::from(byte & 0x7f) << (j * 7);\n            }\n            return Ok(concat);\n        }\n    }\n    Err(StreamDelimitError::VarintDecodeMaxBytesError)\n}\n\npub fn encode_varint(mut value: u64) -> Vec<u8> {\n    let mut ret = vec![0u8; VARINT_MAX_BYTES];\n    let mut n = 0;\n    while value > 127 {\n        ret[n] = 0x80 | (value & 0x7F) as u8;\n        value >>= 7;\n        n += 1\n    }\n    ret[n] = value as u8;\n    n += 1;\n    ret[0..n].to_vec()\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n    use std::io::Cursor;\n\n    #[test]\n    fn test_simple() {\n        assert_eq!(\n            1,\n            decode_varint(&mut Cursor::new(encode_varint(1))).unwrap()\n        );\n    }\n\n    #[test]\n    fn test_two_byte_varint() {\n        assert_eq!(\n            300,\n            decode_varint(&mut Cursor::new(encode_varint(300))).unwrap()\n        );\n    }\n\n    #[test]\n    fn test_decode_known_varint_bytes() {\n        let cases: &[(u64, &[u8])] = &[\n            (0, &[0x00]),\n            (1, &[0x01]),\n            (127, &[0x7f]),\n            (128, &[0x80, 0x01]),\n            (300, &[0xac, 0x02]),\n            (16384, &[0x80, 0x80, 0x01]),\n            (2097152, &[0x80, 0x80, 0x80, 0x01]),\n            (u32::MAX as u64, &[0xff, 0xff, 0xff, 0xff, 0x0f]),\n            (\n                u64::MAX,\n                &[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01],\n            ),\n        ];\n\n        for &(expected, bytes) in cases {\n            assert_eq!(expected, decode_varint(&mut Cursor::new(bytes)).unwrap());\n        }\n    }\n\n    #[test]\n    fn test_three_byte_varint() {\n        // 16384 requires 3 bytes: 0x80 0x80 0x01\n        // This would fail with the old buggy shift formula\n        assert_eq!(\n            16384,\n            decode_varint(&mut Cursor::new(encode_varint(16384))).unwrap()\n        );\n        assert_eq!(\n            100000,\n            decode_varint(&mut Cursor::new(encode_varint(100000))).unwrap()\n        );\n    }\n\n    #[test]\n    fn test_four_byte_varint() {\n        // 2097152 requires 4 bytes\n        assert_eq!(\n            2097152,\n            decode_varint(&mut Cursor::new(encode_varint(2097152))).unwrap()\n        );\n        assert_eq!(\n            10000000,\n            decode_varint(&mut Cursor::new(encode_varint(10000000))).unwrap()\n        );\n    }\n\n    #[test]\n    fn test_large_varints() {\n        assert_eq!(\n            u32::MAX as u64,\n            decode_varint(&mut Cursor::new(encode_varint(u32::MAX as u64))).unwrap()\n        );\n        assert_eq!(\n            u64::MAX,\n            decode_varint(&mut Cursor::new(encode_varint(u64::MAX))).unwrap()\n        );\n    }\n}\n"
  },
  {
    "path": "tests/README.md",
    "content": "Samples and fdset files compiled from the tools in the https://github.com/sevagh/protobuf-test-utils repo.\n"
  },
  {
    "path": "tests/fdsets/cat.fdset",
    "content": "\n<\n\tcat.proto\u0012\u000fcom.example.cat\"\u001e\n\u0003Cat\u0012\u0017\n\u0007is_lazy\u0018\u0001 \u0002(\bR\u0006isLazy"
  },
  {
    "path": "tests/fdsets/dog.fdset",
    "content": "\nm\n\tdog.proto\u0012\u000fcom.example.dog\"O\n\u0003Dog\u0012\u0014\n\u0005breed\u0018\u0001 \u0002(\tR\u0005breed\u0012\u0010\n\u0003age\u0018\u0002 \u0002(\u0005R\u0003age\u0012 \n\u000btemperament\u0018\u0003 \u0002(\tR\u000btemperament"
  },
  {
    "path": "tests/fdsets/person.fdset",
    "content": "\nP\n\fperson.proto\u0012\u0012com.example.person\",\n\u0006Person\u0012\u0012\n\u0004name\u0018\u0001 \u0002(\tR\u0004name\u0012\u000e\n\u0002id\u0018\u0002 \u0002(\u0005R\u0002id"
  },
  {
    "path": "tests/fdsets-invalid/.gitignore",
    "content": "*\n!.gitignore\n"
  },
  {
    "path": "tests/protos/dog.proto",
    "content": "package com.example.dog;\n\nmessage Dog {\n  required string breed = 1;\n  required int32 age = 2;\n  optional string temperament = 3;\n}\n"
  },
  {
    "path": "tests/samples/bad",
    "content": "thisisnotprotobuf"
  },
  {
    "path": "tests/samples/dog",
    "content": "\n\u0003gsd\u0010\u0003\u001a\u0007excited"
  },
  {
    "path": "tests/samples/dog_stream",
    "content": "\u0015\n\nrottweiler\u0010\u0002\u001a\u0005chill"
  },
  {
    "path": "tests/test_pqrs_bin.rs",
    "content": "use assert_cli;\n\nuse std::env;\n\nfn get_test_dir(final_piece: &str) -> String {\n    let mut cwd = env::current_dir().unwrap();\n    cwd.push(\"tests\");\n    cwd.push(final_piece);\n    String::from(cwd.to_str().unwrap())\n}\n\n#[test]\nfn test_dog_decode() {\n    assert_cli::Assert::main_binary()\n        .with_env(assert_cli::Environment::inherit().insert(\"FDSET_PATH\", get_test_dir(\"fdsets\")))\n        .with_args(&[\"--msgtype=com.example.dog.Dog\"])\n        .stdin(include_str!(\"samples/dog\"))\n        .succeeds()\n        .and()\n        .stdout()\n        .contains(\"{\\\"breed\\\":\\\"gsd\\\",\\\"age\\\":3,\\\"temperament\\\":\\\"excited\\\"}\")\n        .unwrap();\n}\n\n#[test]\nfn test_dog_decode_stream() {\n    assert_cli::Assert::main_binary()\n        .with_env(assert_cli::Environment::inherit().insert(\"FDSET_PATH\", get_test_dir(\"fdsets\")))\n        .with_args(&[\"--msgtype=com.example.dog.Dog\", \"--stream=varint\"])\n        .stdin(include_str!(\"samples/dog_stream\"))\n        .succeeds()\n        .and()\n        .stdout()\n        .contains(\"{\\\"breed\\\":\\\"rottweiler\\\",\\\"age\\\":2,\\\"temperament\\\":\\\"chill\\\"}\")\n        .unwrap();\n}\n\n#[test]\nfn test_dog_decode_i32be_stream() {\n    assert_cli::Assert::main_binary()\n        .with_env(assert_cli::Environment::inherit().insert(\"FDSET_PATH\", get_test_dir(\"fdsets\")))\n        .with_args(&[\"--msgtype=com.example.dog.Dog\", \"--stream=i32be\"])\n        .stdin(include_str!(\"samples/dog_i32be_stream\"))\n        .succeeds()\n        .and()\n        .stdout()\n        .contains(\"{\\\"breed\\\":\\\"gsd\\\",\\\"age\\\":3,\\\"temperament\\\":\\\"excited\\\"}\")\n        .unwrap();\n}\n\n#[test]\nfn test_nonexistent_fdset_dir() {\n    assert_cli::Assert::main_binary()\n        .with_env(\n            assert_cli::Environment::inherit()\n                .insert(\"FDSET_PATH\", get_test_dir(\"fdsets-doesnt-exist\")),\n        )\n        .with_args(&[\"--msgtype=com.example.dog.Dog\"])\n        .stdin(include_str!(\"samples/dog\"))\n        .fails()\n        .and()\n        .stderr()\n        .contains(\"No valid fdset files found. Checked:\")\n        .unwrap();\n}\n\n#[test]\nfn test_no_fdset_files() {\n    assert_cli::Assert::main_binary()\n        .with_env(\n            assert_cli::Environment::inherit().insert(\"FDSET_PATH\", get_test_dir(\"fdsets-invalid\")),\n        )\n        .with_args(&[\"--msgtype=com.example.dog.Dog\"])\n        .stdin(include_str!(\"samples/dog\"))\n        .fails()\n        .and()\n        .stderr()\n        .contains(\"No valid fdset files found. Checked:\")\n        .unwrap();\n}\n\n#[test]\nfn test_person_decode() {\n    assert_cli::Assert::main_binary()\n        .with_env(assert_cli::Environment::inherit().insert(\"FDSET_PATH\", get_test_dir(\"fdsets\")))\n        .with_args(&[\"--msgtype=com.example.person.Person\"])\n        .stdin(include_str!(\"samples/person\"))\n        .succeeds()\n        .and()\n        .stdout()\n        .contains(\"{\\\"name\\\":\\\"khosrov\\\",\\\"id\\\":0}\")\n        .unwrap();\n}\n\n#[test]\nfn test_bad_input() {\n    assert_cli::Assert::main_binary()\n        .with_env(assert_cli::Environment::inherit().insert(\"FDSET_PATH\", get_test_dir(\"fdsets\")))\n        .with_args(&[\"--msgtype=com.example.dog.Dog\"])\n        .stdin(include_str!(\"samples/bad\"))\n        .fails()\n        .and()\n        .stderr()\n        .contains(\"protobuf error\")\n        .unwrap();\n}\n\n#[test]\nfn test_person_decode_with_command_line_fdset_dir() {\n    assert_cli::Assert::main_binary()\n        .with_args(&[\n            \"--msgtype=com.example.person.Person\",\n            &format!(\"--fdsetdir={0}\", get_test_dir(\"fdsets\")),\n        ])\n        .stdin(include_str!(\"samples/person\"))\n        .succeeds()\n        .and()\n        .stdout()\n        .contains(\"{\\\"name\\\":\\\"khosrov\\\",\\\"id\\\":0}\")\n        .unwrap();\n}\n\n#[test]\nfn test_person_decode_with_command_line_fdset_file() {\n    assert_cli::Assert::main_binary()\n        .with_args(&[\n            \"--msgtype=com.example.person.Person\",\n            &format!(\"--fdsetfile={0}\", get_test_dir(\"fdsets/person.fdset\")),\n        ])\n        .stdin(include_str!(\"samples/person\"))\n        .succeeds()\n        .and()\n        .stdout()\n        .contains(\"{\\\"name\\\":\\\"khosrov\\\",\\\"id\\\":0}\")\n        .unwrap();\n}\n\n#[test]\nfn test_no_args() {\n    assert_cli::Assert::main_binary()\n        .fails()\n        .and()\n        .stderr()\n        .contains(\"No valid fdset files found\")\n        .unwrap();\n}\n\n#[test]\nfn test_cat_noncanonical_decode() {\n    assert_cli::Assert::main_binary()\n        .with_args(&[\n            \"--msgtype=com.example.cat.Cat\",\n            &format!(\"--fdsetfile={0}\", get_test_dir(\"fdsets/cat.fdset\")),\n        ])\n        .stdin(include_str!(\"samples/cat\"))\n        .succeeds()\n        .and()\n        .stdout()\n        .contains(\"{\\\"is_lazy\\\":false}\")\n        .unwrap();\n}\n\n#[test]\n#[ignore]\nfn test_cat_canonical_decode() {\n    assert_cli::Assert::main_binary()\n        .with_args(&[\n            \"--msgtype=com.example.cat.Cat\",\n            &format!(\"--fdsetfile={0}\", get_test_dir(\"fdsets/cat.fdset\")),\n        ])\n        .stdin(include_str!(\"samples/cat\"))\n        .succeeds()\n        .and()\n        .stdout()\n        .contains(\"{\\\"isLazy\\\":false}\")\n        .unwrap();\n}\n\n#[test]\nfn test_dog_decode_from_proto() {\n    assert_cli::Assert::main_binary()\n        .with_env(\n            assert_cli::Environment::inherit().insert(\"PROTOC_INCLUDE\", get_test_dir(\"protos\")),\n        )\n        .with_args(&[\n            \"--msgtype=com.example.dog.Dog\",\n            &format!(\"--protofile={0}\", get_test_dir(\"protos/dog.proto\")),\n        ])\n        .stdin(include_str!(\"samples/dog\"))\n        .succeeds()\n        .and()\n        .stdout()\n        .contains(\"{\\\"breed\\\":\\\"gsd\\\",\\\"age\\\":3,\\\"temperament\\\":\\\"excited\\\"}\")\n        .unwrap();\n}\n"
  },
  {
    "path": "utils/.gitignore",
    "content": "*_pb2.py\n*.fdset\n__pycache__\n*.pyc\n"
  },
  {
    "path": "utils/GNUmakefile",
    "content": "PROTOS := $(wildcard *.proto)\nFDSETS := $(patsubst %.proto,%.fdset,$(PROTOS))\n\nall: $(FDSETS)\n\npy:\n\t@protoc --python_out . ./*.proto -I./\n\n%.fdset: %.proto\n\t@protoc -o ./$@ ./$^ -I./\n\n.PHONY: clean\n\nclean:\n\t-rm -rf ./*.fdset ./*_pb2.py ./*_pb3.py __pycache__\n"
  },
  {
    "path": "utils/README.txt",
    "content": "Protobuf sample files and generators for pq testing.\n"
  },
  {
    "path": "utils/cat.proto",
    "content": "package com.example.cat;\n\nmessage Cat {\n  required bool is_lazy = 1;\n}\n"
  },
  {
    "path": "utils/dog.proto",
    "content": "package com.example.dog;\n\nmessage Dog {\n  required string breed = 1;\n  required int32 age = 2;\n  optional string temperament = 3;\n}\n"
  },
  {
    "path": "utils/person.proto",
    "content": "package com.example.person;\n\nmessage Person {\n  required string name = 1;\n  required int32 id = 2;\n}\n"
  },
  {
    "path": "utils/proto_encoder.py",
    "content": "#!/usr/bin/env python3\n\nimport dog_pb2\nimport person_pb2\nimport cat_pb2\nimport sys\nimport random\nfrom google.protobuf.internal import encoder\nfrom optparse import OptionParser\n\n\ndef single(msgtype, stream=False):\n    if msgtype == \"cat\":\n        obj = cat_pb2.Cat(is_lazy=bool(random.getrandbits(1)))\n    elif msgtype == \"dog\":\n        obj = dog_pb2.Dog(\n            age=random.choice(range(0, 20)),\n            breed=[\"rottweiler\", \"gsd\", \"poodle\"][random.choice(range(0, 3))],\n            temperament=[\"chill\", \"aggressive\", \"excited\"][random.choice(range(0, 3))],\n        )\n    elif msgtype == \"person\":\n        obj = person_pb2.Person(\n            id=random.choice(range(0, 4)),\n            name=[\"raffi\", \"khosrov\", \"vahaken\"][random.choice(range(0, 3))],\n        )\n    else:\n        usage()\n    obj = obj.SerializeToString()\n    varint_ = encoder._VarintBytes(len(obj)) if stream else b\"\"\n    sys.stdout.buffer.write(varint_ + obj)\n\n\ndef stream(msgtype, limit):\n    for _ in range(limit):\n        single(msgtype, stream=True)\n\n\ndef usage():\n    print(\n        \"Usage: {0} <single|stream> <dog|person|cat>\"\n        \" [--count c]\".format(sys.argv[0]),\n        file=sys.stderr,\n    )\n    sys.exit(1)\n\n\nif __name__ == \"__main__\":\n    parser = OptionParser()\n    parser.add_option(\"--count\", dest=\"count\", help=\"stream count\", metavar=\"COUNT\")\n    (options, args) = parser.parse_args(args=sys.argv)\n    if len(args) != 3:\n        usage()\n\n    if args[1] == \"single\":\n        single(args[2])\n    elif args[1] == \"stream\":\n        stream(args[2], int(options.count))\n"
  },
  {
    "path": "utils/requirements.txt",
    "content": "protobuf\n"
  }
]