Skip to content

Commit

Permalink
Return JSON from all commands (ordinals#2355)
Browse files Browse the repository at this point in the history
  • Loading branch information
casey authored Aug 23, 2023
1 parent 68a41f7 commit 5c09dd6
Show file tree
Hide file tree
Showing 50 changed files with 244 additions and 291 deletions.
2 changes: 1 addition & 1 deletion src/arguments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ pub(crate) struct Arguments {
}

impl Arguments {
pub(crate) fn run(self) -> Result {
pub(crate) fn run(self) -> SubcommandResult {
self.subcommand.run(self.options)
}
}
33 changes: 18 additions & 15 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ use {
options::Options,
outgoing::Outgoing,
representation::Representation,
subcommand::Subcommand,
subcommand::{Subcommand, SubcommandResult},
tally::Tally,
},
anyhow::{anyhow, bail, Context, Error},
Expand Down Expand Up @@ -180,22 +180,25 @@ pub fn main() {
})
.expect("Error setting <CTRL-C> handler");

if let Err(err) = Arguments::parse().run() {
eprintln!("error: {err}");
err
.chain()
.skip(1)
.for_each(|cause| eprintln!("because: {cause}"));
if env::var_os("RUST_BACKTRACE")
.map(|val| val == "1")
.unwrap_or_default()
{
eprintln!("{}", err.backtrace());
}
match Arguments::parse().run() {
Err(err) => {
eprintln!("error: {err}");
err
.chain()
.skip(1)
.for_each(|cause| eprintln!("because: {cause}"));
if env::var_os("RUST_BACKTRACE")
.map(|val| val == "1")
.unwrap_or_default()
{
eprintln!("{}", err.backtrace());
}

gracefully_shutdown_indexer();
gracefully_shutdown_indexer();

process::exit(1);
process::exit(1);
}
Ok(output) => output.print_json(),
}

gracefully_shutdown_indexer();
Expand Down
27 changes: 20 additions & 7 deletions src/subcommand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,6 @@ pub mod supply;
pub mod traits;
pub mod wallet;

fn print_json(output: impl Serialize) -> Result {
serde_json::to_writer_pretty(io::stdout(), &output)?;
println!();
Ok(())
}

#[derive(Debug, Parser)]
pub(crate) enum Subcommand {
#[clap(about = "List the first satoshis of each reward epoch")]
Expand Down Expand Up @@ -48,7 +42,7 @@ pub(crate) enum Subcommand {
}

impl Subcommand {
pub(crate) fn run(self, options: Options) -> Result {
pub(crate) fn run(self, options: Options) -> SubcommandResult {
match self {
Self::Epochs => epochs::run(),
Self::Preview(preview) => preview.run(),
Expand All @@ -70,3 +64,22 @@ impl Subcommand {
}
}
}

#[derive(Serialize, Deserialize)]
pub struct Empty {}

pub(crate) trait Output: Send {
fn print_json(&self);
}

impl<T> Output for T
where
T: Serialize + Send,
{
fn print_json(&self) {
serde_json::to_writer_pretty(io::stdout(), self).ok();
println!();
}
}

pub(crate) type SubcommandResult = Result<Box<dyn Output>>;
6 changes: 2 additions & 4 deletions src/subcommand/epochs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,11 @@ pub struct Output {
pub starting_sats: Vec<Sat>,
}

pub(crate) fn run() -> Result {
pub(crate) fn run() -> SubcommandResult {
let mut starting_sats = Vec::new();
for sat in Epoch::STARTING_SATS {
starting_sats.push(sat);
}

print_json(Output { starting_sats })?;

Ok(())
Ok(Box::new(Output { starting_sats }))
}
7 changes: 2 additions & 5 deletions src/subcommand/find.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,13 @@ pub struct Output {
}

impl Find {
pub(crate) fn run(self, options: Options) -> Result {
pub(crate) fn run(self, options: Options) -> SubcommandResult {
let index = Index::open(&options)?;

index.update()?;

match index.find(self.sat.0)? {
Some(satpoint) => {
print_json(Output { satpoint })?;
Ok(())
}
Some(satpoint) => Ok(Box::new(Output { satpoint })),
None => Err(anyhow!("sat has not been mined as of index height")),
}
}
Expand Down
10 changes: 5 additions & 5 deletions src/subcommand/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ pub(crate) enum IndexSubcommand {
}

impl IndexSubcommand {
pub(crate) fn run(self, options: Options) -> Result {
pub(crate) fn run(self, options: Options) -> SubcommandResult {
match self {
Self::Export(export) => export.run(options),
Self::Run => index::run(options),
Expand All @@ -30,20 +30,20 @@ pub(crate) struct Export {
}

impl Export {
pub(crate) fn run(self, options: Options) -> Result {
pub(crate) fn run(self, options: Options) -> SubcommandResult {
let index = Index::open(&options)?;

index.update()?;
index.export(&self.tsv, self.include_addresses)?;

Ok(())
Ok(Box::new(Empty {}))
}
}

pub(crate) fn run(options: Options) -> Result {
pub(crate) fn run(options: Options) -> SubcommandResult {
let index = Index::open(&options)?;

index.update()?;

Ok(())
Ok(Box::new(Empty {}))
}
8 changes: 3 additions & 5 deletions src/subcommand/info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ pub struct TransactionsOutput {
}

impl Info {
pub(crate) fn run(self, options: Options) -> Result {
pub(crate) fn run(self, options: Options) -> SubcommandResult {
let index = Index::open(&options)?;
index.update()?;
let info = index.info()?;
Expand All @@ -32,11 +32,9 @@ impl Info {
elapsed: (end.starting_timestamp - start.starting_timestamp) as f64 / 1000.0 / 60.0,
});
}
print_json(output)?;
Ok(Box::new(output))
} else {
print_json(info)?;
Ok(Box::new(info))
}

Ok(())
}
}
10 changes: 4 additions & 6 deletions src/subcommand/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ pub struct Output {
}

impl List {
pub(crate) fn run(self, options: Options) -> Result {
pub(crate) fn run(self, options: Options) -> SubcommandResult {
let index = Index::open(&options)?;

index.update()?;
Expand Down Expand Up @@ -47,9 +47,7 @@ impl List {
});
}

print_json(outputs)?;

Ok(())
Ok(Box::new(outputs))
}
Some(crate::index::List::Spent) => Err(anyhow!("output spent.")),
None => Err(anyhow!("output not found")),
Expand Down Expand Up @@ -92,8 +90,8 @@ mod tests {
offset: u64,
rarity: Rarity,
name: String,
) -> Output {
Output {
) -> super::Output {
super::Output {
output,
start,
end,
Expand Down
7 changes: 3 additions & 4 deletions src/subcommand/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,9 @@ pub struct Output {
}

impl Parse {
pub(crate) fn run(self) -> Result {
print_json(Output {
pub(crate) fn run(self) -> SubcommandResult {
Ok(Box::new(Output {
object: self.object,
})?;
Ok(())
}))
}
}
6 changes: 2 additions & 4 deletions src/subcommand/preview.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ impl Drop for KillOnDrop {
}

impl Preview {
pub(crate) fn run(self) -> Result {
pub(crate) fn run(self) -> SubcommandResult {
let tmpdir = TempDir::new()?;

let rpc_port = TcpListener::bind("127.0.0.1:0")?.local_addr()?.port();
Expand Down Expand Up @@ -102,8 +102,6 @@ impl Preview {
options,
subcommand: Subcommand::Server(self.server),
}
.run()?;

Ok(())
.run()
}
}
4 changes: 2 additions & 2 deletions src/subcommand/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ pub(crate) struct Server {
}

impl Server {
pub(crate) fn run(self, options: Options, index: Arc<Index>, handle: Handle) -> Result {
pub(crate) fn run(self, options: Options, index: Arc<Index>, handle: Handle) -> SubcommandResult {
Runtime::new()?.block_on(async {
let block_index_state = BlockIndexState {
block_index: RwLock::new(BlockIndex::new(&index)?),
Expand Down Expand Up @@ -272,7 +272,7 @@ impl Server {
(None, None) => unreachable!(),
}

Ok(())
Ok(Box::new(Empty {}) as Box<dyn Output>)
})
}

Expand Down
8 changes: 3 additions & 5 deletions src/subcommand/subsidy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ pub struct Output {
}

impl Subsidy {
pub(crate) fn run(self) -> Result {
pub(crate) fn run(self) -> SubcommandResult {
let first = self.height.starting_sat();

let subsidy = self.height.subsidy();
Expand All @@ -23,12 +23,10 @@ impl Subsidy {
bail!("block {} has no subsidy", self.height);
}

print_json(Output {
Ok(Box::new(Output {
first: first.0,
subsidy,
name: first.name(),
})?;

Ok(())
}))
}
}
8 changes: 3 additions & 5 deletions src/subcommand/supply.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ pub struct Output {
pub last_mined_in_block: u64,
}

pub(crate) fn run() -> Result {
pub(crate) fn run() -> SubcommandResult {
let mut last = 0;

loop {
Expand All @@ -18,12 +18,10 @@ pub(crate) fn run() -> Result {
last += 1;
}

print_json(Output {
Ok(Box::new(Output {
supply: Sat::SUPPLY,
first: 0,
last: Sat::SUPPLY - 1,
last_mined_in_block: last,
})?;

Ok(())
}))
}
8 changes: 3 additions & 5 deletions src/subcommand/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ pub struct Output {
}

impl Traits {
pub(crate) fn run(self) -> Result {
print_json(Output {
pub(crate) fn run(self) -> SubcommandResult {
Ok(Box::new(Output {
number: self.sat.n(),
decimal: self.sat.decimal().to_string(),
degree: self.sat.degree().to_string(),
Expand All @@ -33,8 +33,6 @@ impl Traits {
period: self.sat.period(),
offset: self.sat.third(),
rarity: self.sat.rarity(),
})?;

Ok(())
}))
}
}
4 changes: 2 additions & 2 deletions src/subcommand/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use {
pub mod balance;
pub mod cardinals;
pub mod create;
pub(crate) mod inscribe;
pub mod inscribe;
pub mod inscriptions;
pub mod outputs;
pub mod receive;
Expand Down Expand Up @@ -54,7 +54,7 @@ pub(crate) enum Wallet {
}

impl Wallet {
pub(crate) fn run(self, options: Options) -> Result {
pub(crate) fn run(self, options: Options) -> SubcommandResult {
match self {
Self::Balance => balance::run(options),
Self::Create(create) => create.run(options),
Expand Down
6 changes: 2 additions & 4 deletions src/subcommand/wallet/balance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ pub struct Output {
pub cardinal: u64,
}

pub(crate) fn run(options: Options) -> Result {
pub(crate) fn run(options: Options) -> SubcommandResult {
let index = Index::open(&options)?;
index.update()?;

Expand All @@ -24,7 +24,5 @@ pub(crate) fn run(options: Options) -> Result {
}
}

print_json(Output { cardinal: balance })?;

Ok(())
Ok(Box::new(Output { cardinal: balance }))
}
Loading

0 comments on commit 5c09dd6

Please sign in to comment.