Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use JSON for all command output #1390

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ ctrlc = "3.2.1"
derive_more = "0.99.17"
dirs = "4.0.0"
env_logger = "0.10.0"
erased-serde = "0.3.24"
futures = "0.3.21"
hex = "0.4.3"
html-escaper = "0.2.0"
Expand Down Expand Up @@ -62,10 +63,12 @@ unindent = "0.1.7"
[[bin]]
name = "ord"
path = "src/bin/main.rs"
test = false

[lib]
name = "ord"
path = "src/lib.rs"
doctest = false

[[test]]
name = "integration"
Expand Down
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) -> Result<Box<dyn Output>> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oooooooh. we're at that stage of the project :)

self.subcommand.run(self.options)
}
}
48 changes: 36 additions & 12 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,25 @@ fn timestamp(seconds: u32) -> DateTime<Utc> {
Utc.timestamp_opt(seconds.into(), 0).unwrap()
}

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

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

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

type SubcommandResult = Result<Box<dyn Output>>;

pub fn main() {
env_logger::init();

Expand All @@ -154,18 +173,23 @@ 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() {
Ok(output) => {
output.print_json();
}
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());
}
process::exit(1);
}
process::exit(1);
}
}
8 changes: 1 addition & 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 Down
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
4 changes: 2 additions & 2 deletions src/subcommand/index.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use super::*;

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(())
}
}
6 changes: 2 additions & 4 deletions src/subcommand/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,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 All @@ -34,9 +34,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
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 @@ -94,8 +94,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 @@ -123,7 +123,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 clone = index.clone();
thread::spawn(move || loop {
Expand Down Expand Up @@ -219,7 +219,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(())
}))
}
}
2 changes: 1 addition & 1 deletion src/subcommand/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,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::run(options),
Expand Down
10 changes: 4 additions & 6 deletions src/subcommand/wallet/balance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,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 @@ -16,14 +16,12 @@ pub(crate) fn run(options: Options) -> Result {
.map(|satpoint| satpoint.outpoint)
.collect::<BTreeSet<OutPoint>>();

let mut balance = 0;
let mut cardinal = 0;
for (outpoint, amount) in get_unspent_outputs(&options)? {
if !inscription_outputs.contains(&outpoint) {
balance += amount.to_sat()
cardinal += amount.to_sat()
}
}

print_json(Output { cardinal: balance })?;

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