referrerpolicy=no-referrer-when-downgrade

sc_cli/commands/
purge_chain_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::{
20	error,
21	params::{DatabaseParams, SharedParams},
22	CliConfiguration,
23};
24use clap::Parser;
25use sc_service::DatabaseSource;
26use std::{
27	fmt::Debug,
28	fs,
29	io::{self, Write},
30};
31
32/// The `purge-chain` command used to remove the whole chain.
33#[derive(Debug, Clone, Parser)]
34pub struct PurgeChainCmd {
35	/// Skip interactive prompt by answering yes automatically.
36	#[arg(short = 'y')]
37	pub yes: bool,
38
39	#[allow(missing_docs)]
40	#[clap(flatten)]
41	pub shared_params: SharedParams,
42
43	#[allow(missing_docs)]
44	#[clap(flatten)]
45	pub database_params: DatabaseParams,
46}
47
48impl PurgeChainCmd {
49	/// Run the purge command
50	pub fn run(&self, database_config: DatabaseSource) -> error::Result<()> {
51		let db_path = database_config.path().and_then(|p| p.parent()).ok_or_else(|| {
52			error::Error::Input("Cannot purge custom database implementation".into())
53		})?;
54
55		if !self.yes {
56			print!("Are you sure to remove {:?}? [y/N]: ", &db_path);
57			io::stdout().flush().expect("failed to flush stdout");
58
59			let mut input = String::new();
60			io::stdin().read_line(&mut input)?;
61			let input = input.trim();
62
63			match input.chars().next() {
64				Some('y') | Some('Y') => {},
65				_ => {
66					println!("Aborted");
67					return Ok(())
68				},
69			}
70		}
71
72		match fs::remove_dir_all(&db_path) {
73			Ok(_) => {
74				println!("{:?} removed.", &db_path);
75				Ok(())
76			},
77			Err(ref err) if err.kind() == io::ErrorKind::NotFound => {
78				eprintln!("{:?} did not exist.", &db_path);
79				Ok(())
80			},
81			Err(err) => Result::Err(err.into()),
82		}
83	}
84}
85
86impl CliConfiguration for PurgeChainCmd {
87	fn shared_params(&self) -> &SharedParams {
88		&self.shared_params
89	}
90
91	fn database_params(&self) -> Option<&DatabaseParams> {
92		Some(&self.database_params)
93	}
94}