iquery/
command_line.rs

1// Copyright 2020 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use crate::commands::*;
6use crate::types::*;
7use argh::FromArgs;
8use serde::Serialize;
9
10#[derive(FromArgs, PartialEq, Debug)]
11#[argh(subcommand)]
12pub enum SubCommand {
13    List(ListCommand),
14    ListAccessors(ListAccessorsCommand),
15    Selectors(SelectorsCommand),
16    Show(ShowCommand),
17}
18
19#[derive(FromArgs, PartialEq, Debug)]
20/// Top-level command.
21pub struct CommandLine {
22    #[argh(option, default = "Format::Text", short = 'f')]
23    /// the format to be used to display the results (json, text).
24    pub format: Format,
25
26    #[argh(subcommand)]
27    pub command: SubCommand,
28
29    #[argh(option)]
30    /// optional tag to print to the console before and after the normal output
31    /// of this program.
32    /// This instructs the Archivist to suspend printing serial logs from other
33    /// sources until this program has finished.
34    pub serial_tag: Option<String>,
35}
36
37fn serialize<T: Serialize + ToString>(format: &Format, input: T) -> Result<String, Error> {
38    match format {
39        Format::Json => serde_json::to_string_pretty(&input).map_err(Error::InvalidCommandResponse),
40        Format::Text => Ok(input.to_string()),
41    }
42}
43
44impl Command for CommandLine {
45    type Result = String;
46
47    async fn execute<P: DiagnosticsProvider>(self, provider: &P) -> Result<Self::Result, Error> {
48        match self.command {
49            SubCommand::List(c) => serialize(&self.format, c.execute(provider).await?),
50            SubCommand::ListAccessors(c) => serialize(&self.format, c.execute(provider).await?),
51            SubCommand::Selectors(c) => serialize(&self.format, c.execute(provider).await?),
52            SubCommand::Show(c) => serialize(&self.format, c.execute(provider).await?),
53        }
54    }
55}