2022-08-01 00:10:06 +03:00
|
|
|
//! Copyright (C) 2022, Dmitriy Pleshevskiy <dmitriy@ideascup.me>
|
|
|
|
//!
|
|
|
|
//! 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/>.
|
|
|
|
//!
|
|
|
|
|
2022-07-30 17:31:05 +03:00
|
|
|
use crate::{cli::Args, domain};
|
2022-07-31 00:54:38 +03:00
|
|
|
use std::fs::File;
|
2022-08-02 11:32:12 +03:00
|
|
|
use std::io::{stdout, Write};
|
2022-07-30 17:31:05 +03:00
|
|
|
|
|
|
|
#[derive(Debug)]
|
|
|
|
pub enum Error {
|
|
|
|
OpenFile,
|
|
|
|
Switch(domain::switch::Error),
|
|
|
|
}
|
|
|
|
|
2022-07-31 00:54:38 +03:00
|
|
|
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 {}
|
|
|
|
|
2022-07-30 17:31:05 +03:00
|
|
|
pub fn execute(args: &Args) -> Result<(), Error> {
|
2022-07-31 00:54:38 +03:00
|
|
|
let content = std::fs::read_to_string(&args.file).map_err(|_| Error::OpenFile)?;
|
2022-08-02 11:32:12 +03:00
|
|
|
|
|
|
|
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)?,
|
|
|
|
)
|
|
|
|
};
|
2022-07-30 17:31:05 +03:00
|
|
|
|
|
|
|
domain::switch::execute(domain::switch::Request {
|
2022-07-31 00:54:38 +03:00
|
|
|
content: &content,
|
2022-07-30 17:31:05 +03:00
|
|
|
writer,
|
|
|
|
sections: &args.sections,
|
|
|
|
})
|
|
|
|
.map_err(Error::Switch)
|
|
|
|
}
|