1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
//! This module generally takes ManagedObjects and either links them
//! to their destination, or threads off and executes the task solution.
extern crate console;
extern crate indicatif;
extern crate shellexpand;
extern crate solvent;
extern crate symlink;

pub mod config;
pub mod hmerror;
pub mod util;

use config::{ManagedObject, Worker};
use hmerror::{ErrorKind as hmek, HMError};

use console::{pad_str, style, Alignment};
use indicatif::{ProgressBar, ProgressStyle};
use solvent::DepGraph;
use std::{
  collections::HashMap,
  collections::HashSet,
  fs::metadata,
  io::{BufRead, BufReader, Error, ErrorKind},
  path::Path,
  process::{Command, Stdio},
  sync::mpsc::Sender,
  {thread, time},
};
use symlink::{symlink_dir as sd, symlink_file as sf};

///
/// Either create a symlink to a file or directory. Generally
/// we'll be doing this in a tilde'd home subdirectory, so
/// we need to be careful to get our Path right.
///
pub fn symlink_file(source: String, target: String) -> Result<(), HMError> {
  let md = match metadata(shellexpand::tilde(&source).to_string()) {
    Ok(a) => a,
    Err(e) => return Err(HMError::Io(e)),
  };
  if md.is_dir() {
    sd(
      Path::new(shellexpand::tilde(&source).to_mut()),
      Path::new(shellexpand::tilde(&target).to_mut()),
    )?;
  } else if md.is_file() {
    sf(
      Path::new(shellexpand::tilde(&source).to_mut()),
      Path::new(shellexpand::tilde(&target).to_mut()),
    )?;
  }
  Ok(())
}

///
/// Take a ManagedObject task, an mpsc tx, and a Progressbar. Execute task and regularly inform the rx
/// (all the way over back in `main()`)about our status using config::Worker.
///
/// TODO: allow the `verbose` bool to show the output of the tasks as they go.
///
/// Return () or io::Error (something went wrong in our task).
///
pub fn send_tasks_off_to_college(
  mo: &ManagedObject,
  tx: &Sender<Worker>,
  p: ProgressBar,
) -> Result<(), Error> {
  let s: String = mo.solution.clone().to_string();
  //let s1 = s.clone();
  let n: String = mo.name.clone().to_string();
  let tx1: Sender<Worker> = Sender::clone(tx);
  let _child: thread::JoinHandle<Result<(), HMError>> = thread::spawn(move || {
    let mut c = Command::new("bash")
      .arg("-c")
      .arg(s)
      .stdout(Stdio::piped())
      .stderr(Stdio::piped())
      .spawn()
      .unwrap();
    //let output = c.stdout.take().unwrap();
    //let reader = BufReader::new(output);
    /*
      reader
        .lines()
        .filter_map(|line| line.ok())
        .for_each(|line| println!("{}", line));
    }
    */
    //p.println(s1);
    p.set_style(
      ProgressStyle::default_spinner()
        .template("[{elapsed:4}] {prefix:.bold.dim} {spinner} {wide_msg}"),
    );
    p.enable_steady_tick(200);
    p.set_prefix(
      pad_str(format!("task {}", n).as_str(), 30, Alignment::Left, None)
        .into_owned()
        .as_str(),
    );
    loop {
      let mut w: Worker = Worker {
        name: n.clone(),
        status: None,
        completed: false,
      };
      match c.try_wait() {
        Ok(Some(status)) => {
          p.finish_with_message(console::style("✓").green().to_string().as_str());
          w.status = status.code();
          w.completed = true;
          tx1.send(w).unwrap();
          return Ok(());
        }
        Ok(None) => {
          tx1.send(w).unwrap();
          thread::sleep(time::Duration::from_millis(200));
        }
        Err(_e) => {
          drop(tx1);
          p.abandon_with_message("error!");
          return Err(HMError::Regular(hmek::SolutionError));
        }
      }
    }
  });
  Ok(())
}

/*
*/
///
/// Create a non-cyclical dependency graph and give it back as a Vec&lt;Vec&lt;ManagedObject&gt;&gt;.
/// Will return a CyclicalDependencyError if the graph is unsolveable.
/// Intended to be used with either mgmt::execute_solution or mgmt::send_tasks_off_to_college.
///
///
/// Example:
///
/// ```
/// let (rx, tx) = mpsc::channel();
/// let p = ProgressBar::new_spinner();
/// let v: Vec<Vec<ManagedObject>> = get_task_batches(nodes);
/// for a in v {
///   for b in a {
///     mgmt::send_tasks_off_to_college(&b, &tx, p);
///   }
/// }
/// ```
///
pub fn get_task_batches(
  nodes: HashMap<String, ManagedObject>,
) -> Result<Vec<Vec<ManagedObject>>, HMError> {
  let mut depgraph: DepGraph<String> = DepGraph::new();
  for (name, node) in nodes.clone() {
    depgraph.register_dependencies(name.to_owned(), node.dependencies.clone());
  }
  let mut tasks: Vec<Vec<ManagedObject>> = Vec::new();
  let mut _dedup: HashSet<String> = HashSet::new();
  for (name, _node) in nodes.clone() {
    let mut q: Vec<ManagedObject> = Vec::new();
    for n in depgraph.dependencies_of(&name).unwrap() {
      match n {
        Ok(r) => {
          let c = String::from(r.as_str());
          // returns true if the set DID NOT have c in it already
          if _dedup.insert(c) {
            let mut a = nodes.get(r).unwrap().to_owned();
            a.set_satisfied();
            q.push(a);
          }
        }
        Err(_e) => {
          return Err(HMError::Regular(hmek::CyclicalDependencyError));
        }
      }
    }
    tasks.push(q);
  }
  drop(_dedup);
  Ok(tasks)
}

///
/// Execute the shell commands specified in the MO's solution in a thread, so as not to block.
///
#[allow(dead_code)]
fn execute_solution(solution: String) -> Result<(), HMError> {
  // marginally adapted but mostly stolen from
  // https://rust-lang-nursery.github.io/rust-cookbook/os/external.html

  let child: thread::JoinHandle<Result<(), HMError>> = thread::spawn(|| {
    let output = Command::new("bash")
      .arg("-c")
      .arg(solution)
      .stdout(Stdio::piped())
      .spawn()?
      .stdout
      .ok_or_else(|| Error::new(ErrorKind::Other, "Couldn't capture stdout"))?;
    if cfg!(debug_assertions) {
      let reader = BufReader::new(output);
      reader
        .lines()
        .filter_map(|line| line.ok())
        .for_each(|line| println!("{}", line));
    }
    Ok(())
  });
  child.join().unwrap()
}

///
/// Pretty simple. We currently support only symlinking, but copying would be trivial.
/// Hand off to the actual function that does the work.
///
pub fn perform_operation_on(mo: ManagedObject) -> Result<(), HMError> {
  let _s = mo.method.as_str();
  match _s {
    "symlink" => {
      let source: String = mo.source;
      let destination: String = mo.destination;
      symlink_file(source, destination)
    }
    _ => {
      println!("{}", style(format!("{}", _s)).red());
      Ok(())
    }
  }
}