1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
//! Expose [`CellIndex::compact`]

use anyhow::{Context, Result as AnyResult};
use clap::{Parser, ValueEnum};
use h3o::CellIndex;

/// Compact the given set of indexes (from stdin).
///
/// All indexes must have the same resolution.
#[derive(Parser, Debug)]
pub struct Args {
    /// Output format.
    #[arg(short, long, value_enum, default_value_t = Format::Text)]
    format: Format,

    /// Prettify the output (JSON only).
    #[arg(short, long, default_value_t = false)]
    pretty: bool,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, ValueEnum)]
enum Format {
    Text,
    Json,
}

/// Run the `compact` command.
pub fn run(args: &Args) -> AnyResult<()> {
    let indexes =
        crate::io::read_cell_indexes().collect::<AnyResult<Vec<_>>>()?;

    let compacted = CellIndex::compact(indexes).context("compaction")?;
    match args.format {
        Format::Text => {
            for index in compacted {
                println!("{index}");
            }
        }
        Format::Json => {
            let compacted = compacted
                .into_iter()
                .map(Into::into)
                .collect::<Vec<crate::json::CellIndex>>();
            crate::json::print(&compacted, args.pretty)?;
        }
    }

    Ok(())
}