subcomponent 0.1.0

A components orchestrator
/*
 * Copyright (c) 2017 Jean Guyomarc'h
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

extern crate std;
extern crate getopts;
use compiler::parser;
use subprocess;
use cmd;

#[derive(Clone)]
pub struct Hook {
   name: String,
   exec: String,
   cwd: String,
   args: Option<Vec<String>>,
   /*
    * TODO
    * - env
    */
}

impl Hook {
   pub fn new(name: String, exec: String, cwd: String, args: Option<Vec<String>>) -> Hook {
      Hook {
         name: name,
         exec: exec,
         cwd: cwd,
         args: args,
      }
   }
   pub fn name_get(&self) -> &String {
      &self.name
   }
   pub fn call(&self) -> Result<(), subprocess::Error> {
      let mut cmd = std::process::Command::new(self.exec.as_str());
      cmd.stdin(std::process::Stdio::null());

      let cwd_path = std::path::Path::new(&self.cwd);
      cmd.current_dir(cwd_path);
      if let Some(ref args) = self.args {
         cmd.args(args);
      }
      debug!("Running hook {}: {:?}", self.name, cmd);
      subprocess::run(&mut cmd)?;
      Ok(())
   }

}

impl cmd::Cmd for Hook {
   #[allow(unused)]
   fn help(&self, opts: &getopts::Options) {
      println!("User hook '{}' executing the command '{}'",
               self.name, self.exec);
   }

   #[allow(unused)]
   fn getopts_set(&self, opts: &mut getopts::Options) {
      /* Nothing to do */
   }

   #[allow(unused)]
   fn getopts_matches_use(&mut self, matches: &getopts::Matches) {
      /* Nothing to do */
   }

   #[allow(unused)]
   fn run(&self, parser_arg: &Option<parser::Parser>) -> Result<(), cmd::Error> {
      self.call()?;
      Ok(())
   }
}