use std::error::Error; use std::ffi::OsStr; use std::fmt; use std::fs::metadata; use std::io; use std::path::Path; use crate::command_runner::CommandRunner; use crate::resources::Resource; use crate::symbols::{Action, OwnedSymbolAction, Symbol, SymbolAction, SymbolRunner}; pub struct GitCheckout<'a, C: CommandRunner, T: AsRef> { target: T, source: &'a str, branch: &'a str, command_runner: &'a C, } impl<'a, C: CommandRunner, T: AsRef> GitCheckout<'a, C, T> { pub fn new(target: T, source: &'a str, branch: &'a str, command_runner: &'a C) -> Self { GitCheckout { target, source, branch, command_runner, } } } impl> fmt::Display for GitCheckout<'_, C, T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "Checkout {} (branch {}) into {}", self.source, self.branch, self.target.as_ref().display() ) } } impl> GitCheckout<'_, C, T> { fn _run_in_target_repo>(&self, args: &[S]) -> Result, Box> { let mut new_args = vec![OsStr::new("-C"), self.target.as_ref().as_ref()]; new_args.extend(args.iter().map(AsRef::as_ref)); self.command_runner.get_output("git", &new_args) } } impl> Symbol for GitCheckout<'_, C, T> { fn target_reached(&self) -> Result> { if let Err(e) = metadata(self.target.as_ref()) { return if e.kind() == io::ErrorKind::NotFound { Ok(false) } else { Err(Box::new(e)) }; } self._run_in_target_repo(&["fetch", self.source, self.branch])?; // git rev-list resolves tag objects let fetch_head = self._run_in_target_repo(&["rev-list", "-1", "FETCH_HEAD"])?; let head = self._run_in_target_repo(&["rev-list", "-1", "HEAD"])?; Ok(fetch_head == head) } fn execute(&self) -> Result<(), Box> { if !self.target.as_ref().exists() { return self.command_runner.run_successfully( "git", &[ OsStr::new("clone"), "--depth".as_ref(), "1".as_ref(), "-b".as_ref(), self.branch.as_ref(), self.source.as_ref(), self.target.as_ref().as_ref(), ], ); } self._run_in_target_repo(&["fetch", self.source, self.branch])?; self._run_in_target_repo(&["merge", "FETCH_HEAD"])?; Ok(()) } fn get_prerequisites(&self) -> Vec { vec![Resource::new( "dir", self.target.as_ref().parent().unwrap().to_string_lossy(), )] } fn provides(&self) -> Option> { Some(vec![Resource::new( "dir", self.target.as_ref().to_str().unwrap(), )]) } fn as_action<'b>(&'b self, runner: &'b dyn SymbolRunner) -> Box { Box::new(SymbolAction::new(runner, self)) } fn into_action<'b>(self: Box, runner: &'b dyn SymbolRunner) -> Box where Self: 'b, { Box::new(OwnedSymbolAction::new(runner, *self)) } } #[cfg(test)] mod test {}