A library for writing host-specific, single-binary configuration management and deployment tools
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
2.0 KiB

8 years ago
  1. use std::fmt;
  2. use std::io;
  3. use command_runner::CommandRunner;
  4. use symbols::Symbol;
  5. pub struct GitCheckout<'a> {
  6. target: &'a str,
  7. source: &'a str,
  8. branch: &'a str,
  9. command_runner: &'a CommandRunner
  10. }
  11. impl<'a> GitCheckout<'a> {
  12. pub fn new(target: &'a str, source: &'a str, branch: &'a str, command_runner: &'a CommandRunner) -> GitCheckout<'a> {
  13. GitCheckout {
  14. target: target,
  15. source: source,
  16. branch: branch,
  17. command_runner: command_runner
  18. }
  19. }
  20. }
  21. impl<'a> fmt::Display for GitCheckout<'a> {
  22. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  23. write!(f, "Checkout {} (branch {}) into {}", self.source, self.branch, self.target)
  24. }
  25. }
  26. use std::fs::metadata;
  27. impl<'a> GitCheckout<'a> {
  28. fn _run_in_target_repo(&self, args: &[&str]) -> Result<Vec<u8>, io::Error> {
  29. let mut new_args = vec!["-C", self.target];
  30. new_args.extend_from_slice(args);
  31. self.command_runner.run_with_args("git", &new_args).map(|res| res.stdout)
  32. }
  33. }
  34. impl<'a> Symbol for GitCheckout<'a> {
  35. type Error = io::Error;
  36. fn target_reached(&self) -> Result<bool, Self::Error> {
  37. if let Err(e) = metadata(self.target) {
  38. return if e.kind() == io::ErrorKind::NotFound {
  39. Ok(false)
  40. } else {
  41. Err(e)
  42. };
  43. }
  44. try!(self._run_in_target_repo(&["fetch", self.source, self.branch]));
  45. let fetch_head = try!(self._run_in_target_repo(&["rev-parse", "FETCH_HEAD"]));
  46. let head = try!(self._run_in_target_repo(&["rev-parse", "HEAD"]));
  47. Ok(fetch_head == head)
  48. }
  49. fn execute(&self) -> Result<(), Self::Error> {
  50. if let Err(e) = metadata(self.target) {
  51. return if e.kind() == io::ErrorKind::NotFound {
  52. try!(self.command_runner.run_with_args("git", &["clone", "-b", self.branch, self.source, self.target]));
  53. Ok(())
  54. } else {
  55. Err(e)
  56. };
  57. }
  58. try!(self._run_in_target_repo(&["fetch", self.source, self.branch]));
  59. try!(self._run_in_target_repo(&["merge", "FETCH_HEAD"]));
  60. Ok(())
  61. }
  62. }
  63. #[cfg(test)]
  64. mod test {
  65. }