summaryrefslogtreecommitdiffstats
path: root/src/edit.rs
blob: c1e94e7646950edf5bc79fdf930b91fe112cf281 (plain)
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
use std::env;
use std::fs;
use std::path::Path;
use std::process::Command;

use crate::khline::KhLine;
use crate::KhResult;
use crate::utils::stdioutils;

pub fn edit_loop(path: &Path) -> KhResult<()> {
  loop {
    edit_file(path)?;
    let edited_cal = KhLine::new(path, None).to_cal()?;
    if let Some(errors) = edited_cal.check_for_errors() {
      if !ask_continue_editing(&errors) {
        return Err("editing aborted by user")?;
      }
    } else {
      return Ok(());
    }
  }
}

fn edit_file(path: &Path) -> KhResult<()> {
  if cfg!(test) { return Ok(()) };

  let editor = env::var("EDITOR").unwrap_or_else(|_| "vim".to_string());

  Command::new(&editor)
    .arg(path.as_os_str())
    .stdin(fs::File::open("/dev/tty").unwrap())
    .status()?;

  Ok(())
}

fn ask_continue_editing(error: &[String]) -> bool {
  println!("Calendar contains errors:\n{}", error.join("\n"));
  println!("Continue editing? y/n:");

  match stdioutils::read_single_char_from_stdin().unwrap() {
    'y' => true,
    _ => false
  }
}