feat: open source vibecoding example project
This commit is contained in:
commit
b370f462f2
34 changed files with 7744 additions and 0 deletions
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
/target
|
||||
.redo/
|
||||
34
CLAUDE.md
Normal file
34
CLAUDE.md
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
To begin fuzzing, run: `cargo fuzz run <fuzz target name>`
|
||||
|
||||
The source code for a fuzz target by default lives in `fuzz/fuzz_targets/<fuzz target name>.rs`.
|
||||
|
||||
Each fuzz target is a Rust program that is given random data and tests a crate (in this case, json-archive). Use `cargo fuzz list` to view the list of all existing fuzz targets:
|
||||
|
||||
## Documentation Style Guidelines
|
||||
|
||||
When writing command documentation, follow the Dutch engineer approach:
|
||||
|
||||
### Structure and Content
|
||||
- Lead with what the command actually does (one clear sentence)
|
||||
- Show real examples using actual demo files from the project
|
||||
- Include both human-readable and machine-readable output modes
|
||||
- Include practical use cases with actual bash/jq examples for scripting
|
||||
- Be upfront about performance characteristics and limitations
|
||||
- Document known bugs/issues directly instead of hiding them
|
||||
|
||||
### Tone and Communication
|
||||
- Be direct and practical, not promotional
|
||||
- Don't apologize for limitations. Just state them clearly so engineers can make informed decisions
|
||||
- Use real scenarios, not toy examples
|
||||
- Focus on what engineers actually need to know to use the tool effectively
|
||||
- Include error cases and what they mean
|
||||
- Provide concrete examples that can be copy-pasted and run
|
||||
|
||||
### Example sections to include
|
||||
1. **Purpose**: One sentence explaining what it does
|
||||
2. **Basic usage**: Simple examples first
|
||||
3. **Output modes**: When to use human vs JSON output
|
||||
4. **Practical use cases**: Real scenarios with working code
|
||||
5. **Performance characteristics**: Memory/CPU usage expectations
|
||||
6. **Error cases**: Common failures and what they mean
|
||||
7. **Known issues**: Bugs or limitations stated directly
|
||||
518
Cargo.lock
generated
Normal file
518
Cargo.lock
generated
Normal file
|
|
@ -0,0 +1,518 @@
|
|||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "android_system_properties"
|
||||
version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arbitrary"
|
||||
version = "1.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1"
|
||||
dependencies = [
|
||||
"derive_arbitrary",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "autocfg"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.9.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2261d10cca569e4643e526d8dc2e62e433cc8aba21ab764233731f8d369bf394"
|
||||
|
||||
[[package]]
|
||||
name = "bumpalo"
|
||||
version = "3.19.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43"
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.2.39"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e1354349954c6fc9cb0deab020f27f783cf0b604e8bb754dc4658ecf0d29c35f"
|
||||
dependencies = [
|
||||
"find-msvc-tools",
|
||||
"shlex",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2fd1289c04a9ea8cb22300a459a72a385d7c73d3259e2ed7dcb2af674838cfa9"
|
||||
|
||||
[[package]]
|
||||
name = "chrono"
|
||||
version = "0.4.42"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "145052bdd345b87320e369255277e3fb5152762ad123a901ef5c262dd38fe8d2"
|
||||
dependencies = [
|
||||
"iana-time-zone",
|
||||
"js-sys",
|
||||
"num-traits",
|
||||
"serde",
|
||||
"wasm-bindgen",
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core-foundation-sys"
|
||||
version = "0.8.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
|
||||
|
||||
[[package]]
|
||||
name = "derive_arbitrary"
|
||||
version = "1.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "errno"
|
||||
version = "0.3.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fastrand"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
|
||||
|
||||
[[package]]
|
||||
name = "find-msvc-tools"
|
||||
version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1ced73b1dacfc750a6db6c0a0c3a3853c8b41997e2e2c563dc90804ae6867959"
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"r-efi",
|
||||
"wasi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "iana-time-zone"
|
||||
version = "0.1.64"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "33e57f83510bb73707521ebaffa789ec8caf86f9657cad665b092b581d40e9fb"
|
||||
dependencies = [
|
||||
"android_system_properties",
|
||||
"core-foundation-sys",
|
||||
"iana-time-zone-haiku",
|
||||
"js-sys",
|
||||
"log",
|
||||
"wasm-bindgen",
|
||||
"windows-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "iana-time-zone-haiku"
|
||||
version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
|
||||
dependencies = [
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c"
|
||||
|
||||
[[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 = "json-archive"
|
||||
version = "0.99.0"
|
||||
dependencies = [
|
||||
"arbitrary",
|
||||
"chrono",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"uuid",
|
||||
"xflags",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.176"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "58f929b4d672ea937a23a1ab494143d968337a5f47e56d0815df1e0890ddf174"
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039"
|
||||
|
||||
[[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 = "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.40"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "r-efi"
|
||||
version = "5.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "1.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cd15f8a2c5551a84d56efdc1cd049089e409ac19a3072d5037a17fd70719ff3e"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[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 = "serde"
|
||||
version = "1.0.227"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "80ece43fc6fbed4eb5392ab50c07334d3e577cbf40997ee896fe7af40bba4245"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.227"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7a576275b607a2c86ea29e410193df32bc680303c82f31e275bbfcafe8b33be5"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.227"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "51e694923b8824cf0e9b382adf0f60d4e05f348f357b38833a3fa5ed7c2ede04"
|
||||
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 = [
|
||||
"itoa",
|
||||
"memchr",
|
||||
"ryu",
|
||||
"serde",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "1.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
|
||||
|
||||
[[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 = "tempfile"
|
||||
version = "3.23.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2d31c77bdf42a745371d260a26ca7163f1e0924b64afa0b688e61b5a9fa02f16"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"getrandom",
|
||||
"once_cell",
|
||||
"rustix",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f63a545481291138910575129486daeaf8ac54aee4387fe7906919f7830c7d9d"
|
||||
|
||||
[[package]]
|
||||
name = "uuid"
|
||||
version = "1.18.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2f87b8aa10b915a06587d0dec516c282ff295b475d94abf425d62b57710070a2"
|
||||
dependencies = [
|
||||
"getrandom",
|
||||
"js-sys",
|
||||
"serde",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasi"
|
||||
version = "0.14.7+wasi-0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "883478de20367e224c0090af9cf5f9fa85bed63a95c1abf3afc5c083ebc06e8c"
|
||||
dependencies = [
|
||||
"wasip2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasip2"
|
||||
version = "1.0.1+wasi-0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7"
|
||||
dependencies = [
|
||||
"wit-bindgen",
|
||||
]
|
||||
|
||||
[[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 = "windows-core"
|
||||
version = "0.62.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6844ee5416b285084d3d3fffd743b925a6c9385455f64f6d4fa3031c4c2749a9"
|
||||
dependencies = [
|
||||
"windows-implement",
|
||||
"windows-interface",
|
||||
"windows-link",
|
||||
"windows-result",
|
||||
"windows-strings",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-implement"
|
||||
version = "0.60.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "edb307e42a74fb6de9bf3a02d9712678b22399c87e6fa869d6dfcd8c1b7754e0"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-interface"
|
||||
version = "0.59.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c0abd1ddbc6964ac14db11c7213d6532ef34bd9aa042c2e5935f59d7908b46a5"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "45e46c0661abb7180e7b9c281db115305d49ca1709ab8242adf09666d2173c65"
|
||||
|
||||
[[package]]
|
||||
name = "windows-result"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7084dcc306f89883455a206237404d3eaf961e5bd7e0f312f7c91f57eb44167f"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-strings"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7218c655a553b0bed4426cf54b20d7ba363ef543b52d515b3e48d7fd55318dda"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.61.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6f109e41dd4a3c848907eb83d5a42ea98b3769495597450cf6d153507b166f0f"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen"
|
||||
version = "0.46.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59"
|
||||
|
||||
[[package]]
|
||||
name = "xflags"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d9e15fbb3de55454b0106e314b28e671279009b363e6f1d8e39fdc3bf048944"
|
||||
dependencies = [
|
||||
"xflags-macros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xflags-macros"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "672423d4fea7ffa2f6c25ba60031ea13dc6258070556f125cc4d790007d4a155"
|
||||
15
Cargo.toml
Normal file
15
Cargo.toml
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
[package]
|
||||
name = "json-archive"
|
||||
version = "0.99.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
xflags = "0.3"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
uuid = { version = "1.0", features = ["v4", "serde"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3.0"
|
||||
arbitrary = { version = "1.0", features = ["derive"] }
|
||||
661
LICENSE
Normal file
661
LICENSE
Normal file
|
|
@ -0,0 +1,661 @@
|
|||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published
|
||||
by the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
20
LICENSE-header
Normal file
20
LICENSE-header
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
json-archive is a tool for tracking JSON file changes over time
|
||||
Copyright (C) 2025 Peoples Grocers LLC
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published
|
||||
by the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
To purchase a license under different terms contact admin@peoplesgrocers.com
|
||||
To request changes, report bugs, or give user feedback contact
|
||||
marxism@peoplesgrocers.com
|
||||
|
||||
215
README.md
Normal file
215
README.md
Normal file
|
|
@ -0,0 +1,215 @@
|
|||
# json-archive
|
||||
|
||||
A practical CLI tool for tracking JSON file changes over time. Instead of keeping multiple copies of JSON files, this creates compact delta-based archives that preserve the complete history.
|
||||
|
||||
## What it does
|
||||
|
||||
This tool solves a simple problem: you have a JSON file that changes regularly, and you want to track its history without storing dozens of full copies.
|
||||
|
||||
`json-archive` creates a `.json.archive` file next to your original JSON file. Each time you run the tool, it calculates only what changed and appends those deltas to the archive. You get complete history with minimal storage overhead.
|
||||
|
||||
The archive format is human-readable JSONL (not binary), making it easy to inspect, debug, and pipe into other scripts or web visualizations.
|
||||
|
||||
## Quick example
|
||||
|
||||
```bash
|
||||
# Create initial archive from data.json (infers output: data.json.archive)
|
||||
json-archive data.json
|
||||
|
||||
# Later, append changes to existing archive
|
||||
json-archive data.json.archive data.json
|
||||
|
||||
# Or let it infer again (won't overwrite without --force)
|
||||
json-archive data.json # Safe: won't overwrite existing data.json.archive
|
||||
```
|
||||
|
||||
## Real-world use case
|
||||
|
||||
Perfect for tracking YouTube video metadata over time:
|
||||
|
||||
```bash
|
||||
# Download video info with yt-dlp
|
||||
yt-dlp --write-info-json -o "%(id)s.%(ext)s" "https://youtube.com/watch?v=..."
|
||||
|
||||
# Create initial archive (creates videoID.info.json.archive)
|
||||
json-archive videoID.info.json
|
||||
|
||||
# Later, append new observations to existing archive
|
||||
json-archive videoID.info.json.archive videoID.info.json
|
||||
|
||||
# Or safely re-run (won't overwrite existing archive)
|
||||
json-archive videoID.info.json
|
||||
|
||||
# Run daily in a cron job to capture changes
|
||||
# The archive preserves your title/description experiments and view count history
|
||||
```
|
||||
|
||||
## Design philosophy
|
||||
|
||||
**Hackable over efficient**: The file format prioritizes human readability and scriptability over binary compactness. You can:
|
||||
|
||||
- Open archives in any text editor
|
||||
- Grep through them for specific changes
|
||||
- Parse them in JavaScript without special libraries
|
||||
- Pipe them through standard Unix tools
|
||||
|
||||
**Minimal workflow changes**: Archive files sit next to your original JSON files with a `.archive` extension. Your existing scripts need minimal modification.
|
||||
|
||||
### Compression support (as a concession)
|
||||
|
||||
While the core design keeps things simple and readable, the tool does work with compressed archives as a practical concession for those who need it. You can read from and write to gzip, brotli, and zlib compressed files without special flags.
|
||||
|
||||
**Important caveat**: Compressed archives may require rewriting the entire file during updates (depending on the compression format). If your temporary filesystem is full or too small, updates can fail. In that case, manually specify an output destination with `-o` to write the new archive elsewhere.
|
||||
|
||||
This works fine for the happy path with archive files up to a few hundred megabytes, but contradicts the "keep it simple" design philosophy - it's included because it's practically useful.
|
||||
|
||||
## Archive format
|
||||
|
||||
The format is JSONL with delta-based changes using [JSON Pointer](https://tools.ietf.org/html/rfc6901) paths. For complete technical details about the file format, see the [file format specification](docs/file-format-spec.md).
|
||||
|
||||
```jsonl
|
||||
{"version": 1, "created": "2025-01-15T10:00:00Z", "initial": {"views": 100, "title": "My Video"}}
|
||||
# First observation
|
||||
["observe", "obs-001", "2025-01-15T10:05:00Z", 2]
|
||||
["change", "/views", 100, 150, "obs-001"]
|
||||
["change", "/title", "My Video", "My Awesome Video", "obs-001"]
|
||||
# Second observation
|
||||
["observe", "obs-002", "2025-01-15T11:00:00Z", 1]
|
||||
["change", "/views", 150, 200, "obs-002"]
|
||||
```
|
||||
|
||||
Each observation records:
|
||||
- What changed (using JSON Pointer paths like `/views`)
|
||||
- The old and new values
|
||||
- When it happened
|
||||
- A unique observation ID
|
||||
|
||||
## Commands
|
||||
|
||||
The tool infers behavior from filenames:
|
||||
|
||||
### Documentation
|
||||
|
||||
- [Info command](docs/info-command.md) - View archive metadata and observation timeline
|
||||
- [State command](docs/state-command.md) - Retrieve JSON state at specific observations
|
||||
- [File format specification](docs/file-format-spec.md) - Technical details about the archive format
|
||||
|
||||
### Creating archives
|
||||
|
||||
```bash
|
||||
# Create archive from JSON files (output inferred from first filename)
|
||||
json-archive file1.json file2.json file3.json
|
||||
# Creates: file1.json.archive
|
||||
|
||||
# Won't overwrite existing archives (safe to re-run)
|
||||
json-archive data.json # Won't overwrite data.json.archive if it exists
|
||||
|
||||
# Force overwrite existing archive
|
||||
json-archive --force data.json
|
||||
|
||||
# Specify custom output location
|
||||
json-archive -o custom.archive data.json
|
||||
```
|
||||
|
||||
### Appending to archives
|
||||
|
||||
```bash
|
||||
# First file is archive, rest are appended
|
||||
json-archive existing.json.archive new1.json new2.json
|
||||
|
||||
# Works with any mix of files
|
||||
json-archive data.json.archive updated-data.json
|
||||
```
|
||||
|
||||
### Additional options
|
||||
|
||||
```bash
|
||||
# Add snapshots after 10 observations instead of default of 100 for faster append operations
|
||||
json-archive -s 50 data.json
|
||||
|
||||
# Add source metadata
|
||||
json-archive --source "youtube-metadata" data.json
|
||||
```
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
cargo install json-archive
|
||||
```
|
||||
|
||||
Or build from source:
|
||||
|
||||
```bash
|
||||
git clone <repo>
|
||||
cd json-archive
|
||||
cargo build --release
|
||||
```
|
||||
|
||||
## File naming convention
|
||||
|
||||
Archives use the `.json.archive` extension by default:
|
||||
|
||||
- `data.json` -> `data.json.archive`
|
||||
- `video.info.json` -> `video.info.json.archive`
|
||||
- `config.json` -> `config.json.archive`
|
||||
|
||||
This makes it immediately clear which files are archives and which are source files.
|
||||
|
||||
|
||||
## Error handling
|
||||
|
||||
The tool uses descriptive diagnostics instead of cryptic error codes:
|
||||
|
||||
```
|
||||
error: I couldn't find the input file: missing.json
|
||||
|
|
||||
= help: Make sure the file path is correct and the file exists.
|
||||
Check for typos in the filename.
|
||||
```
|
||||
|
||||
Diagnostics are categorized as Fatal, Warning, or Info, and the tool exits with non-zero status only for fatal errors.
|
||||
|
||||
## Performance characteristics
|
||||
|
||||
- **Memory usage**: Bounded by largest single JSON file, not archive size
|
||||
- **Append speed**: Fast - only computes deltas, doesn't re-read entire archive
|
||||
- **Read speed**: Linear scan, but snapshots allow seeking to recent state
|
||||
- **File size**: Typically 10-30% the size of storing all JSON copies
|
||||
|
||||
For very large archives, consider using snapshots (`-s` flag) to enable faster seeking.
|
||||
|
||||
## Browser compatibility
|
||||
|
||||
Archives can be loaded directly in web applications:
|
||||
|
||||
```javascript
|
||||
// Parse archive in browser
|
||||
fetch('data.json.archive')
|
||||
.then(response => response.text())
|
||||
.then(text => {
|
||||
const lines = text.split('\n');
|
||||
const header = JSON.parse(lines[0]);
|
||||
const events = lines.slice(1)
|
||||
.filter(line => line && !line.startsWith('#'))
|
||||
.map(line => JSON.parse(line));
|
||||
|
||||
// Replay history, build visualizations, etc.
|
||||
});
|
||||
```
|
||||
|
||||
The format uses only standard JSON. No special parsing required.
|
||||
|
||||
## Contributing
|
||||
|
||||
This is a practical tool built for real workflow needs. Contributions welcome, especially:
|
||||
|
||||
- Additional CLI commands (validate, info, extract)
|
||||
- Performance optimizations for large archives
|
||||
- More compression format support
|
||||
- Better diff algorithms for arrays
|
||||
|
||||
## License
|
||||
|
||||
---
|
||||
|
||||
*Built with Rust for reliability and performance. Designed to be simple enough to understand, powerful enough to be useful.*
|
||||
9
default.do
Normal file
9
default.do
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
#!/usr/bin/env bash
|
||||
|
||||
case $1 in
|
||||
copyright)
|
||||
addlicense -c "Peoples Grocers LLC" -f LICENSE-header -l "agpl-3.0" -s src/ >&2
|
||||
;;
|
||||
|
||||
|
||||
esac
|
||||
174
docs/demo/README.md
Normal file
174
docs/demo/README.md
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
# json-archive Demo
|
||||
|
||||
This directory contains example JSON files that demonstrate how to use the `json-archive` tool to track changes over time.
|
||||
|
||||
## Sample Data
|
||||
|
||||
The demo uses three snapshots of the same JSON object as it evolves:
|
||||
|
||||
### [v1.json](v1.json)
|
||||
```json
|
||||
{"id": 1, "name": "Alice", "count": 0, "tags": ["initial"]}
|
||||
```
|
||||
|
||||
### [v2.json](v2.json)
|
||||
```json
|
||||
{"id": 1, "name": "Alice", "count": 5, "tags": ["initial", "updated"], "lastSeen": "2025-01-15"}
|
||||
```
|
||||
|
||||
### [v3.json](v3.json)
|
||||
```json
|
||||
{"id": 1, "name": "Bob", "count": 10, "tags": ["updated", "final"], "lastSeen": "2025-01-16", "score": 95}
|
||||
```
|
||||
|
||||
## Basic Usage
|
||||
|
||||
### 1. Create Initial Archive
|
||||
|
||||
```bash
|
||||
json-archive v1.json
|
||||
```
|
||||
|
||||
**What happens:**
|
||||
- Creates `v1.json.archive` with the initial state
|
||||
- Leaves `v1.json` untouched
|
||||
- The archive contains a header with the complete initial object
|
||||
|
||||
**Expected output:**
|
||||
```
|
||||
Created archive: v1.json.archive
|
||||
```
|
||||
|
||||
**Archive contents (`v1.json.archive`):**
|
||||
```jsonl
|
||||
{"version": 1, "created": "2025-01-15T10:00:00Z", "initial": {"id": 1, "name": "Alice", "count": 0, "tags": ["initial"]}}
|
||||
```
|
||||
|
||||
### 2. Append New Observation
|
||||
|
||||
```bash
|
||||
json-archive v1.json.archive v2.json
|
||||
```
|
||||
|
||||
**What happens:**
|
||||
- Compares v2.json against the current state (v1.json)
|
||||
- Appends delta changes to the existing archive
|
||||
- Shows what fields changed between versions
|
||||
|
||||
**Expected output:**
|
||||
```
|
||||
Appended observation to: v1.json.archive
|
||||
Changes detected: 3 modifications
|
||||
```
|
||||
|
||||
**New archive contents:**
|
||||
```jsonl
|
||||
{"version": 1, "created": "2025-01-15T10:00:00Z", "initial": {"id": 1, "name": "Alice", "count": 0, "tags": ["initial"]}}
|
||||
["observe", "obs-002", "2025-01-15T10:05:00Z", 3]
|
||||
["change", "/count", 5, "obs-002"]
|
||||
["add", "/lastSeen", "2025-01-15", "obs-002"]
|
||||
["change", "/tags", ["initial", "updated"], "obs-002"]
|
||||
```
|
||||
|
||||
### 3. Continue Building History
|
||||
|
||||
```bash
|
||||
json-archive v1.json.archive v3.json
|
||||
```
|
||||
|
||||
**Expected output:**
|
||||
```
|
||||
Appended observation to: v1.json.archive
|
||||
Changes detected: 4 modifications
|
||||
```
|
||||
|
||||
**Final archive contents:**
|
||||
```jsonl
|
||||
{"version": 1, "created": "2025-01-15T10:00:00Z", "initial": {"id": 1, "name": "Alice", "count": 0, "tags": ["initial"]}}
|
||||
["observe", "obs-002", "2025-01-15T10:05:00Z", 3]
|
||||
["change", "/count", 5, "obs-002"]
|
||||
["add", "/lastSeen", "2025-01-15", "obs-002"]
|
||||
["change", "/tags", ["initial", "updated"], "obs-002"]
|
||||
["observe", "obs-003", "2025-01-15T10:10:00Z", 4]
|
||||
["change", "/name", "Bob", "obs-003"]
|
||||
["change", "/count", 10, "obs-003"]
|
||||
["change", "/tags", ["updated", "final"], "obs-003"]
|
||||
["change", "/lastSeen", "2025-01-16", "obs-003"]
|
||||
["add", "/score", 95, "obs-003"]
|
||||
```
|
||||
|
||||
## Real-World Workflow Example
|
||||
|
||||
```bash
|
||||
# Daily automation script
|
||||
curl https://example.com/123456/user-profile.json -L -O /tmp/user-profile.json
|
||||
json-archive \
|
||||
/mnt/share/backups/user-profile.json.archive /tmp/user-profile.json \
|
||||
--source "my-backup.sh:example.com:123456" \
|
||||
--remove-source-files
|
||||
```
|
||||
|
||||
**What you're seeing here:**
|
||||
|
||||
1. **Self-documenting archives**: The archive filename `user-profile.json.archive` contains the original filename, making it clear what data is being tracked.
|
||||
|
||||
2. **File cleanup with `--remove-source-files`**: This flag moves the JSON file into the archive rather than copying it, automatically cleaning up temporary files in shell scripts.
|
||||
|
||||
3. **Flexible file handling**: You don't have to remove the source file. For example, you could snapshot a `state.json` file that some process uses as a database without disrupting the running process.
|
||||
|
||||
4. **Source labeling for data integrity**: The `--source` flag creates a unique ID for the JSON object you're tracking. When appending to an existing archive, if the source label doesn't match, the tool refuses to run to protect against data loss. Use your own naming convention to create meaningful identifiers (URLs, script names, etc.).
|
||||
|
||||
## Most Useful Features Tour
|
||||
|
||||
|
||||
### 1. Create Archive All At Once
|
||||
|
||||
```bash
|
||||
json-archive v1.json v2.json v3.json
|
||||
```
|
||||
|
||||
**What happens:**
|
||||
- Creates `v1.json.archive` with all three observations
|
||||
- Processes each file sequentially, computing deltas between them
|
||||
- Equivalent to the step-by-step approach above
|
||||
|
||||
### 2. Remove Source Files After Archiving
|
||||
|
||||
```bash
|
||||
json-archive v1.json --remove-source-files
|
||||
```
|
||||
|
||||
**What happens:**
|
||||
- Creates `v1.json.archive`
|
||||
- **Deletes** `v1.json` after successful archive creation
|
||||
- Useful for cleanup workflows where you only want the archive
|
||||
|
||||
### 3. Force Overwrite Existing Archive
|
||||
|
||||
```bash
|
||||
json-archive --force v1.json
|
||||
```
|
||||
|
||||
**What happens:**
|
||||
- Overwrites `v1.json.archive` if it already exists
|
||||
- Without `--force`, the command safely refuses to overwrite
|
||||
|
||||
### 4. Custom Output Location
|
||||
|
||||
```bash
|
||||
json-archive -o my-custom.json.archive v1.json v2.json v3.json
|
||||
```
|
||||
|
||||
**What happens:**
|
||||
- Creates archive at specified path instead of inferring from input filename
|
||||
- Useful when you want a different naming convention
|
||||
|
||||
### 5. Add Source Metadata
|
||||
|
||||
```bash
|
||||
json-archive --source "yt-dlp:youtube:dQw4w9WgXcQ" v1.json v2.json v3.json
|
||||
```
|
||||
|
||||
**What happens:**
|
||||
- Adds source identifier to archive header
|
||||
- Helps track where the data came from in complex workflows
|
||||
1
docs/demo/v1.json
Normal file
1
docs/demo/v1.json
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"id": 1, "name": "Alice", "count": 0, "tags": ["initial"]}
|
||||
1
docs/demo/v2.json
Normal file
1
docs/demo/v2.json
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"id": 1, "name": "Alice", "count": 5, "tags": ["initial", "updated"], "lastSeen": "2025-01-15"}
|
||||
1
docs/demo/v3.json
Normal file
1
docs/demo/v3.json
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"id": 1, "name": "Bob", "count": 10, "tags": ["updated", "final"], "lastSeen": "2025-01-16", "score": 95}
|
||||
288
docs/file-format-spec.md
Normal file
288
docs/file-format-spec.md
Normal file
|
|
@ -0,0 +1,288 @@
|
|||
# JSON Archive Format Specification v1.0
|
||||
|
||||
## Overview
|
||||
|
||||
A JSONL (JSON Lines) format for tracking the evolution of JSON objects over time using delta-based changes with JSON Pointer (RFC 6901) for path notation. Inspired by asciicinema v3 format.
|
||||
|
||||
## File Structure
|
||||
|
||||
```
|
||||
{header}
|
||||
[event]
|
||||
[event]
|
||||
...
|
||||
```
|
||||
|
||||
- First line: JSON header object
|
||||
- Following lines: Event arrays or comments
|
||||
- File extension: `.json.archive`
|
||||
- Encoding: UTF-8
|
||||
|
||||
### File Extension Rationale
|
||||
|
||||
The `.json.archive` extension is designed for workflows where a command line program generates the same `filename.json` file daily. By appending `.archive` to the existing filename, minimal changes are needed to existing processes.
|
||||
|
||||
For example, if you have a daily process that generates `data.json`, the archive becomes `data.json.archive`. This makes shell pipeline operations intuitive:
|
||||
|
||||
```bash
|
||||
json-archive concat data.json.archive data.json --remove-source-files
|
||||
```
|
||||
|
||||
This command clearly shows that `json-archive` is moving the contents of `data.json` into the archive, making the operation self-documenting and requiring minimal changes to existing workflows.
|
||||
|
||||
## Header Format
|
||||
|
||||
```json
|
||||
{
|
||||
"version": 1,
|
||||
"created": "ISO-8601 timestamp",
|
||||
"source": "optional source identifier",
|
||||
"initial": { ... initial object state ... },
|
||||
"metadata": { ... optional metadata ... }
|
||||
}
|
||||
```
|
||||
|
||||
Required fields:
|
||||
- `version`: Format version (currently 1)
|
||||
- `created`: ISO-8601 timestamp of archive creation
|
||||
- `initial`: Complete initial state of the tracked object
|
||||
|
||||
## Event Types
|
||||
|
||||
Each event is a JSON array with the event type as the first element.
|
||||
|
||||
### 1. Observe Event
|
||||
Marks the beginning of an observation with a count of following changes.
|
||||
|
||||
```json
|
||||
["observe", observationId, timestamp, changeCount]
|
||||
```
|
||||
|
||||
- `observationId`: Unique string identifier (can be any string: UUID, timestamp, sequential ID, etc.)
|
||||
- `timestamp`: ISO-8601 timestamp
|
||||
- `changeCount`: Number of add/change/remove/move events that follow
|
||||
|
||||
### 2. Add Event
|
||||
Adds a new field to the object.
|
||||
|
||||
```json
|
||||
["add", path, value, observationId]
|
||||
```
|
||||
|
||||
- `path`: JSON Pointer path to the field
|
||||
- `value`: Any JSON value
|
||||
- `observationId`: String referencing the preceding observe event
|
||||
|
||||
### 3. Change Event
|
||||
Modifies an existing field value.
|
||||
|
||||
```json
|
||||
["change", path, newValue, observationId]
|
||||
```
|
||||
|
||||
- `path`: JSON Pointer path to the field
|
||||
- `newValue`: New value
|
||||
- `observationId`: String referencing the preceding observe event
|
||||
|
||||
### 4. Remove Event
|
||||
Removes a field from the object.
|
||||
|
||||
```json
|
||||
["remove", path, observationId]
|
||||
```
|
||||
|
||||
- `path`: JSON Pointer path to the field
|
||||
- `observationId`: String referencing the preceding observe event
|
||||
|
||||
### 5. Move Event
|
||||
Reorders existing elements within an array. Moves are applied sequentially.
|
||||
|
||||
```json
|
||||
["move", path, [[fromIndex, toIndex], ...], observationId]
|
||||
```
|
||||
|
||||
- `path`: JSON Pointer path to the array
|
||||
- `[[fromIndex, toIndex], ...]`: List of move operations applied in order
|
||||
- `observationId`: String referencing the preceding observe event
|
||||
|
||||
**Important implementation detail:** Each move operation should:
|
||||
1. First, insert a copy of the element at `fromIndex` into position `toIndex`
|
||||
2. Then, remove the original element from its position (accounting for any shift caused by the insertion)
|
||||
|
||||
This approach prevents index calculation errors. When `fromIndex > toIndex`, the removal happens at `fromIndex + 1`. When `fromIndex < toIndex`, the removal happens at `fromIndex`.
|
||||
|
||||
Example: Given array [A, B, C, D]:
|
||||
```json
|
||||
["move", "/items", [[3, 1]], "obs-001"]
|
||||
```
|
||||
Step 1: Insert D at index 1 → [A, D, B, C, D]
|
||||
Step 2: Remove from index 4 → [A, D, B, C]
|
||||
|
||||
For multiple moves on [A, B, C]:
|
||||
```json
|
||||
["move", "/items", [[2, 0], [2, 1]], "obs-001"]
|
||||
```
|
||||
First move: Insert C at 0 → [C, A, B, C], remove from 3 → [C, A, B]
|
||||
Second move: Insert B at 1 → [C, B, A, B], remove from 3 → [C, B, A]
|
||||
|
||||
Note: Use `add` events for new elements, not `move`. Move is strictly for reordering existing elements.
|
||||
|
||||
### 6. Snapshot Event
|
||||
Stores complete object state for faster seeking and append performance.
|
||||
|
||||
```json
|
||||
["snapshot", observationId, timestamp, object]
|
||||
```
|
||||
|
||||
- `observationId`: Unique string identifier for this snapshot
|
||||
- `timestamp`: ISO-8601 timestamp
|
||||
- `object`: Complete object state at this point
|
||||
|
||||
Snapshot events are interchangeable with observe+delta sequences: you can rewrite
|
||||
["observe", observatinID, timestamp, N] followed by N delta events into a single
|
||||
[ "snapshot", observationID, timestamp, object], and vice versa.
|
||||
|
||||
Implementation Reality: The current tool naively appends snapshots without removing
|
||||
equivalent observe+delta sequences. Yhis is lazy programming for implementation ease.
|
||||
Better tools should replace the delta sequence with the snapshot, not duplicate
|
||||
the information.
|
||||
|
||||
The snapshot placement strategy is about append performance optimization.
|
||||
|
||||
1. **Append requires replay:** To append a new observation, you must know the current
|
||||
state. The tool seeks backward from EOF to find the most recent snapshot, then
|
||||
replays forward from there. Placing snapshots near the end of large archives
|
||||
minimizes this replay cost.
|
||||
2. **Snapshot placement is arbitrary:** Unlike fixed-interval I-frames in video codecs,
|
||||
snapshots can be placed anywhere based on access patterns and file size.
|
||||
by moving/adding snapshots closer to the end, reducing replay cost on append.
|
||||
Archives can be "losslessly re-encoded" by repositioning snapshots based on
|
||||
access patterns and file size.
|
||||
3. Practical example:
|
||||
- Small files (10 versions): No snapshots needed, full replay is cheap
|
||||
- Large files (GBs of updates): Place snapshots near end-of-file so append only replays
|
||||
recent deltas
|
||||
- High-frequency appends: Consider periodic re-encoding to maintain snapshots near EOF
|
||||
|
||||
## Identifier Format
|
||||
|
||||
The `observationId` field used throughout events is an arbitrary string that must be unique within the file. Common patterns include:
|
||||
- UUIDs: `"550e8400-e29b-41d4-a716-446655440000"`
|
||||
- Timestamps: `"1705325400.123"`
|
||||
- Sequential IDs: `"obs-001"`, `"obs-002"`
|
||||
- ISO timestamps: `"2025-01-15T10:05:00.123Z"`
|
||||
- Any other string scheme that guarantees uniqueness
|
||||
|
||||
## Path Notation
|
||||
|
||||
Paths use JSON Pointer notation (RFC 6901):
|
||||
|
||||
- Object fields: `/user/profile/name`
|
||||
- Array elements: `/items/0`
|
||||
- Root level: `/fieldname`
|
||||
- Empty string key: `/`
|
||||
- Escape sequences: `~0` for `~`, `~1` for `/`
|
||||
|
||||
Examples:
|
||||
- `/users/0/email` - First user's email
|
||||
- `/metadata/tags/3` - Fourth tag in tags array
|
||||
- `/strange~1key` - Key containing forward slash
|
||||
|
||||
## Comments
|
||||
|
||||
Lines beginning with `#` are treated as comments and ignored by parsers.
|
||||
|
||||
```
|
||||
# This is a comment
|
||||
["observe", "obs-001", "2025-01-15T10:00:00Z", 1]
|
||||
```
|
||||
|
||||
## Example File
|
||||
|
||||
```json
|
||||
{"version": 1, "created": "2025-01-15T10:00:00Z", "initial": {"id": 1, "views": 0, "tags": ["api", "v1"]}}
|
||||
# First observation - using sequential ID
|
||||
["observe", "obs-001", "2025-01-15T10:05:00Z", 2]
|
||||
["add", "/title", "Hello World", "obs-001"]
|
||||
["change", "/views", 10, "obs-001"]
|
||||
# Array modification - using UUID
|
||||
["observe", "550e8400-e29b-41d4-a716-446655440000", "2025-01-15T10:10:00Z", 3]
|
||||
["change", "/views", 25, "550e8400-e29b-41d4-a716-446655440000"]
|
||||
["add", "/tags/2", "public", "550e8400-e29b-41d4-a716-446655440000"]
|
||||
["move", "/tags", [[2, 0]], "550e8400-e29b-41d4-a716-446655440000"]
|
||||
# Snapshot - using timestamp as ID
|
||||
["snapshot", "1705325700.456", "2025-01-15T10:15:00Z", {"id": 1, "views": 25, "title": "Hello World", "tags": ["public", "api", "v1"]}]
|
||||
["observe", "obs-003", "2025-01-15T10:20:00Z", 2]
|
||||
["add", "/likes", 5, "obs-003"]
|
||||
["remove", "/title", "obs-003"]
|
||||
```
|
||||
|
||||
## Reading Algorithm
|
||||
|
||||
1. Parse header from first line
|
||||
2. Initialize state from `header.initial`
|
||||
3. For each subsequent line:
|
||||
- Skip if comment (`#`)
|
||||
- Parse JSON array
|
||||
- Apply event based on type:
|
||||
- `observe`: Note changeCount for bounded reading
|
||||
- `add`: Set field at path
|
||||
- `change`: Update field at path
|
||||
- `remove`: Delete field at path
|
||||
- `move`: Apply array reordering operations sequentially
|
||||
- `snapshot`: Optionally update state completely
|
||||
|
||||
**Important:** Observations in the archive file are not required to be in chronological order. The reader implementation should parse all events and sort them by timestamp if chronological ordering is needed for the use case.
|
||||
|
||||
## CLI Implementation Notes
|
||||
|
||||
### Basic Command Structure
|
||||
```bash
|
||||
jsonarchive create output.jarch input1.json input2.json ...
|
||||
```
|
||||
|
||||
### Processing Logic
|
||||
1. Read first JSON file as initial state
|
||||
2. For each subsequent JSON file:
|
||||
- Compare with current state
|
||||
- Generate observe event with timestamp
|
||||
- Generate add/change/remove/move events for differences (using JSON Pointer paths)
|
||||
- Update current state
|
||||
3. Optionally insert snapshots based on:
|
||||
- Number of observations (e.g., every 100)
|
||||
- Size of accumulated deltas
|
||||
- Time intervals
|
||||
|
||||
### JSON Pointer Implementation
|
||||
- Implement RFC 6901 compliant JSON Pointer resolution
|
||||
- Handle escape sequences: `~0` → `~`, `~1` → `/`
|
||||
- Validate paths before applying operations
|
||||
- Array indices must be valid integers
|
||||
|
||||
### Diff Generation
|
||||
|
||||
**For objects:**
|
||||
1. Recursively traverse both objects
|
||||
2. For keys in new but not old: generate `add`
|
||||
3. For keys in old but not new: generate `remove`
|
||||
4. For keys in both with different values: generate `change`
|
||||
|
||||
**For arrays:**
|
||||
1. Identify common elements (present in both arrays)
|
||||
2. Generate `remove` for elements only in old array
|
||||
3. Generate `add` for elements only in new array
|
||||
4. Generate `change` for common elements with different values
|
||||
5. Generate minimal `move` sequence for common elements in different positions
|
||||
|
||||
**Important:** New array elements should always use `add` operations at their final positions. The `move` operation is strictly for reordering existing elements. This keeps the semantics clear and the diff minimal.
|
||||
|
||||
## Design Rationale
|
||||
|
||||
- **Delta-based**: Minimizes file size for small incremental changes
|
||||
- **Self-contained**: Header contains initial state, making file complete
|
||||
- **Human-readable**: JSONL with comments for debugging
|
||||
- **Standards-compliant**: Uses RFC 6901 JSON Pointer for path notation
|
||||
- **Seekable**: Snapshots allow jumping to recent states without full replay
|
||||
- **Simple parsing**: Line-based format with standard JSON
|
||||
- **Change bounds**: Observe events include count for predictable reads
|
||||
|
||||
160
docs/info-command.md
Normal file
160
docs/info-command.md
Normal file
|
|
@ -0,0 +1,160 @@
|
|||
# Info Command
|
||||
|
||||
Shows what's in an archive file: metadata, observation timeline, and file statistics.
|
||||
|
||||
## Basic Usage
|
||||
|
||||
```bash
|
||||
json-archive info file.archive
|
||||
json-archive info --output json file.archive
|
||||
```
|
||||
|
||||
The command reads the entire archive file to collect observation data, so expect memory usage proportional to file size.
|
||||
|
||||
## Output Modes
|
||||
|
||||
### Human-readable (default)
|
||||
```bash
|
||||
json-archive info docs/demo/v1.json.archive
|
||||
```
|
||||
|
||||
```
|
||||
Archive: docs/demo/v1.json.archive
|
||||
Created: Sun 15:23:40 28-Sep-2025
|
||||
|
||||
3 observations from Sun 15:23:40 28-Sep-2025 to Sun 15:23:40 28-Sep-2025
|
||||
|
||||
# Observation ID Date & Time Changes JSON Size
|
||||
────────────────────────────────────────────────────────────────────────────────────────
|
||||
0 (initial) Sun 15:23:40 28-Sep-2025 - 52 bytes
|
||||
1 obs-c4636428-1400-44... Sun 15:23:40 28-Sep-2025 3 86 bytes
|
||||
2 obs-389b4a7c-4d78-42... Sun 15:23:40 28-Sep-2025 7 94 bytes
|
||||
|
||||
Total archive size: 1.1 KB (0 snapshots)
|
||||
|
||||
To get the JSON value at a specific observation:
|
||||
json-archive state --index <#> docs/demo/v1.json.archive
|
||||
json-archive state --id <observation-id> docs/demo/v1.json.archive
|
||||
|
||||
Examples:
|
||||
json-archive state --index 0 docs/demo/v1.json.archive # Get initial state
|
||||
json-archive state --index 2 docs/demo/v1.json.archive # Get state after observation 2
|
||||
```
|
||||
|
||||
Use this mode when you want to quickly understand what's in an archive or debug observation timelines.
|
||||
|
||||
### JSON output
|
||||
|
||||
Use JSON output for scripting, monitoring, or feeding data into other tools.
|
||||
|
||||
```bash
|
||||
json-archive info --output json docs/demo/v1.json.archive
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"archive": "docs/demo/v1.json.archive",
|
||||
"created": "2025-09-28T15:23:40.633960+00:00",
|
||||
"file_size": 1096,
|
||||
"snapshot_count": 0,
|
||||
"observations": [
|
||||
{
|
||||
"index": 0,
|
||||
"id": "initial",
|
||||
"timestamp": "2025-09-28T15:23:40.633960+00:00",
|
||||
"changes": 0,
|
||||
"json_size": 52
|
||||
},
|
||||
{
|
||||
"index": 1,
|
||||
"id": "obs-c4636428-1400-44d7-b30f-1c080c608e3c",
|
||||
"timestamp": "2025-09-28T15:23:40.634520+00:00",
|
||||
"changes": 3,
|
||||
"json_size": 86
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Field Reference
|
||||
|
||||
### Human-readable fields
|
||||
- **#**: Index number (0-indexed) for use with `--index` flag
|
||||
- **Observation ID**: Unique identifier for use with `--id` flag
|
||||
- **Date & Time**: When the observation was recorded
|
||||
- **Changes**: Number of fields modified (dash for initial state)
|
||||
- **JSON Size**: Size in bytes of the reconstructed JSON at this observation
|
||||
|
||||
### JSON output fields
|
||||
- **archive**: File path
|
||||
- **created**: Archive creation timestamp (ISO-8601)
|
||||
- **file_size**: Archive file size in bytes
|
||||
- **snapshot_count**: Number of snapshots for seeking optimization
|
||||
- **observations[]**: Array of observation metadata
|
||||
- **index**: 0-based position for `--index` access
|
||||
- **id**: Unique ID for `--id` access ("initial" for index 0)
|
||||
- **timestamp**: ISO-8601 timestamp
|
||||
- **changes**: Change count (0 for initial)
|
||||
- **json_size**: Reconstructed JSON size in bytes
|
||||
|
||||
## Practical Use Cases
|
||||
|
||||
### Monitoring archive growth
|
||||
```bash
|
||||
# Archive size and observation count
|
||||
json-archive info --output json data.json.archive | jq '{file_size, observation_count: (.observations | length)}'
|
||||
```
|
||||
|
||||
### Finding large observations
|
||||
```bash
|
||||
# Observations with JSON size > 1KB
|
||||
json-archive info --output json data.json.archive | jq '.observations[] | select(.json_size > 1024)'
|
||||
```
|
||||
|
||||
## Performance Characteristics
|
||||
|
||||
- **Memory usage**: Loads entire archive into memory to reconstruct states
|
||||
- **I/O pattern**: Single full file read, no seeking
|
||||
- **CPU usage**: Minimal - mostly JSON parsing and formatting
|
||||
|
||||
For archives larger than available RAM, consider using [`json-archive state`](state-command.md) with specific observation IDs instead of getting full timeline info.
|
||||
|
||||
## Error Cases
|
||||
|
||||
### Missing archive file
|
||||
```bash
|
||||
$ json-archive info nonexistent.archive
|
||||
error E051: Path not found
|
||||
|
||||
I couldn't find the archive file: nonexistent.archive
|
||||
|
||||
Make sure the file path is correct and the file exists.
|
||||
Check for typos in the filename.
|
||||
```
|
||||
|
||||
### Corrupt archive header
|
||||
```bash
|
||||
$ json-archive info corrupted.archive
|
||||
error E003: Missing header
|
||||
|
||||
I couldn't parse the header: unexpected character at line 1
|
||||
|
||||
The archive file appears to be corrupted or not a valid json-archive file.
|
||||
```
|
||||
|
||||
### Invalid output format
|
||||
```bash
|
||||
$ json-archive info --output xml data.json.archive
|
||||
# Silently falls back to human-readable format
|
||||
# (no validation on output parameter)
|
||||
```
|
||||
|
||||
## Known Issues
|
||||
|
||||
**Command reference bug**: The human-readable output currently shows `json-archive get` commands in the usage examples, but the correct command is `json-archive state`. This is a display bug - the actual functionality is unaffected.
|
||||
|
||||
## See Also
|
||||
|
||||
- [`json-archive state`](state-command.md) - Retrieve JSON data at specific observations
|
||||
- [File Format Specification](file-format-spec.md) - Archive format details
|
||||
- [Getting Started Guide](../README.md) - Basic usage examples
|
||||
202
docs/state-command.md
Normal file
202
docs/state-command.md
Normal file
|
|
@ -0,0 +1,202 @@
|
|||
# State Command
|
||||
|
||||
The `json-archive state` command retrieves the JSON state at a specific observation
|
||||
|
||||
## Flags and Semantics:
|
||||
Primary access methods:
|
||||
- --id <observation-id>: Get state at specific observation (unambiguous, primary method)
|
||||
- --index <n>: Get state at Nth observation in file order (convenience for using outout from info command, with caveat)
|
||||
|
||||
Timestamp-based access:
|
||||
- --as-of <timestamp>: Most recent observation with timestamp ≤ given time ("state as of
|
||||
this moment")
|
||||
- ---before <timestamp>: Most recent observation with timestamp < given time
|
||||
(strictly before)
|
||||
- --after <timestamp>: Earliest observation with timestamp > given time (first state
|
||||
after)
|
||||
- --latest: Most recent observation by timestamp (default if no flags given)
|
||||
|
||||
## Access Methods
|
||||
|
||||
You must specify exactly one access method to identify which observation's state to retrieve:
|
||||
|
||||
### By Observation ID (Recommended)
|
||||
```bash
|
||||
json-archive state --id <OBSERVATION_ID> file.archive
|
||||
```
|
||||
Gets the state at the observation with the specified ID. This is the most unambiguous method since observation IDs are unique within the archive.
|
||||
|
||||
Example:
|
||||
```bash
|
||||
json-archive state --id obs-c4636428-1400-44d7-b30f-1c080c608e3c data.json.archive
|
||||
```
|
||||
|
||||
### By File Index
|
||||
```bash
|
||||
json-archive state --index <INDEX> file.archive
|
||||
```
|
||||
Gets the state at the Nth observation in file order (0-indexed). **Note:** Observations are not guaranteed to be in chronological order in the file.
|
||||
|
||||
Example:
|
||||
```bash
|
||||
json-archive state --index 0 data.json.archive # Initial state (first observation)
|
||||
json-archive state --index 1 data.json.archive # Second observation
|
||||
```
|
||||
|
||||
### By Timestamp
|
||||
|
||||
#### As-Of Timestamp
|
||||
```bash
|
||||
json-archive state --as-of <TIMESTAMP> file.archive
|
||||
```
|
||||
Gets the state from the most recent observation with timestamp ≤ the given time.
|
||||
|
||||
Example:
|
||||
```bash
|
||||
json-archive state --as-of "2025-01-15T10:05:00Z" data.json.archive
|
||||
```
|
||||
|
||||
#### Right Before Timestamp
|
||||
```bash
|
||||
json-archive state --before <TIMESTAMP> file.archive
|
||||
```
|
||||
Gets the state from the most recent observation with timestamp < the given time (strictly before).
|
||||
|
||||
Example:
|
||||
```bash
|
||||
json-archive state --before "2025-01-15T10:05:00Z" data.json.archive
|
||||
```
|
||||
|
||||
#### After Timestamp
|
||||
```bash
|
||||
json-archive state --after <TIMESTAMP> file.archive
|
||||
```
|
||||
Gets the state from the earliest observation with timestamp > the given time.
|
||||
|
||||
Example:
|
||||
```bash
|
||||
json-archive state --after "2025-01-15T10:05:00Z" data.json.archive
|
||||
```
|
||||
|
||||
### Latest State (Default)
|
||||
```bash
|
||||
json-archive state --latest file.archive
|
||||
# Or simply:
|
||||
json-archive state file.archive
|
||||
```
|
||||
Gets the state from the observation with the latest timestamp. This is the default behavior when no other access method is specified.
|
||||
|
||||
## Timestamp Format
|
||||
|
||||
All timestamps must be in ISO-8601 format with UTC timezone:
|
||||
- `2025-01-15T10:05:00Z`
|
||||
- `2025-01-15T10:05:00.123Z` (with milliseconds)
|
||||
|
||||
## Output
|
||||
|
||||
The command outputs the JSON state as pretty-printed JSON to stdout:
|
||||
|
||||
```json
|
||||
{
|
||||
"count": 10,
|
||||
"id": 1,
|
||||
"lastSeen": "2025-01-16",
|
||||
"name": "Bob",
|
||||
"score": 95,
|
||||
"tags": [
|
||||
"initial",
|
||||
"final"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Error Cases
|
||||
|
||||
### Non-existent Observation ID
|
||||
```bash
|
||||
$ json-archive state --id nonexistent-id file.archive
|
||||
error E030: Non-existent observation ID
|
||||
|
||||
I couldn't find an observation with ID 'nonexistent-id'
|
||||
|
||||
Use 'json-archive info' to see available observation IDs
|
||||
```
|
||||
|
||||
### Out-of-bounds Index
|
||||
```bash
|
||||
$ json-archive state --index 10 file.archive
|
||||
error E053: Array index out of bounds
|
||||
|
||||
Index 10 is out of bounds. The archive has 3 observations (0-2)
|
||||
|
||||
Use 'json-archive info' to see available observation indices
|
||||
```
|
||||
|
||||
### Invalid Timestamp
|
||||
```bash
|
||||
$ json-archive state --as-of "invalid-timestamp" file.archive
|
||||
error W012: Invalid timestamp
|
||||
|
||||
I couldn't parse the timestamp 'invalid-timestamp'. Please use ISO-8601 format like '2025-01-15T10:05:00Z'
|
||||
```
|
||||
|
||||
### No Observations Match Timestamp
|
||||
```bash
|
||||
$ json-archive state --as-of "2020-01-01T00:00:00Z" file.archive
|
||||
error E051: Path not found
|
||||
|
||||
No observations found as of 2020-01-01 00:00:00 UTC
|
||||
|
||||
Try using --after to find the first observation after this time
|
||||
```
|
||||
|
||||
### Multiple Access Methods
|
||||
```bash
|
||||
$ json-archive state --id obs-123 --index 1 file.archive
|
||||
error E022: Wrong field count
|
||||
|
||||
Please specify only one access method (--id, --index, --as-of, --right-before, --after, or --latest)
|
||||
|
||||
Examples:
|
||||
json-archive state --id obs-123 file.archive
|
||||
json-archive state --index 2 file.archive
|
||||
json-archive state --as-of "2025-01-15T10:05:00Z" file.archive
|
||||
```
|
||||
|
||||
## Implementation Details and Design Rationale
|
||||
|
||||
### Why Timestamp Access Uses More Memory
|
||||
|
||||
The timestamp-based flags (`--as-of`, `--before`, `--after`, `--latest`) are **memory-intensive** because they must read the entire archive file into memory. Here's why:
|
||||
|
||||
**The Problem**: Since observations are not guaranteed to be in chronological order in the file, we cannot use efficient seeking or leverage snapshots for optimization. To find "the most recent observation ≤ timestamp", we must:
|
||||
|
||||
1. Read every single observation in the file
|
||||
2. Parse all their timestamps
|
||||
3. Sort them chronologically in memory
|
||||
4. Find the target observation
|
||||
5. Replay all events to reconstruct the state
|
||||
|
||||
This is fundamentally different from index-based access (`--index`, `--id`) which can potentially use snapshots and delta compression for efficiency.
|
||||
|
||||
### Why Files Aren't Chronologically Sorted
|
||||
|
||||
The tool accepts observations in any order because data collection is ad hoc. You don't always have perfect control over when or how observations are collected.
|
||||
|
||||
**Real scenario**: You have JSON files scattered across multiple hard drives from different systems. You can't mount all drives simultaneously, so you load them one at a time and absorb the data as you go. The observations end up out of chronological order, but that's fine - you consolidate first, then organize later.
|
||||
|
||||
**Another scenario**: You inherit data from multiple APIs and systems that were collecting observations over time. The timestamps are there, but the files weren't collected in chronological order. You want to merge everything into one archive without having to pre-sort.
|
||||
|
||||
**The approach**: "Octopus-style merging" - absorb all the data as-is, then make sense of it incrementally. The file format doesn't fight this workflow.
|
||||
|
||||
### Design Philosophy
|
||||
|
||||
Timestamp access works the way it does because the tool prioritizes data consolidation over performance optimization. When you use `--as-of` or `--latest`, you're asking the tool to figure out chronological relationships that may not exist in the file structure.
|
||||
|
||||
Index/ID access is direct - you're referencing observations by their position in the file or unique identifier. This is efficient because it doesn't require chronological analysis.
|
||||
|
||||
## See Also
|
||||
|
||||
- [`json-archive info`](info-command.md) - View archive metadata and observation timeline
|
||||
- [File Format Specification](file-format-spec.md) - Details about the archive format
|
||||
- [Getting Started Guide](../README.md) - Basic usage examples
|
||||
4
fuzz/.gitignore
vendored
Normal file
4
fuzz/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
target
|
||||
corpus
|
||||
artifacts
|
||||
coverage
|
||||
549
fuzz/Cargo.lock
generated
Normal file
549
fuzz/Cargo.lock
generated
Normal file
|
|
@ -0,0 +1,549 @@
|
|||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "android_system_properties"
|
||||
version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arbitrary"
|
||||
version = "1.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1"
|
||||
dependencies = [
|
||||
"derive_arbitrary",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "autocfg"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.9.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2261d10cca569e4643e526d8dc2e62e433cc8aba21ab764233731f8d369bf394"
|
||||
|
||||
[[package]]
|
||||
name = "bumpalo"
|
||||
version = "3.19.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43"
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.2.39"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e1354349954c6fc9cb0deab020f27f783cf0b604e8bb754dc4658ecf0d29c35f"
|
||||
dependencies = [
|
||||
"find-msvc-tools",
|
||||
"jobserver",
|
||||
"libc",
|
||||
"shlex",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2fd1289c04a9ea8cb22300a459a72a385d7c73d3259e2ed7dcb2af674838cfa9"
|
||||
|
||||
[[package]]
|
||||
name = "chrono"
|
||||
version = "0.4.42"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "145052bdd345b87320e369255277e3fb5152762ad123a901ef5c262dd38fe8d2"
|
||||
dependencies = [
|
||||
"iana-time-zone",
|
||||
"js-sys",
|
||||
"num-traits",
|
||||
"serde",
|
||||
"wasm-bindgen",
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core-foundation-sys"
|
||||
version = "0.8.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
|
||||
|
||||
[[package]]
|
||||
name = "derive_arbitrary"
|
||||
version = "1.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "errno"
|
||||
version = "0.3.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fastrand"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
|
||||
|
||||
[[package]]
|
||||
name = "find-msvc-tools"
|
||||
version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1ced73b1dacfc750a6db6c0a0c3a3853c8b41997e2e2c563dc90804ae6867959"
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"r-efi",
|
||||
"wasi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "iana-time-zone"
|
||||
version = "0.1.64"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "33e57f83510bb73707521ebaffa789ec8caf86f9657cad665b092b581d40e9fb"
|
||||
dependencies = [
|
||||
"android_system_properties",
|
||||
"core-foundation-sys",
|
||||
"iana-time-zone-haiku",
|
||||
"js-sys",
|
||||
"log",
|
||||
"wasm-bindgen",
|
||||
"windows-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "iana-time-zone-haiku"
|
||||
version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
|
||||
dependencies = [
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c"
|
||||
|
||||
[[package]]
|
||||
name = "jobserver"
|
||||
version = "0.1.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33"
|
||||
dependencies = [
|
||||
"getrandom",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[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 = "json-archive"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"uuid",
|
||||
"xflags",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "json-archive-fuzz"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"arbitrary",
|
||||
"json-archive",
|
||||
"libfuzzer-sys",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.176"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "58f929b4d672ea937a23a1ab494143d968337a5f47e56d0815df1e0890ddf174"
|
||||
|
||||
[[package]]
|
||||
name = "libfuzzer-sys"
|
||||
version = "0.4.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5037190e1f70cbeef565bd267599242926f724d3b8a9f510fd7e0b540cfa4404"
|
||||
dependencies = [
|
||||
"arbitrary",
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039"
|
||||
|
||||
[[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 = "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.40"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "r-efi"
|
||||
version = "5.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "1.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cd15f8a2c5551a84d56efdc1cd049089e409ac19a3072d5037a17fd70719ff3e"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[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 = "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 = [
|
||||
"itoa",
|
||||
"memchr",
|
||||
"ryu",
|
||||
"serde",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "1.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
|
||||
|
||||
[[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 = "tempfile"
|
||||
version = "3.23.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2d31c77bdf42a745371d260a26ca7163f1e0924b64afa0b688e61b5a9fa02f16"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"getrandom",
|
||||
"once_cell",
|
||||
"rustix",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f63a545481291138910575129486daeaf8ac54aee4387fe7906919f7830c7d9d"
|
||||
|
||||
[[package]]
|
||||
name = "uuid"
|
||||
version = "1.18.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2f87b8aa10b915a06587d0dec516c282ff295b475d94abf425d62b57710070a2"
|
||||
dependencies = [
|
||||
"getrandom",
|
||||
"js-sys",
|
||||
"serde",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasi"
|
||||
version = "0.14.7+wasi-0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "883478de20367e224c0090af9cf5f9fa85bed63a95c1abf3afc5c083ebc06e8c"
|
||||
dependencies = [
|
||||
"wasip2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasip2"
|
||||
version = "1.0.1+wasi-0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7"
|
||||
dependencies = [
|
||||
"wit-bindgen",
|
||||
]
|
||||
|
||||
[[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 = "windows-core"
|
||||
version = "0.62.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6844ee5416b285084d3d3fffd743b925a6c9385455f64f6d4fa3031c4c2749a9"
|
||||
dependencies = [
|
||||
"windows-implement",
|
||||
"windows-interface",
|
||||
"windows-link",
|
||||
"windows-result",
|
||||
"windows-strings",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-implement"
|
||||
version = "0.60.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "edb307e42a74fb6de9bf3a02d9712678b22399c87e6fa869d6dfcd8c1b7754e0"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-interface"
|
||||
version = "0.59.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c0abd1ddbc6964ac14db11c7213d6532ef34bd9aa042c2e5935f59d7908b46a5"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "45e46c0661abb7180e7b9c281db115305d49ca1709ab8242adf09666d2173c65"
|
||||
|
||||
[[package]]
|
||||
name = "windows-result"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7084dcc306f89883455a206237404d3eaf961e5bd7e0f312f7c91f57eb44167f"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-strings"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7218c655a553b0bed4426cf54b20d7ba363ef543b52d515b3e48d7fd55318dda"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.61.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6f109e41dd4a3c848907eb83d5a42ea98b3769495597450cf6d153507b166f0f"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen"
|
||||
version = "0.46.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59"
|
||||
|
||||
[[package]]
|
||||
name = "xflags"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d9e15fbb3de55454b0106e314b28e671279009b363e6f1d8e39fdc3bf048944"
|
||||
dependencies = [
|
||||
"xflags-macros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xflags-macros"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "672423d4fea7ffa2f6c25ba60031ea13dc6258070556f125cc4d790007d4a155"
|
||||
38
fuzz/Cargo.toml
Normal file
38
fuzz/Cargo.toml
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
[package]
|
||||
name = "json-archive-fuzz"
|
||||
version = "0.0.0"
|
||||
publish = false
|
||||
edition = "2021"
|
||||
|
||||
[package.metadata]
|
||||
cargo-fuzz = true
|
||||
|
||||
[dependencies]
|
||||
libfuzzer-sys = "0.4"
|
||||
arbitrary = { version = "1.0", features = ["derive"] }
|
||||
tempfile = "3.0"
|
||||
serde_json = "1.0"
|
||||
|
||||
[dependencies.json-archive]
|
||||
path = ".."
|
||||
|
||||
[[bin]]
|
||||
name = "fuzz_random_bytes"
|
||||
path = "fuzz_targets/fuzz_random_bytes.rs"
|
||||
test = false
|
||||
doc = false
|
||||
bench = false
|
||||
|
||||
[[bin]]
|
||||
name = "fuzz_structured"
|
||||
path = "fuzz_targets/fuzz_structured.rs"
|
||||
test = false
|
||||
doc = false
|
||||
bench = false
|
||||
|
||||
[[bin]]
|
||||
name = "fuzz_mutations"
|
||||
path = "fuzz_targets/fuzz_mutations.rs"
|
||||
test = false
|
||||
doc = false
|
||||
bench = false
|
||||
115
fuzz/fuzz_targets/fuzz_mutations.rs
Normal file
115
fuzz/fuzz_targets/fuzz_mutations.rs
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
#![no_main]
|
||||
|
||||
use libfuzzer_sys::fuzz_target;
|
||||
use json_archive::{ArchiveReader, ReadMode};
|
||||
use std::io::Write;
|
||||
use tempfile::NamedTempFile;
|
||||
|
||||
fn create_archive_content(data: &[u8]) -> Vec<u8> {
|
||||
// Start with a simple base archive
|
||||
let base = r#"{"version":1,"created":"2025-01-01T00:00:00Z","initial":{"id":1}}
|
||||
["observe", "obs-1", "2025-01-01T00:00:00Z", 1]
|
||||
["add", "/name", "test", "obs-1"]"#;
|
||||
|
||||
let mut result = base.as_bytes().to_vec();
|
||||
|
||||
// Apply simple mutations based on fuzz input
|
||||
if data.is_empty() {
|
||||
return result;
|
||||
}
|
||||
|
||||
// Keep mutations small and realistic
|
||||
let max_size = 4096; // 4KB limit
|
||||
|
||||
for (i, &byte) in data.iter().take(16).enumerate() {
|
||||
if result.len() > max_size {
|
||||
break;
|
||||
}
|
||||
|
||||
match byte % 8 {
|
||||
0 => {
|
||||
// Truncate at random position
|
||||
let pos = (byte as usize) % result.len().max(1);
|
||||
result.truncate(pos);
|
||||
}
|
||||
1 => {
|
||||
// Insert invalid UTF-8
|
||||
let pos = (byte as usize) % (result.len() + 1);
|
||||
result.insert(pos, 0xFF);
|
||||
}
|
||||
2 => {
|
||||
// Corrupt a quote
|
||||
if let Some(pos) = result.iter().position(|&b| b == b'"') {
|
||||
result[pos] = b'X';
|
||||
}
|
||||
}
|
||||
3 => {
|
||||
// Insert extra newline
|
||||
let pos = (byte as usize) % (result.len() + 1);
|
||||
result.insert(pos, b'\n');
|
||||
}
|
||||
4 => {
|
||||
// Corrupt JSON bracket
|
||||
if let Some(pos) = result.iter().position(|&b| b == b'[' || b == b'{') {
|
||||
result[pos] = b'?';
|
||||
}
|
||||
}
|
||||
5 => {
|
||||
// Insert random byte
|
||||
let pos = (byte as usize) % (result.len() + 1);
|
||||
result.insert(pos, byte);
|
||||
}
|
||||
6 => {
|
||||
// Remove a character
|
||||
if !result.is_empty() {
|
||||
let pos = (byte as usize) % result.len();
|
||||
result.remove(pos);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
// Add some garbage line
|
||||
let insertion = format!("\n[\"garbage\", {}]", i);
|
||||
let pos = (byte as usize) % (result.len() + 1);
|
||||
result.splice(pos..pos, insertion.bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
fuzz_target!(|data: &[u8]| {
|
||||
let archive_content = create_archive_content(data);
|
||||
|
||||
if let Ok(mut temp_file) = NamedTempFile::new() {
|
||||
if temp_file.write_all(&archive_content).is_ok() {
|
||||
// Test both validation modes
|
||||
for mode in [ReadMode::FullValidation, ReadMode::AppendSeek] {
|
||||
if let Ok(reader) = ArchiveReader::new(temp_file.path(), mode) {
|
||||
let result = reader.read(temp_file.path());
|
||||
|
||||
// Should never panic, regardless of input malformation
|
||||
match result {
|
||||
Ok(read_result) => {
|
||||
// Basic invariants that should hold for any successful parse
|
||||
let _ = &read_result.final_state;
|
||||
let _ = &read_result.diagnostics;
|
||||
|
||||
// Observation count should be reasonable
|
||||
assert!(read_result.observation_count < 100000);
|
||||
|
||||
// If we have diagnostics, they should be well-formed
|
||||
for diagnostic in read_result.diagnostics.diagnostics() {
|
||||
assert!(!diagnostic.description.is_empty());
|
||||
}
|
||||
},
|
||||
Err(_) => {
|
||||
// It's fine for the parser to reject malformed input
|
||||
// Just make sure it doesn't panic
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
22
fuzz/fuzz_targets/fuzz_random_bytes.rs
Normal file
22
fuzz/fuzz_targets/fuzz_random_bytes.rs
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
#![no_main]
|
||||
|
||||
use libfuzzer_sys::fuzz_target;
|
||||
use json_archive::{ArchiveReader, ReadMode};
|
||||
use std::io::Write;
|
||||
use tempfile::NamedTempFile;
|
||||
|
||||
fuzz_target!(|data: &[u8]| {
|
||||
// Write the random bytes to a temporary file
|
||||
if let Ok(mut temp_file) = NamedTempFile::new() {
|
||||
if temp_file.write_all(data).is_ok() {
|
||||
// Try to read the file with both validation modes
|
||||
for mode in [ReadMode::FullValidation, ReadMode::AppendSeek] {
|
||||
if let Ok(reader) = ArchiveReader::new(temp_file.path(), mode) {
|
||||
// The read operation should never panic, regardless of input
|
||||
// It should either succeed or return an error gracefully
|
||||
let _ = reader.read(temp_file.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
188
fuzz/fuzz_targets/fuzz_structured.rs
Normal file
188
fuzz/fuzz_targets/fuzz_structured.rs
Normal file
|
|
@ -0,0 +1,188 @@
|
|||
#![no_main]
|
||||
|
||||
use libfuzzer_sys::fuzz_target;
|
||||
use arbitrary::{Arbitrary, Unstructured};
|
||||
use json_archive::{ArchiveReader, ReadMode};
|
||||
use std::io::Write;
|
||||
use tempfile::NamedTempFile;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
#[derive(Arbitrary, Debug)]
|
||||
struct FuzzArchive {
|
||||
header: FuzzHeader,
|
||||
events: Vec<FuzzEvent>,
|
||||
}
|
||||
|
||||
#[derive(Arbitrary, Debug)]
|
||||
struct FuzzHeader {
|
||||
has_type_field: bool,
|
||||
has_version_field: bool,
|
||||
has_created_field: bool,
|
||||
has_initial_field: bool,
|
||||
version_value: i32,
|
||||
initial_state: FuzzValue,
|
||||
}
|
||||
|
||||
#[derive(Arbitrary, Debug)]
|
||||
enum FuzzEvent {
|
||||
Observe {
|
||||
id: String,
|
||||
timestamp: String,
|
||||
change_count: i32,
|
||||
},
|
||||
Add {
|
||||
path: String,
|
||||
value: FuzzValue,
|
||||
obs_id: String,
|
||||
},
|
||||
Change {
|
||||
path: String,
|
||||
old_value: FuzzValue,
|
||||
new_value: FuzzValue,
|
||||
obs_id: String,
|
||||
},
|
||||
Remove {
|
||||
path: String,
|
||||
obs_id: String,
|
||||
},
|
||||
Move {
|
||||
path: String,
|
||||
moves: Vec<(i32, i32)>,
|
||||
obs_id: String,
|
||||
},
|
||||
Snapshot {
|
||||
id: String,
|
||||
timestamp: String,
|
||||
state: FuzzValue,
|
||||
},
|
||||
InvalidEvent {
|
||||
event_type: String,
|
||||
extra_fields: Vec<FuzzValue>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Arbitrary, Debug)]
|
||||
enum FuzzValue {
|
||||
Null,
|
||||
Bool(bool),
|
||||
Number(f64),
|
||||
String(String),
|
||||
Array(Vec<FuzzValue>),
|
||||
Object(Vec<(String, FuzzValue)>),
|
||||
}
|
||||
|
||||
impl FuzzValue {
|
||||
fn to_json(&self) -> Value {
|
||||
match self {
|
||||
FuzzValue::Null => Value::Null,
|
||||
FuzzValue::Bool(b) => Value::Bool(*b),
|
||||
FuzzValue::Number(n) => json!(n),
|
||||
FuzzValue::String(s) => Value::String(s.clone()),
|
||||
FuzzValue::Array(arr) => {
|
||||
Value::Array(arr.iter().map(|v| v.to_json()).collect())
|
||||
}
|
||||
FuzzValue::Object(obj) => {
|
||||
let map: serde_json::Map<String, Value> = obj
|
||||
.iter()
|
||||
.map(|(k, v)| (k.clone(), v.to_json()))
|
||||
.collect();
|
||||
Value::Object(map)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FuzzArchive {
|
||||
fn generate_archive(&self) -> String {
|
||||
let mut lines = Vec::new();
|
||||
|
||||
// Generate potentially malformed header
|
||||
let mut header_obj = serde_json::Map::new();
|
||||
|
||||
if self.header.has_type_field {
|
||||
header_obj.insert("type".to_string(), json!("@peoplesgrocers/json-archive"));
|
||||
}
|
||||
|
||||
if self.header.has_version_field {
|
||||
header_obj.insert("version".to_string(), json!(self.header.version_value));
|
||||
}
|
||||
|
||||
if self.header.has_created_field {
|
||||
header_obj.insert("created".to_string(), json!("2025-01-01T00:00:00Z"));
|
||||
}
|
||||
|
||||
if self.header.has_initial_field {
|
||||
header_obj.insert("initial".to_string(), self.header.initial_state.to_json());
|
||||
}
|
||||
|
||||
lines.push(serde_json::to_string(&Value::Object(header_obj)).unwrap());
|
||||
|
||||
// Generate events
|
||||
for event in &self.events {
|
||||
let event_json = match event {
|
||||
FuzzEvent::Observe { id, timestamp, change_count } => {
|
||||
json!(["observe", id, timestamp, change_count])
|
||||
}
|
||||
FuzzEvent::Add { path, value, obs_id } => {
|
||||
json!(["add", path, value.to_json(), obs_id])
|
||||
}
|
||||
FuzzEvent::Change { path, old_value, new_value, obs_id } => {
|
||||
json!(["change", path, old_value.to_json(), new_value.to_json(), obs_id])
|
||||
}
|
||||
FuzzEvent::Remove { path, obs_id } => {
|
||||
json!(["remove", path, obs_id])
|
||||
}
|
||||
FuzzEvent::Move { path, moves, obs_id } => {
|
||||
let move_array: Vec<Value> = moves
|
||||
.iter()
|
||||
.map(|(from, to)| json!([from, to]))
|
||||
.collect();
|
||||
json!(["move", path, move_array, obs_id])
|
||||
}
|
||||
FuzzEvent::Snapshot { id, timestamp, state } => {
|
||||
json!(["snapshot", id, timestamp, state.to_json()])
|
||||
}
|
||||
FuzzEvent::InvalidEvent { event_type, extra_fields } => {
|
||||
let mut arr = vec![json!(event_type)];
|
||||
arr.extend(extra_fields.iter().map(|f| f.to_json()));
|
||||
Value::Array(arr)
|
||||
}
|
||||
};
|
||||
|
||||
lines.push(serde_json::to_string(&event_json).unwrap());
|
||||
}
|
||||
|
||||
lines.join("\n")
|
||||
}
|
||||
}
|
||||
|
||||
fuzz_target!(|data: &[u8]| {
|
||||
let mut u = Unstructured::new(data);
|
||||
if let Ok(archive) = FuzzArchive::arbitrary(&mut u) {
|
||||
let content = archive.generate_archive();
|
||||
|
||||
if let Ok(mut temp_file) = NamedTempFile::new() {
|
||||
if temp_file.write_all(content.as_bytes()).is_ok() {
|
||||
// Test both validation modes
|
||||
for mode in [ReadMode::FullValidation, ReadMode::AppendSeek] {
|
||||
if let Ok(reader) = ArchiveReader::new(temp_file.path(), mode) {
|
||||
let result = reader.read(temp_file.path());
|
||||
|
||||
// The operation should never panic
|
||||
// Verify that diagnostics are properly generated for invalid structures
|
||||
if let Ok(read_result) = result {
|
||||
// Basic sanity checks on the result
|
||||
assert!(read_result.observation_count < 10000); // Reasonable upper bound
|
||||
|
||||
// If there are fatal diagnostics, final state should be reasonable
|
||||
if read_result.diagnostics.has_fatal() {
|
||||
// Should still have some state (at least initial or null)
|
||||
let _ = &read_result.final_state;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
640
src/archive.rs
Normal file
640
src/archive.rs
Normal file
|
|
@ -0,0 +1,640 @@
|
|||
// json-archive is a tool for tracking JSON file changes over time
|
||||
// Copyright (C) 2025 Peoples Grocers LLC
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
//
|
||||
// To purchase a license under different terms contact admin@peoplesgrocers.com
|
||||
// To request changes, report bugs, or give user feedback contact
|
||||
// marxism@peoplesgrocers.com
|
||||
//
|
||||
|
||||
use chrono::Utc;
|
||||
use serde_json::Value;
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{BufWriter, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::diagnostics::{Diagnostic, DiagnosticCode, DiagnosticLevel};
|
||||
use crate::diff;
|
||||
use crate::events::{Event, Header, Observation};
|
||||
use crate::reader::{ArchiveReader, ReadMode};
|
||||
|
||||
pub struct ArchiveWriter {
|
||||
writer: BufWriter<File>,
|
||||
observation_count: usize,
|
||||
snapshot_interval: Option<usize>,
|
||||
filename: String,
|
||||
}
|
||||
|
||||
impl ArchiveWriter {
|
||||
pub fn new<P: AsRef<Path>>(
|
||||
path: P,
|
||||
snapshot_interval: Option<usize>,
|
||||
) -> Result<Self, Vec<Diagnostic>> {
|
||||
let filename = path.as_ref().display().to_string();
|
||||
let file = match File::create(&path) {
|
||||
Ok(f) => f,
|
||||
Err(e) => {
|
||||
let diagnostic = Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::PathNotFound,
|
||||
format!("I couldn't create the output file: {}", e)
|
||||
)
|
||||
.with_advice(
|
||||
"Make sure you have write permission in this directory and that the path is valid."
|
||||
.to_string()
|
||||
);
|
||||
return Err(vec![diagnostic]);
|
||||
}
|
||||
};
|
||||
let writer = BufWriter::new(file);
|
||||
|
||||
Ok(Self {
|
||||
writer,
|
||||
observation_count: 0,
|
||||
snapshot_interval,
|
||||
filename,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn new_append<P: AsRef<Path>>(
|
||||
path: P,
|
||||
snapshot_interval: Option<usize>,
|
||||
current_observation_count: usize,
|
||||
) -> Result<Self, Vec<Diagnostic>> {
|
||||
let filename = path.as_ref().display().to_string();
|
||||
let file = match OpenOptions::new().append(true).open(&path) {
|
||||
Ok(f) => f,
|
||||
Err(e) => {
|
||||
let diagnostic = Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::PathNotFound,
|
||||
format!("I couldn't open the archive file for appending: {}", e)
|
||||
)
|
||||
.with_advice(
|
||||
"Make sure the archive file exists and you have write permission."
|
||||
.to_string()
|
||||
);
|
||||
return Err(vec![diagnostic]);
|
||||
}
|
||||
};
|
||||
let writer = BufWriter::new(file);
|
||||
|
||||
Ok(Self {
|
||||
writer,
|
||||
observation_count: current_observation_count,
|
||||
snapshot_interval,
|
||||
filename,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn write_header(&mut self, header: &Header) -> Result<(), Vec<Diagnostic>> {
|
||||
let header_json = match serde_json::to_string(header) {
|
||||
Ok(json) => json,
|
||||
Err(e) => {
|
||||
return Err(vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::InvalidEventJson,
|
||||
format!("I couldn't serialize the header to JSON: {}", e),
|
||||
)
|
||||
.with_location(self.filename.clone(), 1)]);
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(e) = writeln!(self.writer, "{}", header_json) {
|
||||
return Err(vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::PathNotFound,
|
||||
format!("I couldn't write to the output file: {}", e),
|
||||
)
|
||||
.with_location(self.filename.clone(), 1)]);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn write_comment(&mut self, comment: &str) -> Result<(), Vec<Diagnostic>> {
|
||||
if let Err(e) = writeln!(self.writer, "# {}", comment) {
|
||||
return Err(vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::PathNotFound,
|
||||
format!("I couldn't write to the output file: {}", e),
|
||||
)]);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn write_observation(&mut self, observation: Observation) -> Result<(), Vec<Diagnostic>> {
|
||||
let events = observation.to_events();
|
||||
|
||||
for event in events {
|
||||
let event_json = match serde_json::to_string(&event) {
|
||||
Ok(json) => json,
|
||||
Err(e) => {
|
||||
return Err(vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::InvalidEventJson,
|
||||
format!("I couldn't serialize an event to JSON: {}", e),
|
||||
)]);
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(e) = writeln!(self.writer, "{}", event_json) {
|
||||
return Err(vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::PathNotFound,
|
||||
format!("I couldn't write to the output file: {}", e),
|
||||
)]);
|
||||
}
|
||||
}
|
||||
|
||||
self.observation_count += 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn write_snapshot(&mut self, object: &Value) -> Result<(), Vec<Diagnostic>> {
|
||||
let snapshot_id = format!("snapshot-{}", Uuid::new_v4());
|
||||
let snapshot = Event::Snapshot {
|
||||
observation_id: snapshot_id,
|
||||
timestamp: Utc::now(),
|
||||
object: object.clone(),
|
||||
};
|
||||
|
||||
let event_json = match serde_json::to_string(&snapshot) {
|
||||
Ok(json) => json,
|
||||
Err(e) => {
|
||||
return Err(vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::InvalidEventJson,
|
||||
format!("I couldn't serialize the snapshot to JSON: {}", e),
|
||||
)]);
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(e) = writeln!(self.writer, "{}", event_json) {
|
||||
return Err(vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::PathNotFound,
|
||||
format!("I couldn't write to the output file: {}", e),
|
||||
)]);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn should_write_snapshot(&self) -> bool {
|
||||
if let Some(interval) = self.snapshot_interval {
|
||||
self.observation_count > 0 && self.observation_count % interval == 0
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub fn finish(mut self) -> Result<(), Vec<Diagnostic>> {
|
||||
if let Err(e) = self.writer.flush() {
|
||||
return Err(vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::PathNotFound,
|
||||
format!("I couldn't flush the output file: {}", e),
|
||||
)]);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ArchiveBuilder {
|
||||
initial_state: Option<Value>,
|
||||
current_state: Value,
|
||||
source: Option<String>,
|
||||
snapshot_interval: Option<usize>,
|
||||
}
|
||||
|
||||
impl ArchiveBuilder {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
initial_state: None,
|
||||
current_state: Value::Null,
|
||||
source: None,
|
||||
snapshot_interval: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_source(mut self, source: String) -> Self {
|
||||
self.source = Some(source);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_snapshot_interval(mut self, interval: usize) -> Self {
|
||||
self.snapshot_interval = Some(interval);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn add_state(&mut self, state: Value) -> Option<Observation> {
|
||||
if self.initial_state.is_none() {
|
||||
self.initial_state = Some(state.clone());
|
||||
self.current_state = state;
|
||||
return None;
|
||||
}
|
||||
|
||||
let observation_id = format!("obs-{}", Uuid::new_v4());
|
||||
let timestamp = Utc::now();
|
||||
|
||||
let diff_result: Vec<Event> = diff::diff(&self.current_state, &state, "", &observation_id);
|
||||
self.current_state = state;
|
||||
|
||||
let mut observation = Observation::new(observation_id, timestamp);
|
||||
for event in diff_result {
|
||||
observation.add_event(event);
|
||||
}
|
||||
|
||||
Some(observation)
|
||||
}
|
||||
|
||||
pub fn build<P: AsRef<Path>>(self, output_path: P) -> Result<(), Vec<Diagnostic>> {
|
||||
if self.initial_state.is_none() {
|
||||
return Err(vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::MissingHeaderField,
|
||||
"I can't build an archive without any initial state.".to_string(),
|
||||
)]);
|
||||
}
|
||||
|
||||
let header = Header::new(self.initial_state.unwrap(), self.source);
|
||||
|
||||
let mut writer = ArchiveWriter::new(output_path, self.snapshot_interval)?;
|
||||
writer.write_header(&header)?;
|
||||
writer.finish()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn get_initial_state(&self) -> Option<&Value> {
|
||||
self.initial_state.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate default output filename from input filename
|
||||
pub fn default_output_filename<P: AsRef<Path>>(input_path: P) -> PathBuf {
|
||||
let path = input_path.as_ref();
|
||||
let mut output = path.to_path_buf();
|
||||
|
||||
// If it already ends with .json.archive, don't modify it
|
||||
if let Some(filename) = path.file_name() {
|
||||
if let Some(filename_str) = filename.to_str() {
|
||||
if filename_str.ends_with(".json.archive") {
|
||||
return output;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add .json.archive extension
|
||||
if let Some(extension) = path.extension() {
|
||||
if extension == "json" {
|
||||
// Replace .json with .json.archive
|
||||
output.set_extension("json.archive");
|
||||
} else {
|
||||
// Append .json.archive to whatever extension exists
|
||||
let new_extension = format!("{}.json.archive", extension.to_string_lossy());
|
||||
output.set_extension(new_extension);
|
||||
}
|
||||
} else {
|
||||
// No extension, just add .json.archive
|
||||
output.set_extension("json.archive");
|
||||
}
|
||||
|
||||
output
|
||||
}
|
||||
|
||||
pub fn create_archive_from_files<P: AsRef<Path>>(
|
||||
input_files: &[P],
|
||||
output_path: P,
|
||||
source: Option<String>,
|
||||
snapshot_interval: Option<usize>,
|
||||
) -> Result<(), Vec<Diagnostic>> {
|
||||
let mut builder = ArchiveBuilder::new();
|
||||
if let Some(source) = source {
|
||||
builder = builder.with_source(source);
|
||||
}
|
||||
if let Some(interval) = snapshot_interval {
|
||||
builder = builder.with_snapshot_interval(interval);
|
||||
}
|
||||
|
||||
let first_content = std::fs::read_to_string(&input_files[0]).map_err(|e| {
|
||||
vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::PathNotFound,
|
||||
format!("I couldn't read the first input file: {}", e),
|
||||
)]
|
||||
})?;
|
||||
|
||||
let first_state: Value = serde_json::from_str(&first_content).map_err(|e| {
|
||||
vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::InvalidEventJson,
|
||||
format!("I couldn't parse the first input file as JSON: {}", e),
|
||||
)
|
||||
.with_advice("Make sure the file contains valid JSON.".to_string())]
|
||||
})?;
|
||||
|
||||
let _ = builder.add_state(first_state.clone());
|
||||
|
||||
let header = Header::new(first_state, builder.source.clone());
|
||||
let mut writer = ArchiveWriter::new(&output_path, builder.snapshot_interval)?;
|
||||
writer.write_header(&header)?;
|
||||
|
||||
for file_path in input_files[1..].iter() {
|
||||
writer.write_comment(&format!("Processing file: {:?}", file_path.as_ref()))?;
|
||||
|
||||
let content = std::fs::read_to_string(file_path).map_err(|e| {
|
||||
vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::PathNotFound,
|
||||
format!("I couldn't read the input file: {}", e),
|
||||
)]
|
||||
})?;
|
||||
|
||||
let state: Value = serde_json::from_str(&content).map_err(|e| {
|
||||
vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::InvalidEventJson,
|
||||
format!("I couldn't parse the input file as JSON: {}", e),
|
||||
)
|
||||
.with_advice("Make sure the file contains valid JSON.".to_string())]
|
||||
})?;
|
||||
|
||||
if let Some(observation) = builder.add_state(state.clone()) {
|
||||
writer.write_observation(observation)?;
|
||||
|
||||
if writer.should_write_snapshot() {
|
||||
writer.write_snapshot(&state)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
writer.finish()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn append_to_archive<P: AsRef<Path>, Q: AsRef<Path>>(
|
||||
archive_path: P,
|
||||
new_files: &[Q],
|
||||
output_path: P,
|
||||
source: Option<String>,
|
||||
snapshot_interval: Option<usize>,
|
||||
) -> Vec<Diagnostic> {
|
||||
// Read the existing archive to get the final state
|
||||
let reader = match ArchiveReader::new(&archive_path, ReadMode::AppendSeek) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
return vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::PathNotFound,
|
||||
format!("I couldn't open the archive for reading: {}", e),
|
||||
)];
|
||||
}
|
||||
};
|
||||
|
||||
let read_result = match reader.read(&archive_path) {
|
||||
Ok(result) => result,
|
||||
Err(e) => {
|
||||
return vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::PathNotFound,
|
||||
format!("I couldn't read the archive: {}", e),
|
||||
)];
|
||||
}
|
||||
};
|
||||
|
||||
// Check for fatal diagnostics in the archive
|
||||
if read_result.diagnostics.has_fatal() {
|
||||
let mut diagnostics = vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::InvalidEventJson,
|
||||
"The existing archive contains fatal errors. Cannot append to a corrupt archive.".to_string(),
|
||||
)];
|
||||
diagnostics.extend(read_result.diagnostics.into_diagnostics());
|
||||
return diagnostics;
|
||||
}
|
||||
|
||||
// If output path is different from archive path, copy the archive first
|
||||
if archive_path.as_ref() != output_path.as_ref() {
|
||||
if let Err(e) = std::fs::copy(&archive_path, &output_path) {
|
||||
return vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::PathNotFound,
|
||||
format!("I couldn't copy the archive to the output location: {}", e),
|
||||
)];
|
||||
}
|
||||
}
|
||||
|
||||
// Create an append writer
|
||||
let mut writer = match ArchiveWriter::new_append(&output_path, snapshot_interval, read_result.observation_count) {
|
||||
Ok(w) => w,
|
||||
Err(diagnostics) => return diagnostics,
|
||||
};
|
||||
|
||||
// Create a builder to track state changes
|
||||
let mut builder = ArchiveBuilder::new();
|
||||
if let Some(source) = source {
|
||||
builder = builder.with_source(source);
|
||||
}
|
||||
if let Some(interval) = snapshot_interval {
|
||||
builder = builder.with_snapshot_interval(interval);
|
||||
}
|
||||
|
||||
// Initialize builder with the final state from the archive
|
||||
let current_state = read_result.final_state;
|
||||
builder.current_state = current_state.clone();
|
||||
builder.initial_state = Some(current_state.clone());
|
||||
|
||||
// Process each new file
|
||||
for file_path in new_files.iter() {
|
||||
if let Err(diagnostics) = writer.write_comment(&format!("Processing file: {:?}", file_path.as_ref())) {
|
||||
return diagnostics;
|
||||
}
|
||||
|
||||
let content = match std::fs::read_to_string(file_path) {
|
||||
Ok(content) => content,
|
||||
Err(e) => {
|
||||
return vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::PathNotFound,
|
||||
format!("I couldn't read the input file: {}", e),
|
||||
)];
|
||||
}
|
||||
};
|
||||
|
||||
let state: Value = match serde_json::from_str(&content) {
|
||||
Ok(state) => state,
|
||||
Err(e) => {
|
||||
return vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::InvalidEventJson,
|
||||
format!("I couldn't parse the input file as JSON: {}", e),
|
||||
)
|
||||
.with_advice("Make sure the file contains valid JSON.".to_string())];
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(observation) = builder.add_state(state.clone()) {
|
||||
if let Err(diagnostics) = writer.write_observation(observation) {
|
||||
return diagnostics;
|
||||
}
|
||||
|
||||
if writer.should_write_snapshot() {
|
||||
if let Err(diagnostics) = writer.write_snapshot(&state) {
|
||||
return diagnostics;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Finish writing
|
||||
match writer.finish() {
|
||||
Ok(()) => Vec::new(),
|
||||
Err(diagnostics) => diagnostics,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
use std::io::Write;
|
||||
use tempfile::NamedTempFile;
|
||||
|
||||
#[test]
|
||||
fn test_archive_writer_header() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let temp_file = NamedTempFile::new()?;
|
||||
let header = Header::new(json!({"test": "value"}), Some("test-source".to_string()));
|
||||
|
||||
{
|
||||
let mut writer = ArchiveWriter::new(temp_file.path(), None)
|
||||
.map_err(|_| "Failed to create writer")?;
|
||||
writer
|
||||
.write_header(&header)
|
||||
.map_err(|_| "Failed to write header")?;
|
||||
writer.finish().map_err(|_| "Failed to finish")?;
|
||||
}
|
||||
|
||||
let content = std::fs::read_to_string(temp_file.path())?;
|
||||
let lines: Vec<&str> = content.lines().collect();
|
||||
assert_eq!(lines.len(), 1);
|
||||
|
||||
let parsed_header: Header = serde_json::from_str(lines[0])?;
|
||||
assert_eq!(parsed_header.file_type, "@peoplesgrocers/json-archive");
|
||||
assert_eq!(parsed_header.version, 1);
|
||||
assert_eq!(parsed_header.initial, json!({"test": "value"}));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_archive_builder() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut builder = ArchiveBuilder::new();
|
||||
|
||||
// First state becomes initial
|
||||
let result = builder.add_state(json!({"count": 0}));
|
||||
assert!(result.is_none());
|
||||
|
||||
// Second state generates observation
|
||||
let observation = builder
|
||||
.add_state(json!({"count": 1}))
|
||||
.expect("Should generate observation");
|
||||
assert!(!observation.events.is_empty());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_create_archive_from_files() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// Create temporary input files
|
||||
let mut file1 = NamedTempFile::new()?;
|
||||
let mut file2 = NamedTempFile::new()?;
|
||||
let output_file = NamedTempFile::new()?;
|
||||
|
||||
writeln!(file1, r#"{{"count": 0, "name": "test"}}"#)?;
|
||||
writeln!(file2, r#"{{"count": 1, "name": "test"}}"#)?;
|
||||
|
||||
let input_files = vec![file1.path(), file2.path()];
|
||||
|
||||
create_archive_from_files(
|
||||
&input_files,
|
||||
output_file.path(),
|
||||
Some("test-source".to_string()),
|
||||
None,
|
||||
)
|
||||
.map_err(|_| "Failed to create archive")?;
|
||||
|
||||
let content = std::fs::read_to_string(output_file.path())?;
|
||||
let lines: Vec<&str> = content.lines().collect();
|
||||
|
||||
assert!(lines.len() >= 2); // At least header + comment + observe + change events
|
||||
|
||||
// First line should be header
|
||||
let header: Header = serde_json::from_str(lines[0])?;
|
||||
assert_eq!(header.file_type, "@peoplesgrocers/json-archive");
|
||||
assert_eq!(header.version, 1);
|
||||
assert_eq!(header.initial, json!({"count": 0, "name": "test"}));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_snapshot_interval() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let temp_file = NamedTempFile::new()?;
|
||||
let mut writer =
|
||||
ArchiveWriter::new(temp_file.path(), Some(2)).map_err(|_| "Failed to create writer")?;
|
||||
|
||||
assert!(!writer.should_write_snapshot()); // No observations yet
|
||||
|
||||
let obs1 = Observation::new("obs-1".to_string(), Utc::now());
|
||||
writer
|
||||
.write_observation(obs1)
|
||||
.map_err(|_| "Failed to write observation")?;
|
||||
assert!(!writer.should_write_snapshot()); // 1 observation, interval is 2
|
||||
|
||||
let obs2 = Observation::new("obs-2".to_string(), Utc::now());
|
||||
writer
|
||||
.write_observation(obs2)
|
||||
.map_err(|_| "Failed to write observation")?;
|
||||
assert!(writer.should_write_snapshot()); // 2 observations, should snapshot
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_default_output_filename() {
|
||||
assert_eq!(
|
||||
default_output_filename("test.json"),
|
||||
PathBuf::from("test.json.archive")
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
default_output_filename("test.txt"),
|
||||
PathBuf::from("test.txt.json.archive")
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
default_output_filename("test"),
|
||||
PathBuf::from("test.json.archive")
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
default_output_filename("test.json.archive"),
|
||||
PathBuf::from("test.json.archive")
|
||||
);
|
||||
}
|
||||
}
|
||||
410
src/cmd/info.rs
Normal file
410
src/cmd/info.rs
Normal file
|
|
@ -0,0 +1,410 @@
|
|||
// json-archive is a tool for tracking JSON file changes over time
|
||||
// Copyright (C) 2025 Peoples Grocers LLC
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
//
|
||||
// To purchase a license under different terms contact admin@peoplesgrocers.com
|
||||
// To request changes, report bugs, or give user feedback contact
|
||||
// marxism@peoplesgrocers.com
|
||||
//
|
||||
|
||||
use crate::flags;
|
||||
use chrono::{DateTime, Utc};
|
||||
use json_archive::{Diagnostic, DiagnosticCode, DiagnosticLevel};
|
||||
use serde::Serialize;
|
||||
use serde_json::Value;
|
||||
use std::fs::File;
|
||||
use std::io::{BufRead, BufReader};
|
||||
use std::path::Path;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ObservationInfo {
|
||||
id: String,
|
||||
timestamp: DateTime<Utc>,
|
||||
created: DateTime<Utc>, // For initial state, this is the archive creation time
|
||||
change_count: usize,
|
||||
json_size: usize,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct JsonObservation {
|
||||
index: usize,
|
||||
id: String,
|
||||
timestamp: String,
|
||||
changes: usize,
|
||||
json_size: usize,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct JsonInfoOutput {
|
||||
archive: String,
|
||||
created: String,
|
||||
file_size: u64,
|
||||
snapshot_count: usize,
|
||||
observations: Vec<JsonObservation>,
|
||||
}
|
||||
|
||||
pub fn run(flags: &flags::Info) -> Vec<Diagnostic> {
|
||||
if !flags.file.exists() {
|
||||
return vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::PathNotFound,
|
||||
format!("I couldn't find the archive file: {}", flags.file.display()),
|
||||
)
|
||||
.with_advice(
|
||||
"Make sure the file path is correct and the file exists. \
|
||||
Check for typos in the filename."
|
||||
.to_string(),
|
||||
)];
|
||||
}
|
||||
|
||||
let observations = match collect_observations(&flags.file) {
|
||||
Ok(obs) => obs,
|
||||
Err(diagnostics) => return diagnostics,
|
||||
};
|
||||
|
||||
let file_size = match std::fs::metadata(&flags.file) {
|
||||
Ok(metadata) => metadata.len(),
|
||||
Err(_) => 0,
|
||||
};
|
||||
|
||||
let snapshot_count = count_snapshots(&flags.file).unwrap_or(0);
|
||||
|
||||
// Check output format
|
||||
let is_json_output = flags.output.as_ref().map(|s| s == "json").unwrap_or(false);
|
||||
|
||||
if is_json_output {
|
||||
// JSON output mode
|
||||
if observations.is_empty() {
|
||||
let empty_output = JsonInfoOutput {
|
||||
archive: flags.file.display().to_string(),
|
||||
created: "".to_string(),
|
||||
file_size,
|
||||
snapshot_count,
|
||||
observations: Vec::new(),
|
||||
};
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::to_string_pretty(&empty_output).unwrap_or_default()
|
||||
);
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let json_observations: Vec<JsonObservation> = observations
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, obs)| JsonObservation {
|
||||
index,
|
||||
id: if index == 0 {
|
||||
"initial".to_string()
|
||||
} else {
|
||||
obs.id.clone()
|
||||
},
|
||||
timestamp: obs.timestamp.to_rfc3339(),
|
||||
changes: obs.change_count,
|
||||
json_size: obs.json_size,
|
||||
})
|
||||
.collect();
|
||||
|
||||
let json_output = JsonInfoOutput {
|
||||
archive: flags.file.display().to_string(),
|
||||
created: observations[0].created.to_rfc3339(),
|
||||
file_size,
|
||||
snapshot_count,
|
||||
observations: json_observations,
|
||||
};
|
||||
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::to_string_pretty(&json_output).unwrap_or_default()
|
||||
);
|
||||
} else {
|
||||
// Human-readable output mode
|
||||
println!("Archive: {}", flags.file.display());
|
||||
|
||||
if observations.is_empty() {
|
||||
println!("No observations found");
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let first_timestamp = &observations[0].created;
|
||||
let last_timestamp = if observations.len() > 1 {
|
||||
&observations.last().unwrap().timestamp
|
||||
} else {
|
||||
first_timestamp
|
||||
};
|
||||
|
||||
println!("Created: {}", format_timestamp(first_timestamp));
|
||||
println!();
|
||||
|
||||
if observations.len() == 1 {
|
||||
println!("1 observation on {}", format_timestamp(first_timestamp));
|
||||
} else {
|
||||
println!(
|
||||
"{} observations from {} to {}",
|
||||
observations.len(),
|
||||
format_timestamp(first_timestamp),
|
||||
format_timestamp(last_timestamp)
|
||||
);
|
||||
}
|
||||
println!();
|
||||
|
||||
// Table header
|
||||
println!(" # Observation ID Date & Time Changes JSON Size");
|
||||
println!("────────────────────────────────────────────────────────────────────────────────────────");
|
||||
|
||||
for (index, obs) in observations.iter().enumerate() {
|
||||
let id_display = if index == 0 {
|
||||
"(initial)".to_string()
|
||||
} else {
|
||||
truncate_id(&obs.id)
|
||||
};
|
||||
|
||||
let changes_display = if index == 0 {
|
||||
"-".to_string()
|
||||
} else {
|
||||
obs.change_count.to_string()
|
||||
};
|
||||
|
||||
println!(
|
||||
" {:2} {:32} {:25} {:7} {:9}",
|
||||
index,
|
||||
id_display,
|
||||
format_timestamp(&obs.timestamp),
|
||||
changes_display,
|
||||
format_size(obs.json_size as u64)
|
||||
);
|
||||
}
|
||||
|
||||
println!();
|
||||
let snapshot_text = if snapshot_count == 0 {
|
||||
"0 snapshots".to_string()
|
||||
} else {
|
||||
format!("{} snapshots", snapshot_count)
|
||||
};
|
||||
println!(
|
||||
"Total archive size: {} ({})",
|
||||
format_size(file_size),
|
||||
snapshot_text
|
||||
);
|
||||
|
||||
// Add usage instructions
|
||||
println!();
|
||||
println!("To get the JSON value at a specific observation:");
|
||||
println!(" json-archive state --index <#> {}", flags.file.display());
|
||||
println!(
|
||||
" json-archive state --id <observation-id> {}",
|
||||
flags.file.display()
|
||||
);
|
||||
println!();
|
||||
println!("Examples:");
|
||||
println!(
|
||||
" json-archive state --index 0 {} # Get initial state",
|
||||
flags.file.display()
|
||||
);
|
||||
println!(
|
||||
" json-archive state --index 2 {} # Get state after observation 2",
|
||||
flags.file.display()
|
||||
);
|
||||
}
|
||||
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
fn collect_observations(file_path: &Path) -> Result<Vec<ObservationInfo>, Vec<Diagnostic>> {
|
||||
let file = match File::open(file_path) {
|
||||
Ok(f) => f,
|
||||
Err(e) => {
|
||||
return Err(vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::PathNotFound,
|
||||
format!("I couldn't open the archive file: {}", e),
|
||||
)]);
|
||||
}
|
||||
};
|
||||
|
||||
let reader = BufReader::new(file);
|
||||
let mut lines = reader.lines();
|
||||
let mut observations = Vec::new();
|
||||
|
||||
// Parse header
|
||||
let header_line = match lines.next() {
|
||||
Some(Ok(line)) => line,
|
||||
_ => {
|
||||
return Err(vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::EmptyFile,
|
||||
"Archive file is empty or unreadable".to_string(),
|
||||
)]);
|
||||
}
|
||||
};
|
||||
|
||||
let header: Value = match serde_json::from_str(&header_line) {
|
||||
Ok(h) => h,
|
||||
Err(e) => {
|
||||
return Err(vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::MissingHeader,
|
||||
format!("I couldn't parse the header: {}", e),
|
||||
)]);
|
||||
}
|
||||
};
|
||||
|
||||
let created_str = header["created"].as_str().unwrap_or("");
|
||||
let created: DateTime<Utc> = match created_str.parse() {
|
||||
Ok(dt) => dt,
|
||||
Err(_) => Utc::now(),
|
||||
};
|
||||
|
||||
let initial_state = header["initial"].clone();
|
||||
let initial_size = serde_json::to_string(&initial_state)
|
||||
.unwrap_or_default()
|
||||
.len();
|
||||
|
||||
// Add initial state as observation 0
|
||||
observations.push(ObservationInfo {
|
||||
id: "initial".to_string(),
|
||||
timestamp: created,
|
||||
created,
|
||||
change_count: 0,
|
||||
json_size: initial_size,
|
||||
});
|
||||
|
||||
let mut current_state = initial_state;
|
||||
|
||||
// Parse events
|
||||
for line in lines {
|
||||
let line = match line {
|
||||
Ok(l) => l,
|
||||
Err(_) => continue,
|
||||
};
|
||||
|
||||
if line.trim().starts_with('#') || line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let event: Value = match serde_json::from_str(&line) {
|
||||
Ok(e) => e,
|
||||
Err(_) => continue,
|
||||
};
|
||||
|
||||
if let Some(arr) = event.as_array() {
|
||||
if arr.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let event_type = arr[0].as_str().unwrap_or("");
|
||||
|
||||
if event_type == "observe" && arr.len() >= 4 {
|
||||
let obs_id = arr[1].as_str().unwrap_or("").to_string();
|
||||
let timestamp_str = arr[2].as_str().unwrap_or("");
|
||||
let change_count = arr[3].as_u64().unwrap_or(0) as usize;
|
||||
|
||||
let timestamp: DateTime<Utc> = match timestamp_str.parse() {
|
||||
Ok(dt) => dt,
|
||||
Err(_) => continue,
|
||||
};
|
||||
|
||||
observations.push(ObservationInfo {
|
||||
id: obs_id,
|
||||
timestamp,
|
||||
created,
|
||||
change_count,
|
||||
json_size: 0, // Will be calculated after applying events
|
||||
});
|
||||
} else {
|
||||
// Apply the event to current_state for size calculation
|
||||
apply_event_to_state(&mut current_state, &arr);
|
||||
|
||||
// Update the JSON size of the last observation
|
||||
if let Some(last_obs) = observations.last_mut() {
|
||||
last_obs.json_size = serde_json::to_string(¤t_state)
|
||||
.unwrap_or_default()
|
||||
.len();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(observations)
|
||||
}
|
||||
|
||||
fn apply_event_to_state(state: &mut Value, event: &[Value]) {
|
||||
if event.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let event_type = event[0].as_str().unwrap_or("");
|
||||
|
||||
match event_type {
|
||||
"add" if event.len() >= 3 => {
|
||||
let path = event[1].as_str().unwrap_or("");
|
||||
let value = event[2].clone();
|
||||
if let Ok(pointer) = json_archive::pointer::JsonPointer::new(path) {
|
||||
let _ = pointer.set(state, value);
|
||||
}
|
||||
}
|
||||
"change" if event.len() >= 3 => {
|
||||
let path = event[1].as_str().unwrap_or("");
|
||||
let value = event[2].clone();
|
||||
if let Ok(pointer) = json_archive::pointer::JsonPointer::new(path) {
|
||||
let _ = pointer.set(state, value);
|
||||
}
|
||||
}
|
||||
"remove" if event.len() >= 2 => {
|
||||
let path = event[1].as_str().unwrap_or("");
|
||||
if let Ok(pointer) = json_archive::pointer::JsonPointer::new(path) {
|
||||
let _ = pointer.remove(state);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn format_timestamp(dt: &DateTime<Utc>) -> String {
|
||||
dt.format("%a %H:%M:%S %d-%b-%Y").to_string()
|
||||
}
|
||||
|
||||
fn truncate_id(id: &str) -> String {
|
||||
if id.len() > 20 {
|
||||
format!("{}...", &id[..20])
|
||||
} else {
|
||||
id.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
fn format_size(bytes: u64) -> String {
|
||||
if bytes < 1024 {
|
||||
format!("{} bytes", bytes)
|
||||
} else if bytes < 1024 * 1024 {
|
||||
format!("{:.1} KB", bytes as f64 / 1024.0)
|
||||
} else {
|
||||
format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0))
|
||||
}
|
||||
}
|
||||
|
||||
fn count_snapshots(file_path: &Path) -> Result<usize, std::io::Error> {
|
||||
let file = File::open(file_path)?;
|
||||
let reader = BufReader::new(file);
|
||||
let mut count = 0;
|
||||
|
||||
for line in reader.lines() {
|
||||
let line = line?;
|
||||
if line.trim().starts_with('[') && line.contains("\"snapshot\"") {
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(count)
|
||||
}
|
||||
23
src/cmd/mod.rs
Normal file
23
src/cmd/mod.rs
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
// json-archive is a tool for tracking JSON file changes over time
|
||||
// Copyright (C) 2025 Peoples Grocers LLC
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
//
|
||||
// To purchase a license under different terms contact admin@peoplesgrocers.com
|
||||
// To request changes, report bugs, or give user feedback contact
|
||||
// marxism@peoplesgrocers.com
|
||||
//
|
||||
|
||||
pub mod info;
|
||||
pub mod state;
|
||||
506
src/cmd/state.rs
Normal file
506
src/cmd/state.rs
Normal file
|
|
@ -0,0 +1,506 @@
|
|||
// json-archive is a tool for tracking JSON file changes over time
|
||||
// Copyright (C) 2025 Peoples Grocers LLC
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
//
|
||||
// To purchase a license under different terms contact admin@peoplesgrocers.com
|
||||
// To request changes, report bugs, or give user feedback contact
|
||||
// marxism@peoplesgrocers.com
|
||||
//
|
||||
|
||||
use crate::flags;
|
||||
use chrono::{DateTime, Utc};
|
||||
use json_archive::reader::{ArchiveReader, ReadMode};
|
||||
use json_archive::{Diagnostic, DiagnosticCode, DiagnosticLevel};
|
||||
use serde_json::Value;
|
||||
use std::path::Path;
|
||||
|
||||
#[derive(Debug)]
|
||||
enum AccessMethod {
|
||||
Id(String),
|
||||
Index(usize),
|
||||
AsOf(DateTime<Utc>),
|
||||
RightBefore(DateTime<Utc>),
|
||||
After(DateTime<Utc>),
|
||||
Latest,
|
||||
}
|
||||
|
||||
pub fn run(flags: &flags::State) -> Vec<Diagnostic> {
|
||||
if !flags.file.exists() {
|
||||
return vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::PathNotFound,
|
||||
format!("I couldn't find the archive file: {}", flags.file.display()),
|
||||
)
|
||||
.with_advice(
|
||||
"Make sure the file path is correct and the file exists. \
|
||||
Check for typos in the filename."
|
||||
.to_string(),
|
||||
)];
|
||||
}
|
||||
|
||||
// Parse and validate flags - ensure only one access method is specified
|
||||
let access_method = match parse_access_method(flags) {
|
||||
Ok(method) => method,
|
||||
Err(diagnostic) => return vec![diagnostic],
|
||||
};
|
||||
|
||||
// Read the archive using the existing reader
|
||||
let reader = match ArchiveReader::new(&flags.file, ReadMode::FullValidation) {
|
||||
Ok(reader) => reader,
|
||||
Err(e) => {
|
||||
return vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::PathNotFound,
|
||||
format!("I couldn't open the archive file: {}", e),
|
||||
)];
|
||||
}
|
||||
};
|
||||
|
||||
let result = match reader.read(&flags.file) {
|
||||
Ok(result) => result,
|
||||
Err(e) => {
|
||||
return vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::PathNotFound,
|
||||
format!("I couldn't read the archive file: {}", e),
|
||||
)];
|
||||
}
|
||||
};
|
||||
|
||||
// If there are fatal diagnostics, return them
|
||||
if result.diagnostics.has_fatal() {
|
||||
return result.diagnostics.into_diagnostics();
|
||||
}
|
||||
|
||||
// For non-latest access methods, we need to collect observations and find the target
|
||||
let target_state = match access_method {
|
||||
AccessMethod::Latest => {
|
||||
// The reader already gives us the final state after all observations
|
||||
result.final_state
|
||||
}
|
||||
_ => {
|
||||
// We need to collect observations and replay to the target
|
||||
match find_and_replay_to_target(&flags.file, &access_method) {
|
||||
Ok(state) => state,
|
||||
Err(diagnostics) => return diagnostics,
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Output the JSON state
|
||||
match serde_json::to_string_pretty(&target_state) {
|
||||
Ok(json) => println!("{}", json),
|
||||
Err(e) => {
|
||||
return vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::InvalidEventJson,
|
||||
format!("I couldn't serialize the state to JSON: {}", e),
|
||||
)];
|
||||
}
|
||||
}
|
||||
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
fn parse_access_method(flags: &flags::State) -> Result<AccessMethod, Diagnostic> {
|
||||
let mut methods = Vec::new();
|
||||
|
||||
if let Some(ref id) = flags.id {
|
||||
methods.push(AccessMethod::Id(id.clone()));
|
||||
}
|
||||
|
||||
if let Some(index) = flags.index {
|
||||
methods.push(AccessMethod::Index(index));
|
||||
}
|
||||
|
||||
if let Some(ref as_of_str) = flags.as_of {
|
||||
match as_of_str.parse::<DateTime<Utc>>() {
|
||||
Ok(dt) => methods.push(AccessMethod::AsOf(dt)),
|
||||
Err(_) => {
|
||||
return Err(Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::InvalidTimestamp,
|
||||
format!("I couldn't parse the timestamp '{}'. Please use ISO-8601 format like '2025-01-15T10:05:00Z'", as_of_str)
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ref right_before_str) = flags.before {
|
||||
match right_before_str.parse::<DateTime<Utc>>() {
|
||||
Ok(dt) => methods.push(AccessMethod::RightBefore(dt)),
|
||||
Err(_) => {
|
||||
return Err(Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::InvalidTimestamp,
|
||||
format!("I couldn't parse the timestamp '{}'. Please use ISO-8601 format like '2025-01-15T10:05:00Z'", right_before_str)
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ref after_str) = flags.after {
|
||||
match after_str.parse::<DateTime<Utc>>() {
|
||||
Ok(dt) => methods.push(AccessMethod::After(dt)),
|
||||
Err(_) => {
|
||||
return Err(Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::InvalidTimestamp,
|
||||
format!("I couldn't parse the timestamp '{}'. Please use ISO-8601 format like '2025-01-15T10:05:00Z'", after_str)
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if flags.latest.unwrap_or(false) {
|
||||
methods.push(AccessMethod::Latest);
|
||||
}
|
||||
|
||||
match methods.len() {
|
||||
0 => Ok(AccessMethod::Latest), // Default to latest if no flags specified
|
||||
1 => Ok(methods.into_iter().next().unwrap()),
|
||||
_ => Err(Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::WrongFieldCount,
|
||||
"Please specify only one access method (--id, --index, --as-of, --right-before, --after, or --latest)".to_string()
|
||||
).with_advice(
|
||||
"Examples:\n\
|
||||
json-archive state --id obs-123 file.archive\n\
|
||||
json-archive state --index 2 file.archive\n\
|
||||
json-archive state --as-of \"2025-01-15T10:05:00Z\" file.archive"
|
||||
.to_string()
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn find_and_replay_to_target(
|
||||
file_path: &Path,
|
||||
access_method: &AccessMethod,
|
||||
) -> Result<Value, Vec<Diagnostic>> {
|
||||
// We need to collect observations with full details to support all access methods
|
||||
let observations = collect_observations_with_events(file_path)?;
|
||||
|
||||
if observations.is_empty() {
|
||||
return Err(vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::EmptyFile,
|
||||
"No observations found in the archive".to_string(),
|
||||
)]);
|
||||
}
|
||||
|
||||
// Find the target observation based on access method
|
||||
let target_observation = match access_method {
|
||||
AccessMethod::Id(id) => observations
|
||||
.iter()
|
||||
.find(|obs| obs.id == *id)
|
||||
.ok_or_else(|| {
|
||||
vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::NonExistentObservationId,
|
||||
format!("I couldn't find an observation with ID '{}'", id),
|
||||
)
|
||||
.with_advice(
|
||||
"Use 'json-archive info' to see available observation IDs".to_string(),
|
||||
)]
|
||||
})?,
|
||||
AccessMethod::Index(index) => {
|
||||
if *index >= observations.len() {
|
||||
return Err(vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::ArrayIndexOutOfBounds,
|
||||
format!(
|
||||
"Index {} is out of bounds. The archive has {} observations (0-{})",
|
||||
index,
|
||||
observations.len(),
|
||||
observations.len() - 1
|
||||
),
|
||||
)
|
||||
.with_advice(
|
||||
"Use 'json-archive info' to see available observation indices".to_string(),
|
||||
)]);
|
||||
}
|
||||
&observations[*index]
|
||||
}
|
||||
AccessMethod::AsOf(timestamp) => {
|
||||
// Find most recent observation with timestamp <= given timestamp
|
||||
observations
|
||||
.iter()
|
||||
.filter(|obs| obs.timestamp <= *timestamp)
|
||||
.max_by_key(|obs| obs.timestamp)
|
||||
.ok_or_else(|| {
|
||||
vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::PathNotFound,
|
||||
format!(
|
||||
"No observations found as of {}",
|
||||
timestamp.format("%Y-%m-%d %H:%M:%S UTC")
|
||||
),
|
||||
)
|
||||
.with_advice(
|
||||
"Try using --after to find the first observation after this time"
|
||||
.to_string(),
|
||||
)]
|
||||
})?
|
||||
}
|
||||
AccessMethod::RightBefore(timestamp) => {
|
||||
// Find most recent observation with timestamp < given timestamp (strictly before)
|
||||
observations
|
||||
.iter()
|
||||
.filter(|obs| obs.timestamp < *timestamp)
|
||||
.max_by_key(|obs| obs.timestamp)
|
||||
.ok_or_else(|| {
|
||||
vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::PathNotFound,
|
||||
format!(
|
||||
"No observations found before {}",
|
||||
timestamp.format("%Y-%m-%d %H:%M:%S UTC")
|
||||
),
|
||||
)
|
||||
.with_advice(
|
||||
"Try using --as-of to include observations at exactly this time"
|
||||
.to_string(),
|
||||
)]
|
||||
})?
|
||||
}
|
||||
AccessMethod::After(timestamp) => {
|
||||
// Find earliest observation with timestamp > given timestamp
|
||||
observations.iter()
|
||||
.filter(|obs| obs.timestamp > *timestamp)
|
||||
.min_by_key(|obs| obs.timestamp)
|
||||
.ok_or_else(|| vec![
|
||||
Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::PathNotFound,
|
||||
format!("No observations found after {}", timestamp.format("%Y-%m-%d %H:%M:%S UTC"))
|
||||
)
|
||||
.with_advice("Try using --as-of to find the most recent observation before or at this time".to_string())
|
||||
])?
|
||||
}
|
||||
AccessMethod::Latest => {
|
||||
// Find observation with latest timestamp
|
||||
observations.iter().max_by_key(|obs| obs.timestamp).unwrap() // Safe because we checked observations is not empty
|
||||
}
|
||||
};
|
||||
|
||||
// Now replay events from initial state up to and including the target observation
|
||||
Ok(target_observation.final_state.clone())
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ObservationWithEvents {
|
||||
id: String,
|
||||
timestamp: DateTime<Utc>,
|
||||
final_state: Value,
|
||||
}
|
||||
|
||||
fn collect_observations_with_events(
|
||||
file_path: &Path,
|
||||
) -> Result<Vec<ObservationWithEvents>, Vec<Diagnostic>> {
|
||||
use std::fs::File;
|
||||
use std::io::{BufRead, BufReader};
|
||||
|
||||
let file = match File::open(file_path) {
|
||||
Ok(f) => f,
|
||||
Err(e) => {
|
||||
return Err(vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::PathNotFound,
|
||||
format!("I couldn't open the archive file: {}", e),
|
||||
)]);
|
||||
}
|
||||
};
|
||||
|
||||
let reader = BufReader::new(file);
|
||||
let mut lines = reader.lines();
|
||||
let mut observations = Vec::new();
|
||||
|
||||
// Parse header
|
||||
let header_line = match lines.next() {
|
||||
Some(Ok(line)) => line,
|
||||
_ => {
|
||||
return Err(vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::EmptyFile,
|
||||
"Archive file is empty or unreadable".to_string(),
|
||||
)]);
|
||||
}
|
||||
};
|
||||
|
||||
let header: Value = match serde_json::from_str(&header_line) {
|
||||
Ok(h) => h,
|
||||
Err(e) => {
|
||||
return Err(vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::MissingHeader,
|
||||
format!("I couldn't parse the header: {}", e),
|
||||
)]);
|
||||
}
|
||||
};
|
||||
|
||||
let created_str = header["created"].as_str().unwrap_or("");
|
||||
let created: DateTime<Utc> = match created_str.parse() {
|
||||
Ok(dt) => dt,
|
||||
Err(_) => Utc::now(),
|
||||
};
|
||||
|
||||
let initial_state = header["initial"].clone();
|
||||
|
||||
// Add initial state as observation 0
|
||||
observations.push(ObservationWithEvents {
|
||||
id: "initial".to_string(),
|
||||
timestamp: created,
|
||||
final_state: initial_state.clone(),
|
||||
});
|
||||
|
||||
let mut current_state = initial_state;
|
||||
|
||||
// Parse events and track state at each observation
|
||||
for line in lines {
|
||||
let line = match line {
|
||||
Ok(l) => l,
|
||||
Err(_) => continue,
|
||||
};
|
||||
|
||||
if line.trim().starts_with('#') || line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let event: Value = match serde_json::from_str(&line) {
|
||||
Ok(e) => e,
|
||||
Err(_) => continue,
|
||||
};
|
||||
|
||||
if let Some(arr) = event.as_array() {
|
||||
if arr.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let event_type = arr[0].as_str().unwrap_or("");
|
||||
|
||||
if event_type == "observe" && arr.len() >= 4 {
|
||||
let obs_id = arr[1].as_str().unwrap_or("").to_string();
|
||||
let timestamp_str = arr[2].as_str().unwrap_or("");
|
||||
|
||||
let timestamp: DateTime<Utc> = match timestamp_str.parse() {
|
||||
Ok(dt) => dt,
|
||||
Err(_) => continue,
|
||||
};
|
||||
|
||||
observations.push(ObservationWithEvents {
|
||||
id: obs_id,
|
||||
timestamp,
|
||||
final_state: current_state.clone(), // Will be updated as events are applied
|
||||
});
|
||||
} else if event_type == "snapshot" && arr.len() >= 4 {
|
||||
// Handle snapshot events
|
||||
let obs_id = arr[1].as_str().unwrap_or("").to_string();
|
||||
let timestamp_str = arr[2].as_str().unwrap_or("");
|
||||
let snapshot_state = arr[3].clone();
|
||||
|
||||
let timestamp: DateTime<Utc> = match timestamp_str.parse() {
|
||||
Ok(dt) => dt,
|
||||
Err(_) => continue,
|
||||
};
|
||||
|
||||
current_state = snapshot_state.clone();
|
||||
observations.push(ObservationWithEvents {
|
||||
id: obs_id,
|
||||
timestamp,
|
||||
final_state: snapshot_state,
|
||||
});
|
||||
} else {
|
||||
// Apply the event to current_state
|
||||
apply_event_to_state(&mut current_state, &arr);
|
||||
|
||||
// Update the final state of the last observation
|
||||
if let Some(last_obs) = observations.last_mut() {
|
||||
last_obs.final_state = current_state.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(observations)
|
||||
}
|
||||
|
||||
fn apply_event_to_state(state: &mut Value, event: &[Value]) {
|
||||
if event.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let event_type = event[0].as_str().unwrap_or("");
|
||||
|
||||
match event_type {
|
||||
"add" if event.len() >= 3 => {
|
||||
let path = event[1].as_str().unwrap_or("");
|
||||
let value = event[2].clone();
|
||||
if let Ok(pointer) = json_archive::pointer::JsonPointer::new(path) {
|
||||
let _ = pointer.set(state, value);
|
||||
}
|
||||
}
|
||||
"change" if event.len() >= 3 => {
|
||||
let path = event[1].as_str().unwrap_or("");
|
||||
let value = event[2].clone();
|
||||
if let Ok(pointer) = json_archive::pointer::JsonPointer::new(path) {
|
||||
let _ = pointer.set(state, value);
|
||||
}
|
||||
}
|
||||
"remove" if event.len() >= 2 => {
|
||||
let path = event[1].as_str().unwrap_or("");
|
||||
if let Ok(pointer) = json_archive::pointer::JsonPointer::new(path) {
|
||||
let _ = pointer.remove(state);
|
||||
}
|
||||
}
|
||||
"move" if event.len() >= 3 => {
|
||||
let path = event[1].as_str().unwrap_or("");
|
||||
let moves_value = event[2].clone();
|
||||
if let Ok(pointer) = json_archive::pointer::JsonPointer::new(path) {
|
||||
if let Ok(array_value) = pointer.get(state) {
|
||||
if let Some(array) = array_value.as_array() {
|
||||
let mut arr = array.clone();
|
||||
if let Some(moves) = moves_value.as_array() {
|
||||
for move_pair in moves {
|
||||
if let Some(pair) = move_pair.as_array() {
|
||||
if pair.len() == 2 {
|
||||
if let (Some(from_idx), Some(to_idx)) = (
|
||||
pair[0].as_u64().map(|i| i as usize),
|
||||
pair[1].as_u64().map(|i| i as usize),
|
||||
) {
|
||||
if from_idx < arr.len() && to_idx <= arr.len() {
|
||||
let element = arr[from_idx].clone();
|
||||
arr.insert(to_idx, element);
|
||||
let remove_idx = if from_idx > to_idx {
|
||||
from_idx + 1
|
||||
} else {
|
||||
from_idx
|
||||
};
|
||||
if remove_idx < arr.len() {
|
||||
arr.remove(remove_idx);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = pointer.set(state, Value::Array(arr));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
185
src/detection.rs
Normal file
185
src/detection.rs
Normal file
|
|
@ -0,0 +1,185 @@
|
|||
// json-archive is a tool for tracking JSON file changes over time
|
||||
// Copyright (C) 2025 Peoples Grocers LLC
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
//
|
||||
// To purchase a license under different terms contact admin@peoplesgrocers.com
|
||||
// To request changes, report bugs, or give user feedback contact
|
||||
// marxism@peoplesgrocers.com
|
||||
//
|
||||
|
||||
//! File type detection for JSON archives.
|
||||
//!
|
||||
//! This module exists to support ergonomic command-line usage without requiring
|
||||
//! `--archive=filename` flags. The goal is to infer intent just from filenames:
|
||||
//!
|
||||
//! - `json-archive data.json.archive data.json` -> append data.json to existing archive
|
||||
//! - `json-archive data.json` -> create new archive from data.json
|
||||
//! - `json-archive data.json.archive.tmp foo.json bar.json` -> append to archive with .tmp suffix
|
||||
//!
|
||||
//! Design choice by @nobody. No user requests for this, just seemed nice.
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::{BufRead, BufReader};
|
||||
use std::path::Path;
|
||||
|
||||
/// Detects if a file is a JSON archive by checking file extension or inspecting the header.
|
||||
///
|
||||
/// Detection strategy:
|
||||
/// 1. Check if filename ends with .json.archive
|
||||
/// 2. Inspect first line for type field as first key with value "@peoplesgrocers/json-archive"
|
||||
///
|
||||
/// Strategy 2 was added by @nobody based on frustration with the Elm compiler,
|
||||
/// which requires specific file extensions (like .js) while build systems often generate
|
||||
/// temporary files with arbitrary suffixes like .tmp. @nobody thought it would be nice if the CLI
|
||||
/// was robust enough to handle this.
|
||||
///
|
||||
///
|
||||
/// The magic value "@peoplesgrocers/json-archive" in the type field works as a file
|
||||
/// signature for cases where the extension isn't what we expect. Not requested by anyone,
|
||||
/// just anticipating potential tooling conflicts.
|
||||
pub fn is_json_archive<P: AsRef<Path>>(path: P) -> Result<bool, std::io::Error> {
|
||||
let path = path.as_ref();
|
||||
|
||||
if let Some(filename) = path.file_name() {
|
||||
if let Some(filename_str) = filename.to_str() {
|
||||
if filename_str.ends_with(".json.archive") {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let file = File::open(path)?;
|
||||
let mut reader = BufReader::new(file);
|
||||
let mut first_line = String::new();
|
||||
|
||||
match reader.read_line(&mut first_line) {
|
||||
Ok(0) => return Ok(false), // Empty file
|
||||
Ok(_) => {
|
||||
// Try to parse as JSON and check if it has our type field as the first key
|
||||
if let Ok(value) = serde_json::from_str::<serde_json::Value>(&first_line) {
|
||||
if let Some(obj) = value.as_object() {
|
||||
// Check if the first key is "type" with our expected value
|
||||
// Note: serde_json::Map preserves insertion order
|
||||
if let Some((first_key, first_value)) = obj.iter().next() {
|
||||
if first_key == "type" {
|
||||
if let Some(type_str) = first_value.as_str() {
|
||||
return Ok(type_str == "@peoplesgrocers/json-archive");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Write;
|
||||
use tempfile::NamedTempFile;
|
||||
|
||||
#[test]
|
||||
fn test_detect_by_json_archive_extension() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut temp_file = NamedTempFile::with_suffix(".json.archive")?;
|
||||
writeln!(temp_file, r#"{{"some": "json"}}"#)?;
|
||||
temp_file.flush()?;
|
||||
|
||||
assert!(is_json_archive(temp_file.path())?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_detect_by_type_field() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut temp_file = NamedTempFile::with_suffix(".weird-extension")?;
|
||||
writeln!(
|
||||
temp_file,
|
||||
r#"{{"type":"@peoplesgrocers/json-archive","version":1}}"#
|
||||
)?;
|
||||
temp_file.flush()?;
|
||||
|
||||
assert!(is_json_archive(temp_file.path())?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_detect_by_type_field_with_tmp_extension() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut temp_file = NamedTempFile::with_suffix(".json.tmp")?;
|
||||
writeln!(
|
||||
temp_file,
|
||||
r#"{{"type":"@peoplesgrocers/json-archive","version":1}}"#
|
||||
)?;
|
||||
temp_file.flush()?;
|
||||
|
||||
assert!(is_json_archive(temp_file.path())?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_not_archive_regular_json() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut temp_file = NamedTempFile::with_suffix(".json")?;
|
||||
writeln!(temp_file, r#"{{"some": "json"}}"#)?;
|
||||
temp_file.flush()?;
|
||||
|
||||
assert!(!is_json_archive(temp_file.path())?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_not_archive_wrong_type_field() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut temp_file = NamedTempFile::with_suffix(".tmp")?;
|
||||
writeln!(temp_file, r#"{{"type":"something-else","version":1}}"#)?;
|
||||
temp_file.flush()?;
|
||||
|
||||
assert!(!is_json_archive(temp_file.path())?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_not_archive_type_not_first_field() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut temp_file = NamedTempFile::with_suffix(".tmp")?;
|
||||
// Use a key that comes after "type" alphabetically to ensure it's first
|
||||
writeln!(
|
||||
temp_file,
|
||||
r#"{{"version":1,"zzz":"@peoplesgrocers/json-archive"}}"#
|
||||
)?;
|
||||
temp_file.flush()?;
|
||||
|
||||
// This should NOT be detected as an archive since the type field doesn't exist
|
||||
assert!(!is_json_archive(temp_file.path())?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_not_archive_empty_file() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let temp_file = NamedTempFile::with_suffix(".json")?;
|
||||
|
||||
assert!(!is_json_archive(temp_file.path())?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_not_archive_invalid_json() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut temp_file = NamedTempFile::with_suffix(".tmp")?;
|
||||
writeln!(temp_file, "not valid json")?;
|
||||
temp_file.flush()?;
|
||||
|
||||
assert!(!is_json_archive(temp_file.path())?);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
286
src/diagnostics.rs
Normal file
286
src/diagnostics.rs
Normal file
|
|
@ -0,0 +1,286 @@
|
|||
// json-archive is a tool for tracking JSON file changes over time
|
||||
// Copyright (C) 2025 Peoples Grocers LLC
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
//
|
||||
// To purchase a license under different terms contact admin@peoplesgrocers.com
|
||||
// To request changes, report bugs, or give user feedback contact
|
||||
// marxism@peoplesgrocers.com
|
||||
//
|
||||
|
||||
use std::fmt;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DiagnosticLevel {
|
||||
Fatal,
|
||||
Warning,
|
||||
Info,
|
||||
}
|
||||
|
||||
impl fmt::Display for DiagnosticLevel {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
DiagnosticLevel::Fatal => write!(f, "error"),
|
||||
DiagnosticLevel::Warning => write!(f, "warning"),
|
||||
DiagnosticLevel::Info => write!(f, "info"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum DiagnosticCode {
|
||||
EmptyFile,
|
||||
MissingHeader,
|
||||
InvalidUtf8,
|
||||
TruncatedJson,
|
||||
|
||||
MissingHeaderField,
|
||||
UnsupportedVersion,
|
||||
InvalidTimestamp,
|
||||
InvalidInitialState,
|
||||
|
||||
InvalidEventJson,
|
||||
UnknownEventType,
|
||||
WrongFieldCount,
|
||||
WrongFieldType,
|
||||
|
||||
NonExistentObservationId,
|
||||
DuplicateObservationId,
|
||||
|
||||
ChangeCountMismatch,
|
||||
InvalidChangeCount,
|
||||
|
||||
InvalidPointerSyntax,
|
||||
PathNotFound,
|
||||
InvalidArrayIndex,
|
||||
ArrayIndexOutOfBounds,
|
||||
ParentPathNotFound,
|
||||
|
||||
TypeMismatch,
|
||||
OldValueMismatch,
|
||||
|
||||
MoveOnNonArray,
|
||||
MoveIndexOutOfBounds,
|
||||
InvalidMoveIndex,
|
||||
|
||||
SnapshotStateMismatch,
|
||||
SnapshotTimestampOrder,
|
||||
}
|
||||
|
||||
impl DiagnosticCode {
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
DiagnosticCode::EmptyFile => "E001",
|
||||
DiagnosticCode::MissingHeader => "E002",
|
||||
DiagnosticCode::InvalidUtf8 => "E003",
|
||||
DiagnosticCode::TruncatedJson => "E004",
|
||||
|
||||
DiagnosticCode::MissingHeaderField => "E010",
|
||||
DiagnosticCode::UnsupportedVersion => "E011",
|
||||
DiagnosticCode::InvalidTimestamp => "W012",
|
||||
DiagnosticCode::InvalidInitialState => "E013",
|
||||
|
||||
DiagnosticCode::InvalidEventJson => "E020",
|
||||
DiagnosticCode::UnknownEventType => "W021",
|
||||
DiagnosticCode::WrongFieldCount => "E022",
|
||||
DiagnosticCode::WrongFieldType => "E023",
|
||||
|
||||
DiagnosticCode::NonExistentObservationId => "E030",
|
||||
DiagnosticCode::DuplicateObservationId => "W031",
|
||||
|
||||
DiagnosticCode::ChangeCountMismatch => "W040",
|
||||
DiagnosticCode::InvalidChangeCount => "E041",
|
||||
|
||||
DiagnosticCode::InvalidPointerSyntax => "E050",
|
||||
DiagnosticCode::PathNotFound => "E051",
|
||||
DiagnosticCode::InvalidArrayIndex => "E052",
|
||||
DiagnosticCode::ArrayIndexOutOfBounds => "E053",
|
||||
DiagnosticCode::ParentPathNotFound => "E054",
|
||||
|
||||
DiagnosticCode::TypeMismatch => "E060",
|
||||
DiagnosticCode::OldValueMismatch => "W061",
|
||||
|
||||
DiagnosticCode::MoveOnNonArray => "E070",
|
||||
DiagnosticCode::MoveIndexOutOfBounds => "E071",
|
||||
DiagnosticCode::InvalidMoveIndex => "E072",
|
||||
|
||||
DiagnosticCode::SnapshotStateMismatch => "W080",
|
||||
DiagnosticCode::SnapshotTimestampOrder => "W081",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn title(&self) -> &'static str {
|
||||
match self {
|
||||
DiagnosticCode::EmptyFile => "Empty file",
|
||||
DiagnosticCode::MissingHeader => "Missing header",
|
||||
DiagnosticCode::InvalidUtf8 => "Invalid UTF-8 encoding",
|
||||
DiagnosticCode::TruncatedJson => "Truncated JSON",
|
||||
|
||||
DiagnosticCode::MissingHeaderField => "Missing required header field",
|
||||
DiagnosticCode::UnsupportedVersion => "Unsupported version",
|
||||
DiagnosticCode::InvalidTimestamp => "Invalid timestamp",
|
||||
DiagnosticCode::InvalidInitialState => "Invalid initial state",
|
||||
|
||||
DiagnosticCode::InvalidEventJson => "Invalid event JSON",
|
||||
DiagnosticCode::UnknownEventType => "Unknown event type",
|
||||
DiagnosticCode::WrongFieldCount => "Wrong field count",
|
||||
DiagnosticCode::WrongFieldType => "Wrong field type",
|
||||
|
||||
DiagnosticCode::NonExistentObservationId => "Non-existent observation ID",
|
||||
DiagnosticCode::DuplicateObservationId => "Duplicate observation ID",
|
||||
|
||||
DiagnosticCode::ChangeCountMismatch => "Change count mismatch",
|
||||
DiagnosticCode::InvalidChangeCount => "Invalid change count",
|
||||
|
||||
DiagnosticCode::InvalidPointerSyntax => "Invalid JSON Pointer syntax",
|
||||
DiagnosticCode::PathNotFound => "Path not found",
|
||||
DiagnosticCode::InvalidArrayIndex => "Invalid array index",
|
||||
DiagnosticCode::ArrayIndexOutOfBounds => "Array index out of bounds",
|
||||
DiagnosticCode::ParentPathNotFound => "Parent path not found",
|
||||
|
||||
DiagnosticCode::TypeMismatch => "Type mismatch",
|
||||
DiagnosticCode::OldValueMismatch => "Old value mismatch",
|
||||
|
||||
DiagnosticCode::MoveOnNonArray => "Move operation on non-array",
|
||||
DiagnosticCode::MoveIndexOutOfBounds => "Move index out of bounds",
|
||||
DiagnosticCode::InvalidMoveIndex => "Invalid move index",
|
||||
|
||||
DiagnosticCode::SnapshotStateMismatch => "Snapshot state mismatch",
|
||||
DiagnosticCode::SnapshotTimestampOrder => "Snapshot timestamp out of order",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Diagnostic {
|
||||
pub filename: Option<String>,
|
||||
pub line_number: Option<usize>,
|
||||
pub column: Option<usize>,
|
||||
pub level: DiagnosticLevel,
|
||||
pub code: DiagnosticCode,
|
||||
pub description: String,
|
||||
pub code_snippet: Option<String>,
|
||||
pub advice: Option<String>,
|
||||
}
|
||||
|
||||
impl Diagnostic {
|
||||
pub fn new(level: DiagnosticLevel, code: DiagnosticCode, description: String) -> Self {
|
||||
Self {
|
||||
filename: None,
|
||||
line_number: None,
|
||||
column: None,
|
||||
level,
|
||||
code,
|
||||
description,
|
||||
code_snippet: None,
|
||||
advice: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_location(mut self, filename: String, line_number: usize) -> Self {
|
||||
self.filename = Some(filename);
|
||||
self.line_number = Some(line_number);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_column(mut self, column: usize) -> Self {
|
||||
self.column = Some(column);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_snippet(mut self, snippet: String) -> Self {
|
||||
self.code_snippet = Some(snippet);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_advice(mut self, advice: String) -> Self {
|
||||
self.advice = Some(advice);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn is_fatal(&self) -> bool {
|
||||
self.level == DiagnosticLevel::Fatal
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Diagnostic {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
if let (Some(filename), Some(line)) = (&self.filename, self.line_number) {
|
||||
if let Some(col) = self.column {
|
||||
write!(f, "{}:{}:{} - ", filename, line, col)?;
|
||||
} else {
|
||||
write!(f, "{}:{} - ", filename, line)?;
|
||||
}
|
||||
}
|
||||
|
||||
writeln!(
|
||||
f,
|
||||
"{} {}: {}",
|
||||
self.level,
|
||||
self.code.as_str(),
|
||||
self.code.title()
|
||||
)?;
|
||||
writeln!(f)?;
|
||||
writeln!(f, "{}", self.description)?;
|
||||
|
||||
if let Some(snippet) = &self.code_snippet {
|
||||
writeln!(f)?;
|
||||
writeln!(f, "{}", snippet)?;
|
||||
}
|
||||
|
||||
if let Some(advice) = &self.advice {
|
||||
writeln!(f)?;
|
||||
writeln!(f, "{}", advice)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct DiagnosticCollector {
|
||||
diagnostics: Vec<Diagnostic>,
|
||||
}
|
||||
|
||||
impl DiagnosticCollector {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
diagnostics: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn add(&mut self, diagnostic: Diagnostic) {
|
||||
self.diagnostics.push(diagnostic);
|
||||
}
|
||||
|
||||
pub fn has_fatal(&self) -> bool {
|
||||
self.diagnostics.iter().any(|d| d.is_fatal())
|
||||
}
|
||||
|
||||
pub fn diagnostics(&self) -> &[Diagnostic] {
|
||||
&self.diagnostics
|
||||
}
|
||||
|
||||
pub fn into_diagnostics(self) -> Vec<Diagnostic> {
|
||||
self.diagnostics
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.diagnostics.is_empty()
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.diagnostics.len()
|
||||
}
|
||||
}
|
||||
345
src/diff.rs
Normal file
345
src/diff.rs
Normal file
|
|
@ -0,0 +1,345 @@
|
|||
// json-archive is a tool for tracking JSON file changes over time
|
||||
// Copyright (C) 2025 Peoples Grocers LLC
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
//
|
||||
// To purchase a license under different terms contact admin@peoplesgrocers.com
|
||||
// To request changes, report bugs, or give user feedback contact
|
||||
// marxism@peoplesgrocers.com
|
||||
//
|
||||
|
||||
use serde_json::Value;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use crate::events::Event;
|
||||
|
||||
pub fn diff(old: &Value, new: &Value, base_path: &str, observation_id: &str) -> Vec<Event> {
|
||||
let mut result = Vec::<Event>::new();
|
||||
diff_recursive(old, new, base_path, observation_id, &mut result);
|
||||
result
|
||||
}
|
||||
|
||||
fn diff_recursive(
|
||||
old: &Value,
|
||||
new: &Value,
|
||||
path: &str,
|
||||
observation_id: &str,
|
||||
result: &mut Vec<Event>,
|
||||
) {
|
||||
match (old, new) {
|
||||
(Value::Object(old_obj), Value::Object(new_obj)) => {
|
||||
diff_objects(old_obj, new_obj, path, observation_id, result);
|
||||
}
|
||||
(Value::Array(old_arr), Value::Array(new_arr)) => {
|
||||
diff_arrays(old_arr, new_arr, path, observation_id, result);
|
||||
}
|
||||
_ => {
|
||||
if old != new {
|
||||
result.push(Event::Change {
|
||||
path: path.to_string(),
|
||||
new_value: new.clone(),
|
||||
observation_id: observation_id.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn diff_objects(
|
||||
old: &serde_json::Map<String, Value>,
|
||||
new: &serde_json::Map<String, Value>,
|
||||
base_path: &str,
|
||||
observation_id: &str,
|
||||
result: &mut Vec<Event>,
|
||||
) {
|
||||
let old_keys: HashSet<&String> = old.keys().collect();
|
||||
let new_keys: HashSet<&String> = new.keys().collect();
|
||||
|
||||
// Removed keys
|
||||
for key in old_keys.difference(&new_keys) {
|
||||
let path = format_path(base_path, key);
|
||||
result.push(Event::Remove {
|
||||
path,
|
||||
observation_id: observation_id.to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
// Added keys
|
||||
for key in new_keys.difference(&old_keys) {
|
||||
let path = format_path(base_path, key);
|
||||
result.push(Event::Add {
|
||||
path,
|
||||
value: new[*key].clone(),
|
||||
observation_id: observation_id.to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
// Changed keys
|
||||
for key in old_keys.intersection(&new_keys) {
|
||||
let path = format_path(base_path, key);
|
||||
let old_value = &old[*key];
|
||||
let new_value = &new[*key];
|
||||
|
||||
if old_value != new_value {
|
||||
diff_recursive(old_value, new_value, &path, observation_id, result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn diff_arrays(
|
||||
old: &[Value],
|
||||
new: &[Value],
|
||||
base_path: &str,
|
||||
observation_id: &str,
|
||||
result: &mut Vec<Event>,
|
||||
) {
|
||||
// Simple implementation: we'll use a more sophisticated approach for move detection
|
||||
let mut old_items: HashMap<String, (usize, &Value)> = HashMap::new();
|
||||
let mut new_items: HashMap<String, (usize, &Value)> = HashMap::new();
|
||||
|
||||
// Create content-based indices for move detection
|
||||
for (i, value) in old.iter().enumerate() {
|
||||
let key = value_hash(value);
|
||||
old_items.insert(key, (i, value));
|
||||
}
|
||||
|
||||
for (i, value) in new.iter().enumerate() {
|
||||
let key = value_hash(value);
|
||||
new_items.insert(key, (i, value));
|
||||
}
|
||||
|
||||
let old_keys: HashSet<&String> = old_items.keys().collect();
|
||||
let new_keys: HashSet<&String> = new_items.keys().collect();
|
||||
let common_keys: HashSet<&String> = old_keys.intersection(&new_keys).cloned().collect();
|
||||
|
||||
// Track which items have been processed
|
||||
let mut processed_old: HashSet<usize> = HashSet::new();
|
||||
let mut processed_new: HashSet<usize> = HashSet::new();
|
||||
|
||||
// Handle items that exist in both arrays (potential moves or unchanged)
|
||||
let mut moves: Vec<(usize, usize)> = Vec::new();
|
||||
|
||||
for key in &common_keys {
|
||||
let (old_idx, old_val) = old_items[*key];
|
||||
let (new_idx, new_val) = new_items[*key];
|
||||
|
||||
processed_old.insert(old_idx);
|
||||
processed_new.insert(new_idx);
|
||||
|
||||
if old_val != new_val {
|
||||
// Value changed
|
||||
let path = format!("{}/{}", base_path, new_idx);
|
||||
result.push(Event::Change {
|
||||
path,
|
||||
new_value: new_val.clone(),
|
||||
observation_id: observation_id.to_string(),
|
||||
});
|
||||
} else if old_idx != new_idx {
|
||||
// Same value, different position - this is a move
|
||||
moves.push((old_idx, new_idx));
|
||||
}
|
||||
}
|
||||
|
||||
// Generate move events if any
|
||||
if !moves.is_empty() {
|
||||
// Sort moves by original position to ensure consistent ordering
|
||||
moves.sort_by_key(|(old_idx, _)| *old_idx);
|
||||
result.push(Event::Move {
|
||||
path: base_path.to_string(),
|
||||
moves,
|
||||
observation_id: observation_id.to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
// Handle removed items (in old but not in new)
|
||||
let mut removed_indices: Vec<usize> = (0..old.len())
|
||||
.filter(|i| !processed_old.contains(i))
|
||||
.collect();
|
||||
|
||||
// Remove from highest index to lowest to avoid index shifting issues
|
||||
removed_indices.sort_by(|a, b| b.cmp(a));
|
||||
|
||||
for idx in removed_indices {
|
||||
let path = format!("{}/{}", base_path, idx);
|
||||
result.push(Event::Remove {
|
||||
path,
|
||||
observation_id: observation_id.to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
// Handle added items (in new but not in old)
|
||||
for i in 0..new.len() {
|
||||
if !processed_new.contains(&i) {
|
||||
let path = format!("{}/{}", base_path, i);
|
||||
result.push(Event::Add {
|
||||
path,
|
||||
value: new[i].clone(),
|
||||
observation_id: observation_id.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn format_path(base: &str, segment: &str) -> String {
|
||||
let escaped_segment = segment.replace("~", "~0").replace("/", "~1");
|
||||
if base.is_empty() {
|
||||
format!("/{}", escaped_segment)
|
||||
} else {
|
||||
format!("{}/{}", base, escaped_segment)
|
||||
}
|
||||
}
|
||||
|
||||
fn value_hash(value: &Value) -> String {
|
||||
// Simple content-based hash for move detection
|
||||
// In a real implementation, you might want a more sophisticated hash
|
||||
format!("{:?}", value)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn test_object_add() {
|
||||
let old = json!({"a": 1});
|
||||
let new = json!({"a": 1, "b": 2});
|
||||
let result = diff(&old, &new, "", "obs-1");
|
||||
|
||||
assert_eq!(result.len(), 1);
|
||||
match &result[0] {
|
||||
Event::Add { path, value, .. } => {
|
||||
assert_eq!(path, "/b");
|
||||
assert_eq!(value, &json!(2));
|
||||
}
|
||||
_ => panic!("Expected Add event"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_object_remove() {
|
||||
let old = json!({"a": 1, "b": 2});
|
||||
let new = json!({"a": 1});
|
||||
let result = diff(&old, &new, "", "obs-1");
|
||||
|
||||
assert_eq!(result.len(), 1);
|
||||
match &result[0] {
|
||||
Event::Remove { path, .. } => {
|
||||
assert_eq!(path, "/b");
|
||||
}
|
||||
_ => panic!("Expected Remove event"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_object_change() {
|
||||
let old = json!({"a": 1});
|
||||
let new = json!({"a": 2});
|
||||
let result = diff(&old, &new, "", "obs-1");
|
||||
|
||||
assert_eq!(result.len(), 1);
|
||||
match &result[0] {
|
||||
Event::Change {
|
||||
path, new_value, ..
|
||||
} => {
|
||||
assert_eq!(path, "/a");
|
||||
assert_eq!(new_value, &json!(2));
|
||||
}
|
||||
_ => panic!("Expected Change event"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_nested_object() {
|
||||
let old = json!({"user": {"name": "Alice", "age": 30}});
|
||||
let new = json!({"user": {"name": "Alice", "age": 31}});
|
||||
let result = diff(&old, &new, "", "obs-1");
|
||||
|
||||
assert_eq!(result.len(), 1);
|
||||
match &result[0] {
|
||||
Event::Change {
|
||||
path, new_value, ..
|
||||
} => {
|
||||
assert_eq!(path, "/user/age");
|
||||
assert_eq!(new_value, &json!(31));
|
||||
}
|
||||
_ => panic!("Expected Change event"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_array_add() {
|
||||
let old = json!(["a", "b"]);
|
||||
let new = json!(["a", "b", "c"]);
|
||||
let result = diff(&old, &new, "", "obs-1");
|
||||
|
||||
assert_eq!(result.len(), 1);
|
||||
match &result[0] {
|
||||
Event::Add { path, value, .. } => {
|
||||
assert_eq!(path, "/2");
|
||||
assert_eq!(value, &json!("c"));
|
||||
}
|
||||
_ => panic!("Expected Add event"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_array_remove() {
|
||||
let old = json!(["a", "b", "c"]);
|
||||
let new = json!(["a", "b"]);
|
||||
let result = diff(&old, &new, "", "obs-1");
|
||||
|
||||
assert_eq!(result.len(), 1);
|
||||
match &result[0] {
|
||||
Event::Remove { path, .. } => {
|
||||
assert_eq!(path, "/2");
|
||||
}
|
||||
_ => panic!("Expected Remove event"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_array_move() {
|
||||
let old = json!(["a", "b", "c"]);
|
||||
let new = json!(["c", "a", "b"]);
|
||||
let result = diff(&old, &new, "", "obs-1");
|
||||
|
||||
// Should generate move events
|
||||
assert!(!result.is_empty());
|
||||
|
||||
// Check if we have a move event
|
||||
let has_move = result.iter().any(|e| matches!(e, Event::Move { .. }));
|
||||
assert!(has_move, "Expected at least one Move event");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_escape_sequences_in_keys() {
|
||||
let old = json!({});
|
||||
let new = json!({"foo/bar": "value", "foo~bar": "value2"});
|
||||
let result = diff(&old, &new, "", "obs-1");
|
||||
|
||||
assert_eq!(result.len(), 2);
|
||||
|
||||
let paths: Vec<&String> = result
|
||||
.iter()
|
||||
.filter_map(|e| match e {
|
||||
Event::Add { path, .. } => Some(path),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
|
||||
assert!(paths.contains(&&"/foo~1bar".to_string()));
|
||||
assert!(paths.contains(&&"/foo~0bar".to_string()));
|
||||
}
|
||||
}
|
||||
452
src/events.rs
Normal file
452
src/events.rs
Normal file
|
|
@ -0,0 +1,452 @@
|
|||
// json-archive is a tool for tracking JSON file changes over time
|
||||
// Copyright (C) 2025 Peoples Grocers LLC
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
//
|
||||
// To purchase a license under different terms contact admin@peoplesgrocers.com
|
||||
// To request changes, report bugs, or give user feedback contact
|
||||
// marxism@peoplesgrocers.com
|
||||
//
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::de::{self, SeqAccess, Visitor};
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Header {
|
||||
/// Type identifier for magic file detection. We put this first to act as a "poor man's
|
||||
/// magic file number detection" when the archive file has an unexpected extension.
|
||||
/// This helps avoid issues like the Elm compiler that requires specific file extensions
|
||||
/// (e.g., .js) which doesn't play nice with build systems using temporary files with
|
||||
/// arbitrary suffixes. By putting this key first, we can detect archive files even
|
||||
/// when they have non-standard extensions like .tmp appended by build tools.
|
||||
#[serde(rename = "type")]
|
||||
pub file_type: String,
|
||||
pub version: u32,
|
||||
pub created: DateTime<Utc>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub source: Option<String>,
|
||||
pub initial: Value,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub metadata: Option<Value>,
|
||||
}
|
||||
|
||||
impl Header {
|
||||
pub fn new(initial: Value, source: Option<String>) -> Self {
|
||||
Self {
|
||||
file_type: "@peoplesgrocers/json-archive".to_string(),
|
||||
version: 1,
|
||||
created: Utc::now(),
|
||||
source,
|
||||
initial,
|
||||
metadata: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Event {
|
||||
Observe {
|
||||
observation_id: String,
|
||||
timestamp: DateTime<Utc>,
|
||||
change_count: usize,
|
||||
},
|
||||
Add {
|
||||
path: String,
|
||||
value: Value,
|
||||
observation_id: String,
|
||||
},
|
||||
Change {
|
||||
path: String,
|
||||
new_value: Value,
|
||||
observation_id: String,
|
||||
},
|
||||
Remove {
|
||||
path: String,
|
||||
observation_id: String,
|
||||
},
|
||||
Move {
|
||||
path: String,
|
||||
moves: Vec<(usize, usize)>,
|
||||
observation_id: String,
|
||||
},
|
||||
Snapshot {
|
||||
observation_id: String,
|
||||
timestamp: DateTime<Utc>,
|
||||
object: Value,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
impl Serialize for Event {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
use serde::ser::SerializeSeq;
|
||||
|
||||
match self {
|
||||
Event::Observe {
|
||||
observation_id,
|
||||
timestamp,
|
||||
change_count,
|
||||
} => {
|
||||
let mut seq = serializer.serialize_seq(Some(4))?;
|
||||
seq.serialize_element("observe")?;
|
||||
seq.serialize_element(observation_id)?;
|
||||
seq.serialize_element(timestamp)?;
|
||||
seq.serialize_element(change_count)?;
|
||||
seq.end()
|
||||
}
|
||||
Event::Add {
|
||||
path,
|
||||
value,
|
||||
observation_id,
|
||||
} => {
|
||||
let mut seq = serializer.serialize_seq(Some(4))?;
|
||||
seq.serialize_element("add")?;
|
||||
seq.serialize_element(path)?;
|
||||
seq.serialize_element(value)?;
|
||||
seq.serialize_element(observation_id)?;
|
||||
seq.end()
|
||||
}
|
||||
Event::Change {
|
||||
path,
|
||||
new_value,
|
||||
observation_id,
|
||||
} => {
|
||||
let mut seq = serializer.serialize_seq(Some(4))?;
|
||||
seq.serialize_element("change")?;
|
||||
seq.serialize_element(path)?;
|
||||
seq.serialize_element(new_value)?;
|
||||
seq.serialize_element(observation_id)?;
|
||||
seq.end()
|
||||
}
|
||||
Event::Remove {
|
||||
path,
|
||||
observation_id,
|
||||
} => {
|
||||
let mut seq = serializer.serialize_seq(Some(3))?;
|
||||
seq.serialize_element("remove")?;
|
||||
seq.serialize_element(path)?;
|
||||
seq.serialize_element(observation_id)?;
|
||||
seq.end()
|
||||
}
|
||||
Event::Move {
|
||||
path,
|
||||
moves,
|
||||
observation_id,
|
||||
} => {
|
||||
let mut seq = serializer.serialize_seq(Some(4))?;
|
||||
seq.serialize_element("move")?;
|
||||
seq.serialize_element(path)?;
|
||||
seq.serialize_element(moves)?;
|
||||
seq.serialize_element(observation_id)?;
|
||||
seq.end()
|
||||
}
|
||||
Event::Snapshot {
|
||||
observation_id,
|
||||
timestamp,
|
||||
object,
|
||||
} => {
|
||||
let mut seq = serializer.serialize_seq(Some(4))?;
|
||||
seq.serialize_element("snapshot")?;
|
||||
seq.serialize_element(observation_id)?;
|
||||
seq.serialize_element(timestamp)?;
|
||||
seq.serialize_element(object)?;
|
||||
seq.end()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct EventVisitor;
|
||||
|
||||
impl<'de> Visitor<'de> for EventVisitor {
|
||||
type Value = Event;
|
||||
|
||||
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
formatter.write_str("a JSON array representing an Event")
|
||||
}
|
||||
|
||||
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
|
||||
where
|
||||
A: SeqAccess<'de>,
|
||||
{
|
||||
let event_type: String = seq
|
||||
.next_element()?
|
||||
.ok_or_else(|| de::Error::missing_field("event type"))?;
|
||||
|
||||
match event_type.as_str() {
|
||||
"observe" => {
|
||||
let observation_id: String = seq
|
||||
.next_element()?
|
||||
.ok_or_else(|| de::Error::missing_field("observation_id"))?;
|
||||
let timestamp: DateTime<Utc> = seq
|
||||
.next_element()?
|
||||
.ok_or_else(|| de::Error::missing_field("timestamp"))?;
|
||||
let change_count: usize = seq
|
||||
.next_element()?
|
||||
.ok_or_else(|| de::Error::missing_field("change_count"))?;
|
||||
Ok(Event::Observe {
|
||||
observation_id,
|
||||
timestamp,
|
||||
change_count,
|
||||
})
|
||||
}
|
||||
"add" => {
|
||||
let path: String = seq
|
||||
.next_element()?
|
||||
.ok_or_else(|| de::Error::missing_field("path"))?;
|
||||
let value: Value = seq
|
||||
.next_element()?
|
||||
.ok_or_else(|| de::Error::missing_field("value"))?;
|
||||
let observation_id: String = seq
|
||||
.next_element()?
|
||||
.ok_or_else(|| de::Error::missing_field("observation_id"))?;
|
||||
Ok(Event::Add {
|
||||
path,
|
||||
value,
|
||||
observation_id,
|
||||
})
|
||||
}
|
||||
"change" => {
|
||||
let path: String = seq
|
||||
.next_element()?
|
||||
.ok_or_else(|| de::Error::missing_field("path"))?;
|
||||
let new_value: Value = seq
|
||||
.next_element()?
|
||||
.ok_or_else(|| de::Error::missing_field("new_value"))?;
|
||||
let observation_id: String = seq
|
||||
.next_element()?
|
||||
.ok_or_else(|| de::Error::missing_field("observation_id"))?;
|
||||
Ok(Event::Change {
|
||||
path,
|
||||
new_value,
|
||||
observation_id,
|
||||
})
|
||||
}
|
||||
"remove" => {
|
||||
let path: String = seq
|
||||
.next_element()?
|
||||
.ok_or_else(|| de::Error::missing_field("path"))?;
|
||||
let observation_id: String = seq
|
||||
.next_element()?
|
||||
.ok_or_else(|| de::Error::missing_field("observation_id"))?;
|
||||
Ok(Event::Remove {
|
||||
path,
|
||||
observation_id,
|
||||
})
|
||||
}
|
||||
"move" => {
|
||||
let path: String = seq
|
||||
.next_element()?
|
||||
.ok_or_else(|| de::Error::missing_field("path"))?;
|
||||
let moves: Vec<(usize, usize)> = seq
|
||||
.next_element()?
|
||||
.ok_or_else(|| de::Error::missing_field("moves"))?;
|
||||
let observation_id: String = seq
|
||||
.next_element()?
|
||||
.ok_or_else(|| de::Error::missing_field("observation_id"))?;
|
||||
Ok(Event::Move {
|
||||
path,
|
||||
moves,
|
||||
observation_id,
|
||||
})
|
||||
}
|
||||
"snapshot" => {
|
||||
let observation_id: String = seq
|
||||
.next_element()?
|
||||
.ok_or_else(|| de::Error::missing_field("observation_id"))?;
|
||||
let timestamp: DateTime<Utc> = seq
|
||||
.next_element()?
|
||||
.ok_or_else(|| de::Error::missing_field("timestamp"))?;
|
||||
let object: Value = seq
|
||||
.next_element()?
|
||||
.ok_or_else(|| de::Error::missing_field("object"))?;
|
||||
Ok(Event::Snapshot {
|
||||
observation_id,
|
||||
timestamp,
|
||||
object,
|
||||
})
|
||||
}
|
||||
_ => Err(de::Error::unknown_variant(
|
||||
&event_type,
|
||||
&["observe", "add", "change", "remove", "move", "snapshot"],
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Event {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
deserializer.deserialize_seq(EventVisitor)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Observation {
|
||||
pub id: String,
|
||||
pub timestamp: DateTime<Utc>,
|
||||
pub events: Vec<Event>,
|
||||
}
|
||||
|
||||
impl Observation {
|
||||
pub fn new(id: String, timestamp: DateTime<Utc>) -> Self {
|
||||
Self {
|
||||
id,
|
||||
timestamp,
|
||||
events: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn add_event(&mut self, event: Event) {
|
||||
self.events.push(event);
|
||||
}
|
||||
|
||||
pub fn to_events(self) -> Vec<Event> {
|
||||
let mut result = vec![Event::Observe {
|
||||
observation_id: self.id.clone(),
|
||||
timestamp: self.timestamp,
|
||||
change_count: self.events.len(),
|
||||
}];
|
||||
result.extend(self.events);
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn test_header_serialization() {
|
||||
let header = Header::new(json!({"test": "value"}), Some("test-source".to_string()));
|
||||
let serialized = serde_json::to_string(&header).unwrap();
|
||||
let deserialized: Header = serde_json::from_str(&serialized).unwrap();
|
||||
|
||||
assert_eq!(header.file_type, deserialized.file_type);
|
||||
assert_eq!(header.version, deserialized.version);
|
||||
assert_eq!(header.initial, deserialized.initial);
|
||||
assert_eq!(header.source, deserialized.source);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_event_serialization() {
|
||||
let timestamp = Utc::now();
|
||||
|
||||
// Test observe event
|
||||
let observe_event = Event::Observe {
|
||||
observation_id: "obs-1".to_string(),
|
||||
timestamp,
|
||||
change_count: 2,
|
||||
};
|
||||
let serialized = serde_json::to_string(&observe_event).unwrap();
|
||||
let expected_array = json!(["observe", "obs-1", timestamp, 2]);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<Value>(&serialized).unwrap(),
|
||||
expected_array
|
||||
);
|
||||
|
||||
// Test add event
|
||||
let add_event = Event::Add {
|
||||
path: "/test".to_string(),
|
||||
value: json!("value"),
|
||||
observation_id: "obs-1".to_string(),
|
||||
};
|
||||
let serialized = serde_json::to_string(&add_event).unwrap();
|
||||
let expected_array = json!(["add", "/test", "value", "obs-1"]);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<Value>(&serialized).unwrap(),
|
||||
expected_array
|
||||
);
|
||||
|
||||
// Test all event types for serialization/deserialization round-trip
|
||||
let events = vec![
|
||||
Event::Observe {
|
||||
observation_id: "obs-1".to_string(),
|
||||
timestamp,
|
||||
change_count: 2,
|
||||
},
|
||||
Event::Add {
|
||||
path: "/test".to_string(),
|
||||
value: json!("value"),
|
||||
observation_id: "obs-1".to_string(),
|
||||
},
|
||||
Event::Change {
|
||||
path: "/test".to_string(),
|
||||
new_value: json!("new"),
|
||||
observation_id: "obs-1".to_string(),
|
||||
},
|
||||
Event::Remove {
|
||||
path: "/test".to_string(),
|
||||
observation_id: "obs-1".to_string(),
|
||||
},
|
||||
Event::Move {
|
||||
path: "/items".to_string(),
|
||||
moves: vec![(0, 1)],
|
||||
observation_id: "obs-1".to_string(),
|
||||
},
|
||||
Event::Snapshot {
|
||||
observation_id: "snap-1".to_string(),
|
||||
timestamp,
|
||||
object: json!({"test": "state"}),
|
||||
},
|
||||
];
|
||||
|
||||
for event in events {
|
||||
let serialized = serde_json::to_string(&event).unwrap();
|
||||
|
||||
// Verify it's serialized as an array
|
||||
let as_value: Value = serde_json::from_str(&serialized).unwrap();
|
||||
assert!(as_value.is_array(), "Event should serialize to JSON array");
|
||||
|
||||
// Verify round-trip serialization/deserialization works
|
||||
let deserialized: Event = serde_json::from_str(&serialized).unwrap();
|
||||
let reserialized = serde_json::to_string(&deserialized).unwrap();
|
||||
assert_eq!(
|
||||
serialized, reserialized,
|
||||
"Round-trip serialization should be identical"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_observation_to_events() {
|
||||
let mut obs = Observation::new("obs-1".to_string(), Utc::now());
|
||||
obs.add_event(Event::Add {
|
||||
path: "/test".to_string(),
|
||||
value: json!("value"),
|
||||
observation_id: "obs-1".to_string(),
|
||||
});
|
||||
obs.add_event(Event::Change {
|
||||
path: "/test".to_string(),
|
||||
new_value: json!("new"),
|
||||
observation_id: "obs-1".to_string(),
|
||||
});
|
||||
|
||||
let events = obs.to_events();
|
||||
assert_eq!(events.len(), 3); // observe + 2 events
|
||||
|
||||
match &events[0] {
|
||||
Event::Observe { change_count, .. } => assert_eq!(*change_count, 2),
|
||||
_ => panic!("First event should be observe"),
|
||||
}
|
||||
}
|
||||
}
|
||||
71
src/flags.rs
Normal file
71
src/flags.rs
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
// json-archive is a tool for tracking JSON file changes over time
|
||||
// Copyright (C) 2025 Peoples Grocers LLC
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
//
|
||||
// To purchase a license under different terms contact admin@peoplesgrocers.com
|
||||
// To request changes, report bugs, or give user feedback contact
|
||||
// marxism@peoplesgrocers.com
|
||||
//
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
xflags::xflags! {
|
||||
cmd json-archive {
|
||||
default cmd create {
|
||||
/// Input JSON files in chronological order (first file determines default output name)
|
||||
repeated inputs: PathBuf
|
||||
|
||||
/// Output archive file path (defaults to first input + .json.archive)
|
||||
optional -o, --output output: PathBuf
|
||||
|
||||
/// Insert snapshot every N observations (optional)
|
||||
optional -s, --snapshot-interval snapshot_interval: usize
|
||||
|
||||
/// Source identifier for archive metadata
|
||||
optional --source source: String
|
||||
}
|
||||
|
||||
cmd info {
|
||||
/// Archive file to show information about
|
||||
required file: PathBuf
|
||||
|
||||
/// Output format: human-readable (default) or json
|
||||
optional --output output: String
|
||||
}
|
||||
|
||||
cmd state {
|
||||
/// Archive file to read state from
|
||||
required file: PathBuf
|
||||
|
||||
/// Get state at specific observation ID
|
||||
optional --id id: String
|
||||
|
||||
/// Get state at Nth observation in file order (not chronological)
|
||||
optional --index index: usize
|
||||
|
||||
/// Get state as of this timestamp (most recent observation <= timestamp)
|
||||
optional --as-of as_of: String
|
||||
|
||||
/// Get state right before this timestamp (most recent observation < timestamp)
|
||||
optional --before before: String
|
||||
|
||||
/// Get state after this timestamp (earliest observation > timestamp)
|
||||
optional --after after: String
|
||||
|
||||
/// Get latest state by timestamp (default if no other flags specified)
|
||||
optional --latest latest: bool
|
||||
}
|
||||
}
|
||||
}
|
||||
38
src/lib.rs
Normal file
38
src/lib.rs
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
// json-archive is a tool for tracking JSON file changes over time
|
||||
// Copyright (C) 2025 Peoples Grocers LLC
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
//
|
||||
// To purchase a license under different terms contact admin@peoplesgrocers.com
|
||||
// To request changes, report bugs, or give user feedback contact
|
||||
// marxism@peoplesgrocers.com
|
||||
//
|
||||
|
||||
pub mod archive;
|
||||
pub mod detection;
|
||||
pub mod diagnostics;
|
||||
pub mod diff;
|
||||
pub mod events;
|
||||
pub mod flags;
|
||||
pub mod pointer;
|
||||
pub mod reader;
|
||||
|
||||
pub use archive::{
|
||||
append_to_archive, create_archive_from_files, default_output_filename, ArchiveBuilder, ArchiveWriter,
|
||||
};
|
||||
pub use detection::is_json_archive;
|
||||
pub use diagnostics::{Diagnostic, DiagnosticCode, DiagnosticCollector, DiagnosticLevel};
|
||||
pub use events::{Event, Header, Observation};
|
||||
pub use pointer::JsonPointer;
|
||||
pub use reader::{ArchiveReader, ReadMode, ReadResult};
|
||||
152
src/main.rs
Normal file
152
src/main.rs
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
// json-archive is a tool for tracking JSON file changes over time
|
||||
// Copyright (C) 2025 Peoples Grocers LLC
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
//
|
||||
// To purchase a license under different terms contact admin@peoplesgrocers.com
|
||||
// To request changes, report bugs, or give user feedback contact
|
||||
// marxism@peoplesgrocers.com
|
||||
//
|
||||
|
||||
use json_archive::{
|
||||
append_to_archive, create_archive_from_files, default_output_filename, is_json_archive, Diagnostic,
|
||||
DiagnosticCode, DiagnosticLevel,
|
||||
};
|
||||
use std::path::Path;
|
||||
use std::process;
|
||||
|
||||
mod cmd;
|
||||
mod flags;
|
||||
|
||||
fn main() {
|
||||
let flags = flags::JsonArchive::from_env_or_exit();
|
||||
|
||||
let diagnostics = run(flags);
|
||||
|
||||
for diagnostic in &diagnostics {
|
||||
eprintln!("{}", diagnostic);
|
||||
}
|
||||
|
||||
let has_fatal = diagnostics.iter().any(|d| d.is_fatal());
|
||||
if has_fatal {
|
||||
process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
fn run(flags: flags::JsonArchive) -> Vec<Diagnostic> {
|
||||
match flags.subcommand {
|
||||
flags::JsonArchiveCmd::Create(create_flags) => create_archive(&create_flags),
|
||||
flags::JsonArchiveCmd::Info(info_flags) => cmd::info::run(&info_flags),
|
||||
flags::JsonArchiveCmd::State(state_flags) => cmd::state::run(&state_flags),
|
||||
}
|
||||
}
|
||||
|
||||
fn create_archive(flags: &flags::Create) -> Vec<Diagnostic> {
|
||||
if flags.inputs.is_empty() {
|
||||
return vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::MissingHeaderField,
|
||||
"I need at least one JSON file to create an archive, but you didn't provide any."
|
||||
.to_string(),
|
||||
)
|
||||
.with_advice(
|
||||
"Usage: json-archive <file1.json> [file2.json ...]\n\n\
|
||||
The first file will be used as the initial state, and subsequent files \
|
||||
will be compared to generate change events."
|
||||
.to_string(),
|
||||
)];
|
||||
}
|
||||
|
||||
let output_path = match &flags.output {
|
||||
Some(path) => path.clone(),
|
||||
None => default_output_filename(&flags.inputs[0]),
|
||||
};
|
||||
|
||||
let mut diagnostics = Vec::new();
|
||||
for input_path in &flags.inputs {
|
||||
if !Path::new(input_path).exists() {
|
||||
diagnostics.push(
|
||||
Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::PathNotFound,
|
||||
format!("I couldn't find the input file: {}", input_path.display()),
|
||||
)
|
||||
.with_advice(
|
||||
"Make sure the file path is correct and the file exists. \
|
||||
Check for typos in the filename."
|
||||
.to_string(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if !diagnostics.is_empty() {
|
||||
return diagnostics;
|
||||
}
|
||||
|
||||
let first_is_archive = match is_json_archive(&flags.inputs[0]) {
|
||||
Ok(is_archive) => is_archive,
|
||||
Err(e) => {
|
||||
return vec![Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::PathNotFound,
|
||||
format!("I couldn't check if the first file is an archive: {}", e),
|
||||
)];
|
||||
}
|
||||
};
|
||||
|
||||
if first_is_archive {
|
||||
println!("First input appears to be a JSON archive file");
|
||||
if flags.inputs.len() == 1 {
|
||||
return vec![
|
||||
Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::MissingHeaderField,
|
||||
"I found that the first input is already an archive file, but you didn't provide any additional JSON files to append.".to_string()
|
||||
)
|
||||
.with_advice(
|
||||
"If you want to append to an archive, provide additional JSON files:\n\
|
||||
json-archive existing.json.archive new1.json new2.json"
|
||||
.to_string()
|
||||
)
|
||||
];
|
||||
}
|
||||
|
||||
return append_to_archive(&flags.inputs[0], &flags.inputs[1..], &output_path, flags.source.clone(), flags.snapshot_interval);
|
||||
}
|
||||
|
||||
println!("Creating archive: {}", output_path.display());
|
||||
println!("Input files: {:?}", flags.inputs);
|
||||
|
||||
if let Some(interval) = flags.snapshot_interval {
|
||||
println!("Snapshot interval: every {} observations", interval);
|
||||
}
|
||||
|
||||
if let Some(ref source) = flags.source {
|
||||
println!("Source: {}", source);
|
||||
}
|
||||
|
||||
match create_archive_from_files(
|
||||
&flags.inputs,
|
||||
output_path.clone(),
|
||||
flags.source.clone(),
|
||||
flags.snapshot_interval,
|
||||
) {
|
||||
Ok(()) => {
|
||||
println!("Archive created successfully: {}", output_path.display());
|
||||
Vec::new()
|
||||
}
|
||||
Err(diagnostics) => diagnostics,
|
||||
}
|
||||
}
|
||||
414
src/pointer.rs
Normal file
414
src/pointer.rs
Normal file
|
|
@ -0,0 +1,414 @@
|
|||
// json-archive is a tool for tracking JSON file changes over time
|
||||
// Copyright (C) 2025 Peoples Grocers LLC
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
//
|
||||
// To purchase a license under different terms contact admin@peoplesgrocers.com
|
||||
// To request changes, report bugs, or give user feedback contact
|
||||
// marxism@peoplesgrocers.com
|
||||
//
|
||||
|
||||
use crate::diagnostics::{Diagnostic, DiagnosticCode, DiagnosticLevel};
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct JsonPointer {
|
||||
tokens: Vec<String>,
|
||||
}
|
||||
|
||||
impl JsonPointer {
|
||||
pub fn new(path: &str) -> Result<Self, Diagnostic> {
|
||||
if path.is_empty() {
|
||||
return Ok(JsonPointer { tokens: vec![] });
|
||||
}
|
||||
|
||||
if !path.starts_with('/') {
|
||||
return Err(Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::InvalidPointerSyntax,
|
||||
format!(
|
||||
"I couldn't parse the path '{}': Path must start with '/'",
|
||||
path
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
let tokens = path[1..]
|
||||
.split('/')
|
||||
.map(|token| token.replace("~1", "/").replace("~0", "~"))
|
||||
.collect();
|
||||
|
||||
Ok(JsonPointer { tokens })
|
||||
}
|
||||
|
||||
pub fn get<'a>(&self, value: &'a Value) -> Result<&'a Value, Diagnostic> {
|
||||
let mut current = value;
|
||||
|
||||
for token in &self.tokens {
|
||||
match current {
|
||||
Value::Object(obj) => {
|
||||
current = obj.get(token).ok_or_else(|| {
|
||||
Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::PathNotFound,
|
||||
format!("I couldn't find the key '{}'", token),
|
||||
)
|
||||
})?;
|
||||
}
|
||||
Value::Array(arr) => {
|
||||
let index = token.parse::<usize>().map_err(|_| {
|
||||
Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::InvalidArrayIndex,
|
||||
format!("I couldn't parse '{}' as an array index", token),
|
||||
)
|
||||
})?;
|
||||
current = arr.get(index).ok_or_else(|| {
|
||||
Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::PathNotFound,
|
||||
format!(
|
||||
"I couldn't find index {} (array length is {})",
|
||||
index,
|
||||
arr.len()
|
||||
),
|
||||
)
|
||||
})?;
|
||||
}
|
||||
_ => {
|
||||
return Err(Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::TypeMismatch,
|
||||
format!(
|
||||
"I can't index into {} with '{}'",
|
||||
current.type_name(),
|
||||
token
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(current)
|
||||
}
|
||||
|
||||
pub fn set(&self, value: &mut Value, new_value: Value) -> Result<(), Diagnostic> {
|
||||
if self.tokens.is_empty() {
|
||||
*value = new_value;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut current = value;
|
||||
let last_token = &self.tokens[self.tokens.len() - 1];
|
||||
|
||||
for token in &self.tokens[..self.tokens.len() - 1] {
|
||||
match current {
|
||||
Value::Object(obj) => {
|
||||
current = obj.get_mut(token).ok_or_else(|| {
|
||||
Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::PathNotFound,
|
||||
format!("I couldn't find the key '{}'", token),
|
||||
)
|
||||
})?;
|
||||
}
|
||||
Value::Array(arr) => {
|
||||
let index = token.parse::<usize>().map_err(|_| {
|
||||
Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::InvalidArrayIndex,
|
||||
format!("I couldn't parse '{}' as an array index", token),
|
||||
)
|
||||
})?;
|
||||
let array_len = arr.len();
|
||||
current = arr.get_mut(index).ok_or_else(|| {
|
||||
Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::PathNotFound,
|
||||
format!(
|
||||
"I couldn't find index {} (array length is {})",
|
||||
index, array_len
|
||||
),
|
||||
)
|
||||
})?;
|
||||
}
|
||||
_ => {
|
||||
return Err(Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::TypeMismatch,
|
||||
format!(
|
||||
"I can't index into {} with '{}'",
|
||||
current.type_name(),
|
||||
token
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match current {
|
||||
Value::Object(obj) => {
|
||||
obj.insert(last_token.clone(), new_value);
|
||||
}
|
||||
Value::Array(arr) => {
|
||||
let index = last_token.parse::<usize>().map_err(|_| {
|
||||
Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::InvalidArrayIndex,
|
||||
format!("I couldn't parse '{}' as an array index", last_token),
|
||||
)
|
||||
})?;
|
||||
|
||||
if index == arr.len() {
|
||||
arr.push(new_value);
|
||||
} else if index < arr.len() {
|
||||
arr[index] = new_value;
|
||||
} else {
|
||||
return Err(Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::PathNotFound,
|
||||
format!(
|
||||
"I couldn't set index {} (array length is {})",
|
||||
index,
|
||||
arr.len()
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
return Err(Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::TypeMismatch,
|
||||
format!(
|
||||
"I can't set property '{}' on {}",
|
||||
last_token,
|
||||
current.type_name()
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn remove(&self, value: &mut Value) -> Result<Value, Diagnostic> {
|
||||
if self.tokens.is_empty() {
|
||||
return Err(Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::InvalidPointerSyntax,
|
||||
"I can't remove the root value".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let mut current = value;
|
||||
let last_token = &self.tokens[self.tokens.len() - 1];
|
||||
|
||||
for token in &self.tokens[..self.tokens.len() - 1] {
|
||||
match current {
|
||||
Value::Object(obj) => {
|
||||
current = obj.get_mut(token).ok_or_else(|| {
|
||||
Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::PathNotFound,
|
||||
format!("I couldn't find the key '{}'", token),
|
||||
)
|
||||
})?;
|
||||
}
|
||||
Value::Array(arr) => {
|
||||
let index = token.parse::<usize>().map_err(|_| {
|
||||
Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::InvalidArrayIndex,
|
||||
format!("I couldn't parse '{}' as an array index", token),
|
||||
)
|
||||
})?;
|
||||
let array_len = arr.len();
|
||||
current = arr.get_mut(index).ok_or_else(|| {
|
||||
Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::PathNotFound,
|
||||
format!(
|
||||
"I couldn't find index {} (array length is {})",
|
||||
index, array_len
|
||||
),
|
||||
)
|
||||
})?;
|
||||
}
|
||||
_ => {
|
||||
return Err(Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::TypeMismatch,
|
||||
format!(
|
||||
"I can't index into {} with '{}'",
|
||||
current.type_name(),
|
||||
token
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match current {
|
||||
Value::Object(obj) => obj.remove(last_token).ok_or_else(|| {
|
||||
Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::PathNotFound,
|
||||
format!("I couldn't find the key '{}' to remove", last_token),
|
||||
)
|
||||
}),
|
||||
Value::Array(arr) => {
|
||||
let index = last_token.parse::<usize>().map_err(|_| {
|
||||
Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::InvalidArrayIndex,
|
||||
format!("I couldn't parse '{}' as an array index", last_token),
|
||||
)
|
||||
})?;
|
||||
|
||||
if index < arr.len() {
|
||||
Ok(arr.remove(index))
|
||||
} else {
|
||||
Err(Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::PathNotFound,
|
||||
format!(
|
||||
"I couldn't remove index {} (array length is {})",
|
||||
index,
|
||||
arr.len()
|
||||
),
|
||||
))
|
||||
}
|
||||
}
|
||||
_ => Err(Diagnostic::new(
|
||||
DiagnosticLevel::Fatal,
|
||||
DiagnosticCode::TypeMismatch,
|
||||
format!(
|
||||
"I can't remove property '{}' from {}",
|
||||
last_token,
|
||||
current.type_name()
|
||||
),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_string(&self) -> String {
|
||||
if self.tokens.is_empty() {
|
||||
return "".to_string();
|
||||
}
|
||||
|
||||
let escaped_tokens: Vec<String> = self
|
||||
.tokens
|
||||
.iter()
|
||||
.map(|token| token.replace("~", "~0").replace("/", "~1"))
|
||||
.collect();
|
||||
|
||||
format!("/{}", escaped_tokens.join("/"))
|
||||
}
|
||||
}
|
||||
|
||||
trait ValueTypeExt {
|
||||
fn type_name(&self) -> &'static str;
|
||||
}
|
||||
|
||||
impl ValueTypeExt for Value {
|
||||
fn type_name(&self) -> &'static str {
|
||||
match self {
|
||||
Value::Null => "null",
|
||||
Value::Bool(_) => "boolean",
|
||||
Value::Number(_) => "number",
|
||||
Value::String(_) => "string",
|
||||
Value::Array(_) => "array",
|
||||
Value::Object(_) => "object",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn test_empty_pointer() {
|
||||
let pointer = JsonPointer::new("").unwrap();
|
||||
let value = json!({"foo": "bar"});
|
||||
assert_eq!(pointer.get(&value).unwrap(), &value);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_simple_object_access() {
|
||||
let pointer = JsonPointer::new("/foo").unwrap();
|
||||
let value = json!({"foo": "bar"});
|
||||
assert_eq!(pointer.get(&value).unwrap(), &json!("bar"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_nested_object_access() {
|
||||
let pointer = JsonPointer::new("/foo/bar").unwrap();
|
||||
let value = json!({"foo": {"bar": "baz"}});
|
||||
assert_eq!(pointer.get(&value).unwrap(), &json!("baz"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_array_access() {
|
||||
let pointer = JsonPointer::new("/items/0").unwrap();
|
||||
let value = json!({"items": ["first", "second"]});
|
||||
assert_eq!(pointer.get(&value).unwrap(), &json!("first"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_escape_sequences() {
|
||||
let pointer = JsonPointer::new("/foo~1bar").unwrap();
|
||||
let value = json!({"foo/bar": "baz"});
|
||||
assert_eq!(pointer.get(&value).unwrap(), &json!("baz"));
|
||||
|
||||
let pointer = JsonPointer::new("/foo~0bar").unwrap();
|
||||
let value = json!({"foo~bar": "baz"});
|
||||
assert_eq!(pointer.get(&value).unwrap(), &json!("baz"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_set_object() {
|
||||
let pointer = JsonPointer::new("/foo").unwrap();
|
||||
let mut value = json!({"foo": "bar"});
|
||||
pointer.set(&mut value, json!("new_value")).unwrap();
|
||||
assert_eq!(value, json!({"foo": "new_value"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_set_array_append() {
|
||||
let pointer = JsonPointer::new("/items/2").unwrap();
|
||||
let mut value = json!({"items": ["first", "second"]});
|
||||
pointer.set(&mut value, json!("third")).unwrap();
|
||||
assert_eq!(value, json!({"items": ["first", "second", "third"]}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_remove_object() {
|
||||
let pointer = JsonPointer::new("/foo").unwrap();
|
||||
let mut value = json!({"foo": "bar", "baz": "qux"});
|
||||
let removed = pointer.remove(&mut value).unwrap();
|
||||
assert_eq!(removed, json!("bar"));
|
||||
assert_eq!(value, json!({"baz": "qux"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_remove_array() {
|
||||
let pointer = JsonPointer::new("/items/0").unwrap();
|
||||
let mut value = json!({"items": ["first", "second", "third"]});
|
||||
let removed = pointer.remove(&mut value).unwrap();
|
||||
assert_eq!(removed, json!("first"));
|
||||
assert_eq!(value, json!({"items": ["second", "third"]}));
|
||||
}
|
||||
}
|
||||
1005
src/reader.rs
Normal file
1005
src/reader.rs
Normal file
File diff suppressed because it is too large
Load diff
Loading…
Add table
Add a link
Reference in a new issue