h3o_cli/commands/
cell_to_parent.rs

1//! Expose [`CellIndex::parent`]
2
3use anyhow::Result as AnyResult;
4use clap::{Parser, ValueEnum};
5use h3o::{CellIndex, Resolution};
6use serde::Serialize;
7
8/// Converts an index into its parent.
9///
10/// This command generates the hierarchical parent of a cell index at the
11/// specified resolution. If the specified resolution is greater than or equal to
12/// the resolution of the index, only the given cell is returned.
13#[derive(Parser, Debug)]
14#[command(author, version)]
15pub struct Args {
16    /// Converts parents from this index.
17    #[arg(short, long)]
18    child: Option<CellIndex>,
19
20    /// Resolution, if greater than PARENT's resolution only PARENT is printed.
21    #[arg(short, long, default_value_t = Resolution::Zero)]
22    resolution: Resolution,
23
24    /// Output format.
25    #[arg(short, long, value_enum, default_value_t = Format::Text)]
26    format: Format,
27
28    /// Prettify the output (JSON only).
29    #[arg(short, long, default_value_t = false)]
30    pretty: bool,
31}
32
33#[derive(Debug, Copy, Clone, PartialEq, Eq, ValueEnum)]
34enum Format {
35    Text,
36    Json,
37}
38
39/// Run the `cellToParent` command.
40pub fn run(args: &Args) -> AnyResult<()> {
41    let indexes = crate::utils::get_cell_indexes(args.child)
42        .map(|child| child.map(|child| (child, child.parent(args.resolution))));
43
44    match args.format {
45        Format::Text => {
46            for result in indexes {
47                let (child, parent) = result?;
48                println!("{}", parent.unwrap_or(child));
49            }
50        }
51        Format::Json => {
52            #[derive(Serialize)]
53            struct ChildParent {
54                child: crate::json::CellIndex,
55                parent: Option<crate::json::CellIndex>,
56            }
57
58            let indexes = indexes
59                .map(|result| {
60                    result.map(|(child, parent)| ChildParent {
61                        child: child.into(),
62                        parent: parent.map(Into::into),
63                    })
64                })
65                .collect::<AnyResult<Vec<_>>>()?;
66
67            crate::json::print(&indexes, args.pretty)?;
68        }
69    }
70
71    Ok(())
72}