Skip to main content

soil_cli/commands/
export_blocks_cmd.rs

1// This file is part of Soil.
2
3// Copyright (C) Soil contributors.
4// Copyright (C) Parity Technologies (UK) Ltd.
5// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
6
7use crate::{
8	error,
9	params::{DatabaseParams, GenericNumber, PruningParams, SharedParams},
10	CliConfiguration,
11};
12use clap::Parser;
13use log::info;
14use soil_client::client_api::{BlockBackend, HeaderBackend, UsageProvider};
15use soil_service::{chain_ops::export_blocks, config::DatabaseSource};
16use std::{fmt::Debug, fs, io, path::PathBuf, str::FromStr, sync::Arc};
17use subsoil::runtime::traits::{Block as BlockT, Header as HeaderT};
18
19/// The `export-blocks` command used to export blocks.
20#[derive(Debug, Clone, Parser)]
21pub struct ExportBlocksCmd {
22	/// Output file name or stdout if unspecified.
23	#[arg()]
24	pub output: Option<PathBuf>,
25
26	/// Specify starting block number.
27	/// Default is 1.
28	#[arg(long, value_name = "BLOCK")]
29	pub from: Option<GenericNumber>,
30
31	/// Specify last block number.
32	/// Default is best block.
33	#[arg(long, value_name = "BLOCK")]
34	pub to: Option<GenericNumber>,
35
36	/// Use binary output rather than JSON.
37	#[arg(long)]
38	pub binary: bool,
39
40	#[allow(missing_docs)]
41	#[clap(flatten)]
42	pub shared_params: SharedParams,
43
44	#[allow(missing_docs)]
45	#[clap(flatten)]
46	pub pruning_params: PruningParams,
47
48	#[allow(missing_docs)]
49	#[clap(flatten)]
50	pub database_params: DatabaseParams,
51}
52
53impl ExportBlocksCmd {
54	/// Run the export-blocks command
55	pub async fn run<B, C>(
56		&self,
57		client: Arc<C>,
58		database_config: DatabaseSource,
59	) -> error::Result<()>
60	where
61		B: BlockT,
62		C: HeaderBackend<B> + BlockBackend<B> + UsageProvider<B> + 'static,
63		<<B::Header as HeaderT>::Number as FromStr>::Err: Debug,
64	{
65		if let Some(path) = database_config.path() {
66			info!("DB path: {}", path.display());
67		}
68
69		let from = self.from.as_ref().and_then(|f| f.parse().ok()).unwrap_or(1u32);
70		let to = self.to.as_ref().and_then(|t| t.parse().ok());
71
72		let binary = self.binary;
73
74		let file: Box<dyn io::Write> = match &self.output {
75			Some(filename) => Box::new(fs::File::create(filename)?),
76			None => Box::new(io::stdout()),
77		};
78
79		export_blocks(client, file, from.into(), to, binary).await.map_err(Into::into)
80	}
81}
82
83impl CliConfiguration for ExportBlocksCmd {
84	fn shared_params(&self) -> &SharedParams {
85		&self.shared_params
86	}
87
88	fn pruning_params(&self) -> Option<&PruningParams> {
89		Some(&self.pruning_params)
90	}
91
92	fn database_params(&self) -> Option<&DatabaseParams> {
93		Some(&self.database_params)
94	}
95}