diff options
| author | tv <tv@krebsco.de> | 2026-11-19 21:00:40 +0000 |
|---|---|---|
| committer | tv <tv@krebsco.de> | 2026-11-19 22:10:36 +0100 |
| commit | edb4443510d7c8e4957e953093a25f9e7876493e (patch) | |
| tree | ed78864d7a71345c4af4da1e32ca7bbb4c2c20ed /src/federation/party.rs | |
| parent | 59cc0283117be6b4195afbe857d702e7f8ddba6e (diff) | |
continuum-party get: what counts, as JSON, a path at a time
What counts is kept by place, each place's value whole: `values` showed
it so, a place a line, and `--json` as one object keyed by places. An
application holds it as one tree.
`get [PATH]` reads it so (tree, at): each place's value at its path, the
maps on its way made, so that `get home/tv` is one object of everything
under it, and `get home/tv/hosts/laptop/ip6` reaches into a place's
value, a list's items by their index. Where a place lies under another's
value, the deeper place is the later word there (merge). Nothing at a
path is an error. `-r` writes a string as it is, as jq -r does; other
values as JSON. Bash completes it with places and the paths on their
way.
Diffstat (limited to 'src/federation/party.rs')
| -rw-r--r-- | src/federation/party.rs | 127 |
1 files changed, 127 insertions, 0 deletions
diff --git a/src/federation/party.rs b/src/federation/party.rs index 19aadbd..4902f0f 100644 --- a/src/federation/party.rs +++ b/src/federation/party.rs @@ -36,6 +36,8 @@ //! * `status`: the store, its version and parties, the party's keys and nodes, the node, //! the proposals, the versions the node refused of its own, what to sign again; //! * `values [PATH]`: the values that count, all or under `PATH`, with who writes there; +//! * `get [PATH]`: what counts at `PATH` as one JSON value (`tree`): a place's, or what lies +//! under it, places and the values within theirs; with `-r`, a string as it is; //! * `found PARTY=KEY|FILE...`: the first version of a federation, from its parties' keys, //! node lists (`--nodes`) and rules (`--rule`), to standard output; //! * `root FILE`: the root of the federation whose first version `FILE` holds (JSON), @@ -280,6 +282,21 @@ fn command() -> Command { proposals on the current version, and what the party has to sign again", )) .subcommand( + Command::new("get") + .about( + "What counts at a path, as JSON: a place's value, or what lies under it, \ + places and the values within theirs, as one object; all without a path", + ) + .arg(Arg::new("path").help("Segments by slashes (home/tv/motd); a list's items by their index")) + .arg( + Arg::new("raw") + .short('r') + .long("raw") + .action(ArgAction::SetTrue) + .help("A string as it is, not as JSON, as jq -r prints one"), + ), + ) + .subcommand( Command::new("values") .about("The values that count, each with who writes there: all, or under a path") .arg(Arg::new("path").help("The place, and those under it")) @@ -645,6 +662,24 @@ pub(crate) async fn main() -> Result<()> { if name == "values" { return values(&node, sub).await; } + if name == "get" { + let counts = node.counts().await?; + let path = sub + .get_one::<String>("path") + .map(|path| path.trim_matches('/')) + .unwrap_or_default(); + let empty = serde_json::Map::new(); + let tree = tree(counts["values"].as_object().unwrap_or(&empty), path); + let found = at(&tree, path).with_context(|| format!("nothing counts at {path}"))?; + match found { + JsonValue::String(text) if sub.get_flag("raw") => println!("{text}"), + JsonValue::Object(_) | JsonValue::Array(_) => { + println!("{}", serde_json::to_string_pretty(found)?) + } + scalar => println!("{scalar}"), + } + return Ok(()); + } if name == "show" { let counts = node.counts().await?; let proposal = proposal_named(&counts, sub)?.to_string(); @@ -1768,6 +1803,64 @@ async fn values(node: &Node, sub: &ArgMatches) -> Result<()> { Ok(()) } +/// What counts as one JSON value, from `values`, what counts at each place: each place's +/// value at its path, the maps on its way made; of those on the way to `path` or under +/// it alone (all, for an empty `path`). A place under another one's value goes into it, +/// winning over what that value held there: the deeper place is the later word. +fn tree(values: &serde_json::Map<String, JsonValue>, path: &str) -> JsonValue { + let under = (!path.is_empty()).then_some(path); + let mut places: Vec<(Vec<&str>, &JsonValue)> = values + .iter() + .filter(|(place, _)| { + is_under(place, under) || under.is_some_and(|under| is_under(under, Some(place))) + }) + .map(|(place, value)| (place.split('/').collect(), value)) + .collect(); + places.sort_by(|(a, _), (b, _)| a.len().cmp(&b.len()).then(a.cmp(b))); + let mut tree = JsonValue::Object(serde_json::Map::new()); + for (segments, value) in places { + let mut at = &mut tree; + for segment in segments { + if !at.is_object() { + *at = JsonValue::Object(serde_json::Map::new()); + } + at = at + .as_object_mut() + .expect("made an object") + .entry(segment.to_owned()) + .or_insert(JsonValue::Null); + } + merge(at, value.clone()); + } + tree +} + +/// `value` put where `at` is: objects merged, `value`'s members winning, deeply; else +/// `value` in its place. +fn merge(at: &mut JsonValue, value: JsonValue) { + match (at, value) { + (JsonValue::Object(held), JsonValue::Object(given)) => { + for (key, value) in given { + merge(held.entry(key).or_insert(JsonValue::Null), value); + } + } + (at, value) => *at = value, + } +} + +/// What `tree` holds at `path`, segments by slashes, a list's items by their index; all of +/// it for an empty `path`. +fn at<'a>(tree: &'a JsonValue, path: &str) -> Option<&'a JsonValue> { + if path.is_empty() { + return Some(tree); + } + path.split('/').try_fold(tree, |at, segment| match at { + JsonValue::Object(members) => members.get(segment), + JsonValue::Array(items) => items.get(segment.parse::<usize>().ok()?), + _ => None, + }) +} + /// Whether `place` is the place `under` names, or under it; any, where `under` is none. fn is_under(place: &str, under: Option<&str>) -> bool { under.is_none_or(|under| { @@ -2930,6 +3023,40 @@ mod tests { assert_eq!(lines[2], "keys of its key set (writes): the same"); } + /// `get` reads what counts as JSON: a place's value; what lies under a path, places and + /// the values within theirs, as one object; a list's item by its index; a deeper place + /// winning over what a value above it held there. + #[test] + fn what_counts_as_json() { + use serde_json::json; + let values = json!({ + "home/tv/motd": "hello", + "home/tv/hosts/laptop": {"ip6": "42::1", "ports": [22, 80]}, + "home/tv/hosts": {"desk": {"ip6": "42::2"}, "laptop": {"ip6": "old"}}, + "home/lass/motd": "hi", + "home/tvx/motd": "beside", + }); + let values = values.as_object().unwrap(); + let get = |path: &str| super::at(&super::tree(values, path), path).cloned(); + assert_eq!(get("home/tv/motd"), Some(json!("hello"))); + assert_eq!( + get("home/tv"), + Some(json!({ + "motd": "hello", + "hosts": { + "desk": {"ip6": "42::2"}, + "laptop": {"ip6": "42::1", "ports": [22, 80]}, + }, + })) + ); + assert_eq!(get("home/tv/hosts/desk/ip6"), Some(json!("42::2"))); + assert_eq!(get("home/tv/hosts/laptop/ports/1"), Some(json!(80))); + assert_eq!(get("home/tv/hosts/laptop/ports/2"), None); + assert_eq!(get("home/tv/elsewhere"), None); + assert_eq!(get("home").unwrap()["lass"], json!({"motd": "hi"})); + assert_eq!(get("").unwrap()["home"]["tvx"]["motd"], "beside"); + } + /// `values` shows a place and those under it, not those beside it. #[test] fn places_under_a_path() { |
