jql-runner-8.0.9/.cargo_vcs_info.json0000644000000001570000000000100131520ustar { "git": { "sha1": "704b6fc1c49b6888d841c05442ba48b3a5a46428" }, "path_in_vcs": "crates/jql-runner" }jql-runner-8.0.9/Cargo.lock0000644000000370630000000000100111330ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 4 [[package]] name = "aho-corasick" version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" dependencies = [ "memchr", ] [[package]] name = "anes" version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" [[package]] name = "anstyle" version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78" [[package]] name = "autocfg" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" [[package]] name = "bumpalo" version = "3.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43" [[package]] name = "cast" version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" [[package]] name = "cfg-if" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2fd1289c04a9ea8cb22300a459a72a385d7c73d3259e2ed7dcb2af674838cfa9" [[package]] name = "ciborium" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" dependencies = [ "ciborium-io", "ciborium-ll", "serde", ] [[package]] name = "ciborium-io" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" [[package]] name = "ciborium-ll" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" dependencies = [ "ciborium-io", "half", ] [[package]] name = "clap" version = "4.5.48" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2134bb3ea021b78629caa971416385309e0131b351b25e01dc16fb54e1b5fae" dependencies = [ "clap_builder", ] [[package]] name = "clap_builder" version = "4.5.48" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2ba64afa3c0a6df7fa517765e31314e983f51dda798ffba27b988194fb65dc9" dependencies = [ "anstyle", "clap_lex", ] [[package]] name = "clap_lex" version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b94f61472cee1439c0b966b47e3aca9ae07e45d070759512cd390ea2bebc6675" [[package]] name = "criterion" version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e1c047a62b0cc3e145fa84415a3191f628e980b194c2755aa12300a4e6cbd928" dependencies = [ "anes", "cast", "ciborium", "clap", "criterion-plot", "itertools", "num-traits", "oorandom", "plotters", "rayon", "regex", "serde", "serde_json", "tinytemplate", "walkdir", ] [[package]] name = "criterion-plot" version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b1bcc0dc7dfae599d84ad0b1a55f80cde8af3725da8313b528da95ef783e338" dependencies = [ "cast", "itertools", ] [[package]] name = "crossbeam-deque" version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51" dependencies = [ "crossbeam-epoch", "crossbeam-utils", ] [[package]] name = "crossbeam-epoch" version = "0.9.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" dependencies = [ "crossbeam-utils", ] [[package]] name = "crossbeam-utils" version = "0.8.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" [[package]] name = "crunchy" version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" [[package]] name = "either" version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" [[package]] name = "equivalent" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" [[package]] name = "half" version = "2.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e54c115d4f30f52c67202f079c5f9d8b49db4691f460fdb0b4c2e838261b2ba5" dependencies = [ "cfg-if", "crunchy", "zerocopy", ] [[package]] name = "hashbrown" version = "0.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5419bdc4f6a9207fbeba6d11b604d481addf78ecd10c11ad51e76c2f6482748d" [[package]] name = "indexmap" version = "2.11.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4b0f83760fb341a774ed326568e19f5a863af4a952def8c39f9ab92fd95b88e5" dependencies = [ "equivalent", "hashbrown", "rayon", ] [[package]] name = "itertools" version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" dependencies = [ "either", ] [[package]] name = "itoa" version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" [[package]] name = "jql-parser" version = "8.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "524d4365f9892e5dba4dbe643ed91a27da4083ee77c97f965520624d8f582ba4" dependencies = [ "thiserror", "winnow", ] [[package]] name = "jql-runner" version = "8.0.9" dependencies = [ "criterion", "indexmap", "jql-parser", "rayon", "serde_json", "thiserror", ] [[package]] name = "js-sys" version = "0.3.81" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec48937a97411dcb524a265206ccd4c90bb711fca92b2792c407f268825b9305" dependencies = [ "once_cell", "wasm-bindgen", ] [[package]] name = "log" version = "0.4.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34080505efa8e45a4b816c349525ebe327ceaa8559756f0356cba97ef3bf7432" [[package]] name = "memchr" version = "2.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273" [[package]] name = "num-traits" version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", ] [[package]] name = "once_cell" version = "1.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" [[package]] name = "oorandom" version = "11.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" [[package]] name = "plotters" version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5aeb6f403d7a4911efb1e33402027fc44f29b5bf6def3effcc22d7bb75f2b747" dependencies = [ "num-traits", "plotters-backend", "plotters-svg", "wasm-bindgen", "web-sys", ] [[package]] name = "plotters-backend" version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df42e13c12958a16b3f7f4386b9ab1f3e7933914ecea48da7139435263a4172a" [[package]] name = "plotters-svg" version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "51bae2ac328883f7acdfea3d66a7c35751187f870bc81f94563733a154d7a670" dependencies = [ "plotters-backend", ] [[package]] name = "proc-macro2" version = "1.0.101" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "89ae43fd86e4158d6db51ad8e2b80f313af9cc74f5c0e03ccb87de09998732de" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.41" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce25767e7b499d1b604768e7cde645d14cc8584231ea6b295e9c9eb22c02e1d1" dependencies = [ "proc-macro2", ] [[package]] name = "rayon" version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "368f01d005bf8fd9b1206fb6fa653e6c4a81ceb1466406b81792d87c5677a58f" dependencies = [ "either", "rayon-core", ] [[package]] name = "rayon-core" version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" dependencies = [ "crossbeam-deque", "crossbeam-utils", ] [[package]] name = "regex" version = "1.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b5288124840bee7b386bc413c487869b360b2b4ec421ea56425128692f2a82c" dependencies = [ "aho-corasick", "memchr", "regex-automata", "regex-syntax", ] [[package]] name = "regex-automata" version = "0.4.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "833eb9ce86d40ef33cb1306d8accf7bc8ec2bfea4355cbdebb3df68b40925cad" dependencies = [ "aho-corasick", "memchr", "regex-syntax", ] [[package]] name = "regex-syntax" version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "caf4aa5b0f434c91fe5c7f1ecb6a5ece2130b02ad2a590589dda5146df959001" [[package]] name = "rustversion" version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" [[package]] name = "ryu" version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" [[package]] name = "same-file" version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" dependencies = [ "winapi-util", ] [[package]] name = "serde" version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" dependencies = [ "serde_core", "serde_derive", ] [[package]] name = "serde_core" version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_json" version = "1.0.145" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "402a6f66d8c709116cf22f558eab210f5a50187f702eb4d7e5ef38d9a7f1c79c" dependencies = [ "indexmap", "itoa", "memchr", "ryu", "serde", "serde_core", ] [[package]] name = "syn" version = "2.0.106" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ede7c438028d4436d71104916910f5bb611972c5cfd7f89b8300a8186e6fada6" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "thiserror" version = "2.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f63587ca0f12b72a0600bcba1d40081f830876000bb46dd2337a3051618f4fc8" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" version = "2.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ff15c8ecd7de3849db632e14d18d2571fa09dfc5ed93479bc4485c7a517c913" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "tinytemplate" version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc" dependencies = [ "serde", "serde_json", ] [[package]] name = "unicode-ident" version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f63a545481291138910575129486daeaf8ac54aee4387fe7906919f7830c7d9d" [[package]] name = "walkdir" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" dependencies = [ "same-file", "winapi-util", ] [[package]] name = "wasm-bindgen" version = "0.2.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1da10c01ae9f1ae40cbfac0bac3b1e724b320abfcf52229f80b547c0d250e2d" dependencies = [ "cfg-if", "once_cell", "rustversion", "wasm-bindgen-macro", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-backend" version = "0.2.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "671c9a5a66f49d8a47345ab942e2cb93c7d1d0339065d4f8139c486121b43b19" dependencies = [ "bumpalo", "log", "proc-macro2", "quote", "syn", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-macro" version = "0.2.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7ca60477e4c59f5f2986c50191cd972e3a50d8a95603bc9434501cf156a9a119" dependencies = [ "quote", "wasm-bindgen-macro-support", ] [[package]] name = "wasm-bindgen-macro-support" version = "0.2.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f07d2f20d4da7b26400c9f4a0511e6e0345b040694e8a75bd41d578fa4421d7" dependencies = [ "proc-macro2", "quote", "syn", "wasm-bindgen-backend", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" version = "0.2.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bad67dc8b2a1a6e5448428adec4c3e84c43e561d8c9ee8a9e5aabeb193ec41d1" dependencies = [ "unicode-ident", ] [[package]] name = "web-sys" version = "0.3.81" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9367c417a924a74cae129e6a2ae3b47fabb1f8995595ab474029da749a8be120" dependencies = [ "js-sys", "wasm-bindgen", ] [[package]] name = "winapi-util" version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ "windows-sys", ] [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" [[package]] name = "windows-sys" version = "0.61.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" dependencies = [ "windows-link", ] [[package]] name = "winnow" version = "0.7.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "21a0236b59786fed61e2a80582dd500fe61f18b5dca67a4a067d0bc9039339cf" dependencies = [ "memchr", ] [[package]] name = "zerocopy" version = "0.8.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0894878a5fa3edfd6da3f88c4805f4c8558e2b996227a3d864f47fe11e38282c" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" version = "0.8.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "88d2b8d9c68ad2b9e4340d7832716a4d21a22a1154777ad56ea55c51a9cf3831" dependencies = [ "proc-macro2", "quote", "syn", ] jql-runner-8.0.9/Cargo.toml0000644000000030140000000000100111430ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2024" name = "jql-runner" version = "8.0.9" authors = ["Davy Duperron "] build = false autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "Runner for jql - the JSON Query Language tool." readme = "README.md" keywords = [ "cli", "json", "terminal", "tool", "query", ] categories = [ "command-line-utilities", "filesystem", ] license = "MIT OR Apache-2.0" repository = "https://github.com/yamafaktory/jql" resolver = "2" [lib] name = "jql_runner" path = "src/lib.rs" [[test]] name = "integration" path = "tests/integration.rs" [[bench]] name = "benchmark" path = "benches/benchmark.rs" harness = false [dependencies.indexmap] version = "2.11.4" features = ["rayon"] [dependencies.jql-parser] version = "8.0.9" [dependencies.rayon] version = "1.11.0" [dependencies.serde_json] version = "1.0.145" features = [ "preserve_order", "unbounded_depth", ] [dependencies.thiserror] version = "2.0.17" [dev-dependencies.criterion] version = "0.7.0" jql-runner-8.0.9/Cargo.toml.orig000064400000000000000000000012051046102023000146240ustar 00000000000000[package] authors.workspace = true categories.workspace = true description = "Runner for jql - the JSON Query Language tool." edition.workspace = true keywords.workspace = true license.workspace = true name = "jql-runner" readme.workspace = true repository.workspace = true version.workspace = true [dependencies] indexmap = { version = "2.11.4", features = ["rayon"] } jql-parser = { path = "../jql-parser", version = "8.0.9" } rayon = "1.11.0" serde_json.workspace = true thiserror.workspace = true [dev-dependencies] criterion = "0.7.0" [lib] path = "src/lib.rs" [[bench]] harness = false name = "benchmark" path = "benches/benchmark.rs" jql-runner-8.0.9/LICENSE-APACHE000064400000000000000000000260721046102023000136720ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2023 Davy Duperron Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. jql-runner-8.0.9/LICENSE-MIT000064400000000000000000000020351046102023000133730ustar 00000000000000Copyright 2023 Davy Duperron Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. jql-runner-8.0.9/README.md000064400000000000000000000005001046102023000132110ustar 00000000000000# jql-runner ## About This crate is a workspace dependency of the [jql](https://github.com/yamafaktory/jql) tool. ## Features - Raw runner (string slice as input) - Token runner (tokens as input) - Errors ## License For licensing information, please check the [workspace root](https://github.com/yamafaktory/jql). jql-runner-8.0.9/benches/benchmark.rs000064400000000000000000000033311046102023000156460ustar 00000000000000use criterion::{ Criterion, criterion_group, criterion_main, }; use jql_runner::runner::raw; use serde_json::json; fn array_range_selector(c: &mut Criterion) { c.bench_function("Array range selector", move |b| { b.iter(|| raw("[2,0]", &json!([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))) }); } fn flatten_operator(c: &mut Criterion) { c.bench_function("Flatten operator", move |b| { b.iter(|| raw("..", &json!([[[[[[[0]]], 1, [[[[2]]]], 3]]]]))) }); } fn group_separator(c: &mut Criterion) { c.bench_function("Group separator", move |b| { b.iter(|| raw(r#""a","b","c""#, &json!({ "a": 1, "b": 2, "c": 3 }))) }); } fn key_selector(c: &mut Criterion) { c.bench_function("Key selector", move |b| { b.iter(|| { raw( r#""props""a""b""c""#, &json!({ "props": { "a": { "b": { "c": 1} } } }), ) }) }); } fn pipe_operators(c: &mut Criterion) { c.bench_function("Pipe operators", move |b| { b.iter(|| { raw( r#""nested"|>"laptop""brand"<|[1]"#, &json!({ "nested": [ { "laptop": { "brand": "Apple" } }, { "laptop": { "brand": "Asus" } } ] }), ) }) }); } criterion_group!( benches, array_range_selector, flatten_operator, group_separator, key_selector, pipe_operators, ); criterion_main!(benches); jql-runner-8.0.9/src/array.rs000064400000000000000000000312631046102023000142170ustar 00000000000000use std::num::NonZeroUsize; use jql_parser::tokens::{ Index, Lens, LensValue, Range, Token, }; use rayon::prelude::*; use serde_json::{ Value, json, }; use crate::{ errors::JqlRunnerError, runner::group_runner, }; /// Takes a mutable reference of JSON `Value` and returns a reference of a /// mutable vector of JSON `Value` or an error. fn as_array_mut(json: &mut Value) -> Result<&mut Vec, JqlRunnerError> { if json.is_array() { // We can safely unwrap here since this is an array. Ok(json.as_array_mut().unwrap()) } else { Err(JqlRunnerError::InvalidArrayError(json.clone())) } } /// Takes an `Index` and a JSON `Value`. /// Returns a reference of a JSON `Value` or an error. fn get_array_index(index: Index, json: &Value) -> Result { let num: usize = index.into(); if let Some(value) = json.get(num) { Ok(value.clone()) } else { Err(JqlRunnerError::IndexOutOfBoundsError { index: num, parent: json.clone(), }) } } /// Takes a slice of `Index` and a reference of a JSON `Value`. /// Returns a reference of a JSON `Value` or an error. pub(crate) fn get_array_indexes(indexes: &[Index], json: &Value) -> Result { if indexes.len() == 1 { return get_array_index(indexes[0], json); } let values: Vec = indexes .iter() .try_fold(vec![], |mut acc: Vec, index| { acc.push(get_array_index(*index, json)?); Ok::, JqlRunnerError>(acc) })?; Ok(json!(values)) } /// Takes a reference of a `Range` and a mutable reference of a JSON `Value`. /// Returns a JSON `Value` or an error. pub(crate) fn get_array_range(range: &Range, json: &mut Value) -> Result { let array = as_array_mut(json)?; if array.is_empty() { return Ok(json!([])); } let len = array.len(); // Array's length can't be zero so we can safely unwrap here. let non_zero_len = NonZeroUsize::new(len).unwrap(); let (start, end) = range.to_boundaries(non_zero_len); // Out of bounds. if start + 1 > len || end + 1 > len { return Err(JqlRunnerError::RangeOutOfBoundsError { start, end, parent: json.clone(), }); } let is_natural_order = start < end; let result = if is_natural_order { &mut array[start..=end] } else { &mut array[end..=start] }; if !is_natural_order { result.reverse(); } Ok(json!(result)) } /// Takes a reference of a JSON `Value`. /// Returns a flattened array as a JSON `Value` or an error. /// Note: the runner checks that the input is a JSON array. pub(crate) fn get_flattened_array(json: &Value) -> Result { let result = json .as_array() .unwrap() .par_iter() .try_fold_with(Vec::new(), |mut acc: Vec, inner_value| { if inner_value.is_array() { let mut flattened = get_flattened_array(inner_value)?; let result = as_array_mut(&mut flattened)?; acc.append(result); } else { acc.push(inner_value.clone()); } Ok::, JqlRunnerError>(acc) }) .try_reduce(Vec::new, |mut a, b| { a.extend(b); Ok(a) })?; Ok(json!(result)) } /// Takes a slice of `Lens` and a mutable reference of a JSON `Value`. /// Returns a JSON `Value` or an error. pub(crate) fn get_array_lenses(lenses: &[Lens], json: &mut Value) -> Result { let array = as_array_mut(json)?; if array.is_empty() { return Ok(json!([])); } let result = array .par_iter() .try_fold_with(Vec::new(), |mut acc: Vec, inner_value| { if lenses.iter().any(|lens| { let (tokens, value) = lens.get(); let tokens: Vec<&Token> = tokens.iter().collect(); let result = group_runner(&tokens, inner_value); if let Ok(current_value) = result { match value { Some(LensValue::Bool(boolean)) => { current_value.is_boolean() && current_value.as_bool().unwrap() == boolean } Some(LensValue::Null) => current_value.is_null(), Some(LensValue::Number(value)) => { current_value.is_u64() && current_value.as_u64().unwrap() == value as u64 } Some(LensValue::String(value)) => current_value == value, None => true, } } else { false } }) { acc.push(inner_value.clone()); } Ok::, JqlRunnerError>(acc) }) .try_reduce(Vec::new, |mut a, b| { a.extend(b); Ok(a) })?; Ok(json!(result)) } /// Takes a reference of a JSON `Value`. /// Converts the original array as indexes and returns a JSON `Value` or an error. /// Note: the runner checks that the input is a JSON array. pub(crate) fn get_array_as_indexes(json: &Value) -> Result { let result = json .as_array() .unwrap() .par_iter() .enumerate() .try_fold_with(Vec::new(), |mut acc: Vec, (i, _)| { acc.push(i.into()); Ok::, JqlRunnerError>(acc) }) .try_reduce(Vec::new, |mut a, b| { a.extend(b); Ok(a) })?; Ok(json!(result)) } #[cfg(test)] mod tests { use jql_parser::tokens::{ Index, Lens, LensValue, Range, Token, }; use serde_json::json; use super::{ get_array_as_indexes, get_array_index, get_array_indexes, get_array_lenses, get_array_range, get_flattened_array, }; use crate::errors::JqlRunnerError; #[test] fn check_get_array_index() { let value = json!(["a", "b", "c"]); assert_eq!(get_array_index(Index::new(0), &value), Ok(json!("a"))); assert_eq!( get_array_index(Index::new(3), &value), Err(JqlRunnerError::IndexOutOfBoundsError { index: 3, parent: value }) ); } #[test] fn check_get_array_indexes() { let value = json!(["a", "b", "c"]); assert_eq!(get_array_indexes(&[Index::new(0)], &value), Ok(json!("a"))); assert_eq!( get_array_indexes(&[Index::new(0), Index::new(2)], &value), Ok(json!(["a", "c"])) ); assert_eq!( get_array_indexes(&[Index::new(0), Index::new(3)], &value), Err(JqlRunnerError::IndexOutOfBoundsError { index: 3, parent: value }) ); } #[test] fn check_get_array_as_indexes() { let value = json!(["a", "b", "c"]); assert_eq!(get_array_as_indexes(&value), Ok(json!([0, 1, 2]))); } #[test] fn check_get_array_range() { let value = json!(["a", "b", "c", "d", "e"]); assert_eq!( get_array_range( &Range::new(Some(Index::new(0)), Some(Index::new(2))), &mut json!([]) ), Ok(json!([])) ); assert_eq!( get_array_range( &Range::new(Some(Index::new(0)), Some(Index::new(2))), &mut value.clone() ), Ok(json!(["a", "b", "c"])) ); assert_eq!( get_array_range( &Range::new(Some(Index::new(2)), Some(Index::new(0))), &mut value.clone() ), Ok(json!(["c", "b", "a"])) ); assert_eq!( get_array_range( &Range::new(Some(Index::new(0)), Some(Index::new(0))), &mut value.clone() ), Ok(json!(["a"])) ); assert_eq!( get_array_range(&Range::new(None, Some(Index::new(4))), &mut value.clone()), Ok(json!(["a", "b", "c", "d", "e"])) ); assert_eq!( get_array_range(&Range::new(Some(Index::new(4)), None), &mut value.clone()), Ok(json!(["e"])) ); assert_eq!( get_array_range(&Range::new(None, Some(Index::new(5))), &mut value.clone()), Err(JqlRunnerError::RangeOutOfBoundsError { start: 0, end: 5, parent: value }) ); let value = json!(1); assert_eq!( get_array_range(&Range::new(None, Some(Index::new(5))), &mut value.clone()), Err(JqlRunnerError::InvalidArrayError(value)) ); } #[test] fn check_get_flattened_array() { assert_eq!( get_flattened_array(&json!([[[[[[[[[[[[[[1]]]]]]]]]]]]], [[[[[2]]]], 3], null])), Ok(json!([1, 2, 3, null])) ); assert_eq!( get_flattened_array( &json!([[[[[[[[[[[[[[{ "a": 1 }]]]]]]]]]]]]], [[[[[{ "b": 2 }]]]], { "c": 3 }], null]) ), Ok(json!([{ "a": 1 }, { "b": 2 }, { "c": 3 }, null])) ); } #[test] #[allow(clippy::too_many_lines)] fn check_get_array_lenses() { let mut value = json!([ { "a": 1, "b": 2 }, { "a": 2, "b": "some" }, { "a": 2, "b": null }, { "a": 2, "b": true }, ]); assert_eq!( get_array_lenses( &[Lens::new(&[Token::KeySelector("a")], None)], &mut json!([]) ), Ok(json!([])) ); assert_eq!( get_array_lenses( &[Lens::new(&[Token::KeySelector("a")], None)], &mut value.clone() ), Ok(json!([ { "a": 1, "b": 2 }, { "a": 2, "b": "some" }, { "a": 2, "b": null }, { "a": 2, "b": true }, ])) ); assert_eq!( get_array_lenses( &[Lens::new( &[Token::KeySelector("a")], Some(LensValue::Number(1)) )], &mut value.clone() ), Ok(json!([{ "a": 1, "b": 2 }])) ); assert_eq!( get_array_lenses( &[ Lens::new(&[Token::KeySelector("a")], Some(LensValue::Number(1))), Lens::new(&[Token::KeySelector("a")], Some(LensValue::Number(2))), ], &mut value.clone() ), Ok(json!([ { "a": 1, "b": 2 }, { "a": 2, "b": "some" }, { "a": 2, "b": null }, { "a": 2, "b": true }, ])) ); assert_eq!( get_array_lenses( &[ Lens::new(&[Token::KeySelector("a")], Some(LensValue::Number(1))), Lens::new(&[Token::KeySelector("b")], Some(LensValue::Number(2))), ], &mut value.clone() ), Ok(json!([ { "a": 1, "b": 2 }, ])) ); assert_eq!( get_array_lenses( &[ Lens::new(&[Token::KeySelector("a")], Some(LensValue::Number(1))), Lens::new(&[Token::KeySelector("b")], Some(LensValue::String("some"))), ], &mut value.clone() ), Ok(json!([ { "a": 1, "b": 2 }, { "a": 2, "b": "some" }, ])) ); assert_eq!( get_array_lenses( &[ Lens::new(&[Token::KeySelector("a")], Some(LensValue::Number(1))), Lens::new(&[Token::KeySelector("b")], Some(LensValue::Bool(true))), ], &mut value.clone() ), Ok(json!([ { "a": 1, "b": 2 }, { "a": 2, "b": true }, ])) ); assert_eq!( get_array_lenses( &[ Lens::new(&[Token::KeySelector("a")], Some(LensValue::Number(1))), Lens::new(&[Token::KeySelector("b")], Some(LensValue::Null)), ], &mut value ), Ok(json!([ { "a": 1, "b": 2 }, { "a": 2, "b": null }, ])) ); } } jql-runner-8.0.9/src/errors.rs000064400000000000000000000076111046102023000144150ustar 00000000000000use jql_parser::errors::JqlParserError; use serde_json::Value; use thiserror::Error; static SLICE_SEP: &str = " ... "; static SLICE_LEN: usize = 7; static SEP: &str = ", "; /// Joins multiple `String`. fn join(values: &[String]) -> String { values.join(SEP) } /// Shortens a JSON `Value` for error injection. fn shorten(json: &Value) -> String { let full_json_string = json.to_string(); if full_json_string.len() < SLICE_LEN * 2 + SLICE_SEP.len() { return full_json_string; } let start_slice = &full_json_string[..SLICE_LEN]; let end_slice = &full_json_string[full_json_string.len() - SLICE_LEN..]; [start_slice, end_slice].join(SLICE_SEP) } /// Returns the type of a JSON `Value`. fn get_json_type(json: &Value) -> &str { match json { Value::Array(_) => "array", Value::Bool(_) => "boolean", Value::Null => "null", Value::Number(_) => "number", Value::Object(_) => "object", Value::String(_) => "string", } } /// Error type returned by the runner. #[derive(Debug, Error, PartialEq)] pub enum JqlRunnerError { /// Empty query error. #[error("Query is empty")] EmptyQueryError, /// Flatten error. #[error("Value {0} is neither an array nor an object and can't be flattened")] FlattenError(Value), /// Index out of bounds error. #[error("Index {index} in parent {parent} is out of bounds")] IndexOutOfBoundsError { /// Index. index: usize, /// Parent value. parent: Value, }, /// Invalid array error. #[error("Value {} is not a JSON array ({})", .0, get_json_type(.0))] InvalidArrayError(Value), /// Invalid object error. #[error("Value {} is not a JSON object ({})", .0, get_json_type(.0))] InvalidObjectError(Value), /// Key not found error. #[error(r#"Key "{key}" doesn't exist in parent {}"#, shorten(parent))] KeyNotFoundError { /// Key not found. key: String, /// Parent value. parent: Value, }, /// Keys not found error. #[error("Keys {} don't exist in parent {}", join(keys), shorten(parent))] MultiKeyNotFoundError { /// Keys not found. keys: Vec, /// Parent value. parent: Value, }, /// Parsing error. #[error(transparent)] ParsingError(#[from] JqlParserError), /// Pipe in error. #[error("Pipe in operator used on {0} which is not an array")] PipeInError(Value), /// Pipe in error. #[error("Pipe out operator used without a preceding pipe in operator")] PipeOutError, /// Range out of bounds error. #[error("Range [{start}:{end}] in parent {parent} is out of bounds")] RangeOutOfBoundsError { /// Start range. start: usize, /// End range. end: usize, /// parent value. parent: Value, }, /// Unknown error. #[error("Unknown error")] UnknownError, } #[cfg(test)] mod tests { use serde_json::json; use super::{ get_json_type, join, shorten, }; #[test] fn check_get_json_type() { assert_eq!(get_json_type(&json!([])), "array"); assert_eq!(get_json_type(&json!(true)), "boolean"); assert_eq!(get_json_type(&json!(null)), "null"); assert_eq!(get_json_type(&json!(1)), "number"); assert_eq!(get_json_type(&json!({})), "object"); assert_eq!(get_json_type(&json!("a")), "string"); } #[test] fn check_join() { assert_eq!( join(&["a".to_string(), "b".to_string(), "c".to_string()]), "a, b, c".to_string() ); } #[test] fn check_shorten() { assert_eq!(shorten(&json!("thismakesnosense")), r#""thismakesnosense""#); assert_eq!( shorten(&json!({ "a": { "b": { "c": [1, 2 ,3, 4, 5, 6, 7, 8, 9] } } })), r#"{"a":{" ... 8,9]}}}"#.to_string() ); } } jql-runner-8.0.9/src/lib.rs000064400000000000000000000004671046102023000136510ustar 00000000000000#![doc = include_str!("../README.md")] #![doc( html_logo_url = "https://raw.githubusercontent.com/yamafaktory/jql/a438ab0039faf64c3329fb09bae399ae95601000/jql.svg" )] /// Array utilities. mod array; /// Parser errors. pub mod errors; /// Object utilities. mod object; /// Runner utilities. pub mod runner; jql-runner-8.0.9/src/object.rs000064400000000000000000000330631046102023000143470ustar 00000000000000use std::{ num::NonZeroUsize, string::ToString, }; use indexmap::{ IndexMap, IndexSet, }; use jql_parser::tokens::{ Index, Range, }; use rayon::prelude::*; use serde_json::{ Map, Value, json, }; use crate::errors::JqlRunnerError; /// Takes a reference of a JSON `Value` and returns a reference of a JSON `Map` /// or an error. fn as_object_mut(json: &mut Value) -> Result<&mut Map, JqlRunnerError> { if json.is_object() { // We can safely unwrap here since this is an object. Ok(json.as_object_mut().unwrap()) } else { Err(JqlRunnerError::InvalidObjectError(json.clone())) } } /// Takes a key as a string slice and a reference of a JSON `Value`. /// Returns a JSON `Value` or an error. pub(crate) fn get_object_key(key: &str, json: &Value) -> Result { if !json.is_object() { return Err(JqlRunnerError::InvalidObjectError(json.clone())); } json.get(key) .ok_or_else(|| JqlRunnerError::KeyNotFoundError { key: key.to_string(), parent: json.clone(), }) .cloned() } /// Takes a key as a string slice and a reference of a JSON `Value`. /// Returns a JSON `Value` or an error. pub(crate) fn get_object_multi_key( keys: &[&str], json: &mut Value, ) -> Result { let len = keys.len(); let (mut result, found_keys) = as_object_mut(json)? .iter_mut() .par_bridge() .try_fold_with( (IndexMap::with_capacity(len), IndexSet::with_capacity(len)), |mut acc: (IndexMap, IndexSet), (key, value)| { if let Some(index) = keys.iter().position(|s| s == key) { acc.0.insert(index, value.clone()); acc.1.insert(key.to_string()); } Ok::<(IndexMap, IndexSet), JqlRunnerError>(acc) }, ) .try_reduce( || (IndexMap::with_capacity(len), IndexSet::with_capacity(len)), |mut a, b| { a.0.extend(b.0); a.1.extend(b.1); Ok(a) }, )?; let keys_set: IndexSet = keys.iter().map(ToString::to_string).collect(); let mut keys_not_found: Vec = found_keys .symmetric_difference(&keys_set) .map(ToString::to_string) .collect(); if !keys_not_found.is_empty() { keys_not_found.sort(); return Err(JqlRunnerError::MultiKeyNotFoundError { keys: keys_not_found, parent: json.clone(), }); } // Restore the original order. result.par_sort_keys(); let new_map = result .into_iter() .fold(Map::with_capacity(len), |mut acc, (index, value)| { acc.insert(keys[index].to_owned(), value); acc }); Ok(json!(new_map)) } /// Takes a mutable reference of a JSON `Value`. /// Returns a flattened object as a JSON `Value`. pub(crate) fn get_flattened_object(json: &Value) -> Value { let mut flattened = Map::::new(); flatten_value(json, String::new(), 0, &mut flattened); json!(flattened) } /// Internal utility for `flatten_json_object`. fn flatten_value( json: &Value, parent_key: String, depth: usize, flattened: &mut Map, ) { if let Some(value) = json.as_object() { flatten_object(value, &parent_key, depth, flattened); } else { flattened.insert(parent_key, json.clone()); } } /// Internal utility for `flatten_json_object`. fn flatten_object( map: &Map, parent_key: &str, depth: usize, flattened: &mut Map, ) { for (k, v) in map { let parent_key = if depth > 0 { format!("{}{}{}", parent_key, ".", k) } else { k.to_string() }; flatten_value(v, parent_key, depth + 1, flattened); } } /// Takes a slice of `Index` and a mutable reference of a JSON `Value`. /// Returns a reference of a JSON `Value` or an error. pub(crate) fn get_object_indexes( indexes: &[Index], json: &mut Value, ) -> Result { let mut_object = as_object_mut(json)?; if mut_object.is_empty() { return Ok(json!({})); } let len = indexes.len(); // We can safely unwrap since indexes can't be empty. let max: usize = (*indexes.iter().max().unwrap()).into(); if max + 1 > mut_object.len() { return Err(JqlRunnerError::IndexOutOfBoundsError { index: max, parent: json.clone(), }); } let mut result = mut_object .iter_mut() .enumerate() .par_bridge() .try_fold_with( IndexMap::with_capacity(len), |mut acc: IndexMap, (index, (key, value))| { if let Some(index) = indexes.iter().position(|i| { let num: usize = (*i).into(); num == index }) { acc.insert(index, (key.to_string(), value.clone())); } Ok::, JqlRunnerError>(acc) }, ) .try_reduce( || IndexMap::with_capacity(len), |mut a, b| { a.extend(b); Ok(a) }, )?; // Restore the original order. result.par_sort_keys(); let new_map = result .into_iter() .fold(Map::with_capacity(len), |mut acc, (_, (key, value))| { acc.insert(key, value); acc }); Ok(json!(new_map)) } /// Takes a reference of a `Range` and a mutable reference of a JSON `Value`. /// Returns a reference of a JSON `Value` or an error. pub(crate) fn get_object_range(range: &Range, json: &mut Value) -> Result { let mut_object = as_object_mut(json)?; if mut_object.is_empty() { return Ok(json!({})); } let len = mut_object.len(); // Object's length can't be zero so we can safely unwrap here. let non_zero_len = NonZeroUsize::new(len).unwrap(); let (start, end) = range.to_boundaries(non_zero_len); // Out of bounds. if start + 1 > len || end + 1 > len { return Err(JqlRunnerError::RangeOutOfBoundsError { start, end, parent: json.clone(), }); } let is_natural_order = start < end; let mut result = mut_object .iter_mut() .enumerate() .par_bridge() .try_fold_with( IndexMap::with_capacity(len), |mut acc: IndexMap, (index, (key, value))| { if (is_natural_order && index >= start && index <= end) || (!is_natural_order && index >= end && index <= start) { acc.insert(index, (key.to_string(), value.clone())); } Ok::, JqlRunnerError>(acc) }, ) .try_reduce( || IndexMap::with_capacity(len), |mut a, b| { a.extend(b); Ok(a) }, )?; // Restore the original order. result.par_sort_keys(); // Reverse if not in natural order. if !is_natural_order { result.reverse(); } let new_map = result .into_iter() .fold(Map::with_capacity(len), |mut acc, (_, (key, value))| { acc.insert(key, value); acc }); Ok(json!(new_map)) } /// Takes a mutable reference of a JSON `Value`. /// Converts the original object as an array of its keys and returns a JSON `Value` or an error. /// Note: the runner checks that the input is a JSON object. pub(crate) fn get_object_as_keys(json: &mut Value) -> Result { let mut_object = json.as_object_mut().unwrap(); let mut result = mut_object .iter_mut() .par_bridge() .try_fold_with(Vec::new(), |mut acc: Vec, (k, _)| { acc.push(json!(k)); Ok::, JqlRunnerError>(acc) }) .try_reduce(Vec::new, |mut a, b| { a.extend(b); Ok(a) })?; // Restore the original order. // We can safely unwrap here since the key is a string. result.par_sort_by_key(|v| String::from(v.as_str().unwrap())); Ok(json!(result)) } #[cfg(test)] mod tests { use jql_parser::tokens::{ Index, Range, }; use serde_json::{ Value, json, }; use super::{ get_flattened_object, get_object_as_keys, get_object_indexes, get_object_key, get_object_multi_key, get_object_range, }; use crate::errors::JqlRunnerError; /// If we perform a direct comparison between the processed value and /// the expected value from the `json!` macro, we might get a false /// positive since the order of the keys is not checked on equality. fn assert_string_eq(processed: Result, expected: Value) { let processed = processed.unwrap(); let processed = serde_json::to_string(&processed).unwrap(); let expected = serde_json::to_string(&expected).unwrap(); assert_eq!(processed, expected); } #[test] fn check_get_object_key() { let value = json!({ "a": 1 }); assert_eq!(get_object_key("a", &value), Ok(json!(1))); assert_eq!( get_object_key("b", &value), Err(JqlRunnerError::KeyNotFoundError { key: "b".to_string(), parent: value }) ); } #[test] fn check_get_object_multi_key() { let value = json!({ "a": 1, "b": 2, "c": 3, "d": 4, "e": 5 }); assert_eq!( get_object_multi_key(&["a", "b", "c"], &mut value.clone()), Ok(json!({ "a": 1, "b": 2, "c": 3 })) ); assert_string_eq( get_object_multi_key(&["c", "a", "b"], &mut value.clone()), json!({"c": 3, "a": 1, "b": 2}), ); assert_eq!( get_object_multi_key(&["w", "a", "t"], &mut value.clone()), Err(JqlRunnerError::MultiKeyNotFoundError { keys: vec!["t".to_string(), "w".to_string()], parent: value, }) ); let value = json!(1); assert_eq!( get_object_multi_key(&["a", "b", "c"], &mut value.clone()), Err(JqlRunnerError::InvalidObjectError(value)) ); } #[test] fn check_get_flattened_object() { assert_eq!( get_flattened_object( &json!({ "a": { "c": false }, "b": { "d": { "e": { "f": 1, "g": { "h": 2 }} } } }) ), json!({ "a.c": false, "b.d.e.f": 1, "b.d.e.g.h": 2 }) ); } #[test] fn check_get_object_indexes() { let value = json!({ "a": 1, "b": 2, "c": 3, "d": 4, "e": 5 }); assert_string_eq( get_object_indexes( &[Index::new(4), Index::new(2), Index::new(0)], &mut value.clone(), ), json!({ "e": 5, "c": 3, "a": 1 }), ); assert_eq!( get_object_indexes( &[Index::new(4), Index::new(2), Index::new(10)], &mut value.clone() ), Err(JqlRunnerError::IndexOutOfBoundsError { index: 10, parent: value, }) ); } #[test] fn check_get_object_as_keys() { let value = json!({ "a": 1, "b": 2, "c": 3, "d": 4, "e": 5 }); assert_string_eq( get_object_as_keys(&mut value.clone()), json!(["a", "b", "c", "d", "e"]), ); } #[test] fn check_get_object_range() { let value = json!({ "a": 1, "b": 2, "c": 3, "d": 4, "e": 5 }); assert_eq!( get_object_range( &Range::new(Some(Index::new(0)), Some(Index::new(2))), &mut json!({}) ), Ok(json!({})) ); assert_string_eq( get_object_range( &Range::new(Some(Index::new(0)), Some(Index::new(2))), &mut value.clone(), ), json!({ "a": 1, "b": 2, "c": 3 }), ); assert_string_eq( get_object_range( &Range::new(Some(Index::new(2)), Some(Index::new(0))), &mut value.clone(), ), json!({ "c": 3, "b": 2, "a": 1 }), ); assert_eq!( get_object_range( &Range::new(Some(Index::new(0)), Some(Index::new(0))), &mut value.clone() ), Ok(json!({ "a": 1 })) ); assert_string_eq( get_object_range(&Range::new(None, Some(Index::new(4))), &mut value.clone()), json!({ "a": 1, "b": 2, "c": 3, "d": 4, "e": 5 }), ); assert_eq!( get_object_range(&Range::new(Some(Index::new(4)), None), &mut value.clone()), Ok(json!({ "e": 5 })) ); assert_eq!( get_object_range(&Range::new(None, Some(Index::new(5))), &mut value.clone()), Err(JqlRunnerError::RangeOutOfBoundsError { start: 0, end: 5, parent: value }) ); let value = json!(1); assert_eq!( get_object_range(&Range::new(None, Some(Index::new(5))), &mut value.clone()), Err(JqlRunnerError::InvalidObjectError(value)) ); } } jql-runner-8.0.9/src/runner.rs000064400000000000000000000215751046102023000144170ustar 00000000000000use jql_parser::{ group::split, parser::parse, tokens::Token, }; use rayon::prelude::*; use serde_json::{ Value, json, }; use crate::{ array::{ get_array_as_indexes, get_array_indexes, get_array_lenses, get_array_range, get_flattened_array, }, errors::JqlRunnerError, object::{ get_flattened_object, get_object_as_keys, get_object_indexes, get_object_key, get_object_multi_key, get_object_range, }, }; /// Takes a raw input as a slice string to parse and a reference of a JSON /// `Value`. /// Returns a JSON `Value`. /// /// # Errors /// /// Returns a `JqlRunnerError` on failure. pub fn raw(input: &str, json: &Value) -> Result { if input.is_empty() { return Err(JqlRunnerError::EmptyQueryError); } let tokens = parse(input)?; token(&tokens, json) } /// Takes a slice of `Tokens` to parse and a reference of a JSON /// `Value`. /// Returns a JSON `Value`. /// /// # Errors /// /// Returns a `JqlRunnerError` on failure. pub fn token(tokens: &[Token], json: &Value) -> Result { let groups = split(tokens); let result = groups .par_iter() .try_fold_with(vec![], |mut acc: Vec, group| { acc.push(group_runner(group, json)?); Ok::, JqlRunnerError>(acc) }) .try_reduce(Vec::new, |mut a, b| { a.extend(b); Ok(a) }); result.map(|group| { if groups.len() == 1 { json!(group[0]) } else { json!(group) } }) } /// Takes a slice of references of `Token` and a reference of a JSON `Value`. /// Returns a JSON `Value` or an error. /// Note: the `GroupSeparator` enum variant is unreachable at this point since /// it has been filtered out by any of the public `runner` functions. pub(crate) fn group_runner(tokens: &[&Token], json: &Value) -> Result { tokens .iter() // At this level we can use rayon since every token is applied // sequentially. .try_fold((json.clone(), false), |mut outer_acc, &token| { if outer_acc.1 { let result = outer_acc .0 .as_array_mut() // We can safely unwrap since `outer_acc.1` is truthy. .unwrap() .par_iter() .try_fold_with( (vec![], outer_acc.1), |mut inner_acc: (Vec, bool), inner_value| { let result = matcher((inner_value.clone(), outer_acc.1), token)?; inner_acc.0.push(result.0); inner_acc.1 = result.1; Ok::<(Vec, bool), JqlRunnerError>(inner_acc) }, ) .try_reduce( || (vec![], false), |mut a, b| { a.0.extend(b.0); Ok((a.0, b.1)) }, )?; Ok((json!(result.0), result.1)) } else { matcher(outer_acc, token) } }) // Drop the `pipe` boolean flag. .map(|(value, _)| value) } /// Internal matcher consumed by the `group_runner` to apply a selection based /// on the provided mutable JSON `Value` and the reference of a `Token`. /// A `piped` flag is used to keep track of the pipe operators. fn matcher( (mut acc, mut piped): (Value, bool), token: &Token, ) -> Result<(Value, bool), JqlRunnerError> { let result = match token { Token::ArrayIndexSelector(indexes) => get_array_indexes(indexes, &acc), Token::ArrayRangeSelector(range) => get_array_range(range, &mut acc), Token::FlattenOperator => match acc { Value::Array(_) => get_flattened_array(&acc), Value::Object(_) => Ok(get_flattened_object(&acc)), _ => Err(JqlRunnerError::FlattenError(acc)), }, Token::KeyOperator => match acc { Value::Array(_) => get_array_as_indexes(&acc), Value::Object(_) => get_object_as_keys(&mut acc), // Return the original value for Null, Bool, Number and String. Value::Bool(bool) => Ok(json!(bool)), Value::Number(number) => Ok(json!(number)), Value::String(string) => Ok(json!(string)), Value::Null => Ok(json!(null)), }, Token::GroupSeparator => unreachable!(), Token::KeySelector(key) => get_object_key(key, &acc), Token::LensSelector(lenses) => get_array_lenses(lenses, &mut acc), Token::MultiKeySelector(keys) => get_object_multi_key(keys, &mut acc), Token::ObjectIndexSelector(indexes) => get_object_indexes(indexes, &mut acc), Token::ObjectRangeSelector(range) => get_object_range(range, &mut acc), Token::PipeInOperator => { if !acc.is_array() { return Err(JqlRunnerError::PipeInError(acc)); } piped = true; Ok(acc) } Token::PipeOutOperator => { if !piped { return Err(JqlRunnerError::PipeOutError); } piped = false; Ok(acc) } Token::TruncateOperator => match acc { Value::Array(_) => Ok(json!([])), Value::Object(_) => Ok(json!({})), Value::Bool(_) | Value::Number(_) | Value::String(_) | Value::Null => Ok(acc), }, }; result.map(|value| (value, piped)) } #[cfg(test)] mod tests { use jql_parser::{ errors::JqlParserError, tokens::{ Token, View, }, }; use serde_json::json; use super::raw; use crate::errors::JqlRunnerError; #[test] fn check_runner_empty_input_error() { assert_eq!(raw("", &json!("")), Err(JqlRunnerError::EmptyQueryError)); } #[test] fn check_runner_parsing_error() { assert_eq!( raw(r#""a"b"#, &json!({ "a": 1 })), Err(JqlRunnerError::ParsingError(JqlParserError::ParsingError { tokens: [Token::KeySelector("a")].stringify(), unparsed: "b".to_string(), })) ); } #[test] fn check_runner_no_key_found_error() { let parent = json!({ "a": 1 }); assert_eq!( raw(r#""b""#, &parent), Err(JqlRunnerError::KeyNotFoundError { key: "b".to_string(), parent }) ); } #[test] fn check_runner_index_not_found_error() { let parent = json!(["a"]); assert_eq!( raw("[1]", &parent), Err(JqlRunnerError::IndexOutOfBoundsError { index: 1, parent }) ); } #[test] fn check_runner_success() { assert_eq!( raw(r#""a","b""#, &json!({ "a": 1, "b": 2 })), Ok(json!([1, 2])) ); assert_eq!(raw(r#""a""b""#, &json!({ "a": { "b": 2 } })), Ok(json!(2))); assert_eq!( raw("[4,2,0]", &json!(["a", "b", "c", "d", "e"])), Ok(json!(["e", "c", "a"])) ); } #[test] fn check_runner_pipes() { let value = json!({ "a": [{ "b": { "c": 1 } }, { "b": { "c": 2 }}]}); assert_eq!(raw(r#""a"|>"b""c"<|[1]"#, &value), Ok(json!(2))); } #[test] fn check_runner_truncate() { assert_eq!(raw(r#""a"!"#, &json!({ "a": [1, 2, 3] })), Ok(json!([]))); assert_eq!(raw(r#""a"!"#, &json!({ "a": { "b": 1 } })), Ok(json!({}))); assert_eq!(raw(r#""a"!"#, &json!({ "a": true })), Ok(json!(true))); assert_eq!(raw(r#""a"!"#, &json!({ "a": 1 })), Ok(json!(1))); assert_eq!(raw(r#""a"!"#, &json!({ "a": "b" })), Ok(json!("b"))); assert_eq!(raw(r#""a"!"#, &json!({ "a": null })), Ok(json!(null))); assert_eq!(raw("!", &json!({ "a": null })), Ok(json!({}))); assert_eq!( raw(r#""a"!"b""#, &json!({ "a": [1, 2, 3] })), Err(JqlRunnerError::ParsingError(JqlParserError::TruncateError( [ Token::KeySelector("a"), Token::TruncateOperator, Token::KeySelector("b") ] .stringify(), ))) ); } #[test] fn check_runner_lens() { let value = json!([ { "a": { "b": { "c": 1 }}}, { "a": { "b": { "c": 2 }}}, ]); assert_eq!( raw(r#"|={"a""b""c"=2}"#, &value), Ok(json!([ { "a": { "b": { "c": 2 }}} ])) ); } #[test] fn check_runner_keys() { let value = json!({ "a": { "b": { "c": { "d": 1 }}}}); assert_eq!(raw(r#""a""b""c"@"#, &value), Ok(json!(["d"]))); } } jql-runner-8.0.9/tests/integration.rs000064400000000000000000000010501046102023000157660ustar 00000000000000use jql_parser::tokens::Token; use jql_runner::runner::{ raw, token, }; use serde_json::json; #[test] fn check_raw_integration() { assert_eq!( raw(r#""a","b""#, &json!({ "a": 1, "b": 2 })), Ok(json!([1, 2])) ); } #[test] fn check_token_integration() { assert_eq!( token( &[ Token::KeySelector("a"), Token::GroupSeparator, Token::KeySelector("b") ], &json!({ "a": 1, "b": 2 }) ), Ok(json!([1, 2])) ); }