sc_cli/commands/
export_chain_spec_cmd.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5
6// This program is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10
11// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// You should have received a copy of the GNU General Public License
17// along with this program. If not, see <https://www.gnu.org/licenses/>.
18
19use crate::error::Result;
20use clap::Parser;
21use sc_service::{chain_ops, ChainSpec};
22use std::{
23	fs,
24	io::{self, Write},
25	path::PathBuf,
26};
27
28/// Export a chain-spec to a JSON file in plain or in raw storage format.
29///
30/// Nodes that expose this command usually have embedded runtimes WASM blobs with
31/// genesis config presets which can be referenced via `--chain <id>` . The logic for
32/// loading the chain spec into memory based on an `id` is specific to each
33/// node and is a prerequisite to enable this command.
34///
35/// Same functionality can be achieved currently via
36/// [`crate::commands::build_spec_cmd::BuildSpecCmd`]  but we recommend
37/// `export-chain-spec` in its stead. `build-spec` is known
38///  to be a legacy mix of exporting chain specs to JSON files or
39///  converting them to raw, which will be better
40///  represented under `export-chain-spec`.
41#[derive(Debug, Clone, Parser)]
42pub struct ExportChainSpecCmd {
43	/// The chain spec identifier to export.
44	#[arg(long, default_value = "local")]
45	pub chain: String,
46
47	/// `chain-spec` JSON file path. If omitted, prints to stdout.
48	#[arg(long)]
49	pub output: Option<PathBuf>,
50
51	/// Export in raw genesis storage format.
52	#[arg(long)]
53	pub raw: bool,
54}
55
56impl ExportChainSpecCmd {
57	/// Run the export-chain-spec command
58	pub fn run(&self, spec: Box<dyn ChainSpec>) -> Result<()> {
59		let json = chain_ops::build_spec(spec.as_ref(), self.raw)?;
60		if let Some(ref path) = self.output {
61			fs::write(path, json)?;
62			println!("Exported chain spec to {}", path.display());
63		} else {
64			io::stdout().write_all(json.as_bytes()).map_err(|e| format!("{}", e))?;
65		}
66		Ok(())
67	}
68}