dotfiles_actions/
install_command.rs

1// Copyright (c) 2021-2022 Miguel Barreto and others
2//
3// Permission is hereby granted, free of charge, to any person obtaining
4// a copy of this software and associated documentation files (the
5// "Software"), to deal in the Software without restriction, including
6// without limitation the rights to use, copy, modify, merge, publish,
7// distribute, sublicense, and/or sell copies of the Software, and to
8// permit persons to whom the Software is furnished to do so, subject to
9// the following conditions:
10//
11// The above copyright notice and this permission notice shall be
12// included in all copies or substantial portions of the Software.
13//
14// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22//! Module that contains common code for all commands that install a package
23
24use dotfiles_core::{error::DotfilesError, exec_wrapper::execute_commands};
25use log::info;
26use std::fmt::Display;
27use subprocess::Exec;
28
29/// Trait that represents a command that installs an item using an action (brew install, brew
30/// install cask, apt install...)
31pub trait InstallCommand<F: Display> {
32  /// The base command to run
33  fn base_command(&self) -> Exec;
34  /// The arguments to pass to the command
35  fn args(&self) -> &Vec<String>;
36  /// The description of the action to run, i.e. "Installing cask"
37  fn action_description(&self) -> &str;
38  /// The name of the action to run, i.e. "cask"
39  fn action_name(&self) -> &str;
40
41  /// The item actually being installed, for example a homebrew formula.
42  fn items(&self) -> &Vec<F>;
43
44  /// a list of items to display
45  fn formatted_item_list(&self) -> Vec<String> {
46    self.items().iter().map(|it| format!("{}", it)).collect()
47  }
48
49  /// Runs the command to execut
50  fn execute(&self) -> Result<(), DotfilesError> {
51    let item_list: String = self.formatted_item_list().join(", ").into();
52    info!("{} {}", self.action_description(), item_list);
53    let mut cmd = self.base_command();
54    for arg in self.args().iter() {
55      cmd = cmd.arg(arg);
56    }
57    execute_commands(
58      vec![cmd],
59      format!("Couldn't {} {}", self.action_name(), item_list).as_str(),
60      format!(
61        "Unexpected error while {} {}",
62        self.action_description(),
63        &item_list
64      )
65      .as_str(),
66    )
67  }
68}