vnetod/src/cli/switch.rs

57 lines
1.7 KiB
Rust

//! Copyright (C) 2022, Dmitriy Pleshevskiy <dmitriy@pleshevski.ru>
//!
//! vnetod is free software: you can redistribute it and/or modify
//! it under the terms of the GNU General Public License as published by
//! the Free Software Foundation, either version 3 of the License, or
//! (at your option) any later version.
//!
//! vnetod is distributed in the hope that it will be useful,
//! but WITHOUT ANY WARRANTY; without even the implied warranty of
//! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//! GNU General Public License for more details.
//!
//! You should have received a copy of the GNU General Public License
//! along with vnetod. If not, see <https://www.gnu.org/licenses/>.
//!
use crate::{cli::Args, domain};
use std::fs::File;
use std::io::{stdout, Write};
#[derive(Debug)]
pub enum Error {
OpenFile,
Switch(domain::switch::Error),
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::OpenFile => f.write_str("Cannot open file"),
Error::Switch(inner) => write!(f, "Cannot switch between states: {}", inner),
}
}
}
impl std::error::Error for Error {}
pub fn execute(args: &Args) -> Result<(), Error> {
let content = std::fs::read_to_string(&args.file).map_err(|_| Error::OpenFile)?;
let writer: Box<dyn Write> = if args.dry_run {
Box::new(stdout())
} else {
Box::new(
File::create(args.output.as_ref().unwrap_or(&args.file))
.map_err(|_| Error::OpenFile)?,
)
};
domain::switch::execute(domain::switch::Request {
content: &content,
writer,
sections: &args.sections,
})
.map_err(Error::Switch)
}