From 6b105f41d22557c9a7d38b07e2c1a5638da9edc2 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sat, 2 Jan 2016 19:43:46 +0100 Subject: [PATCH] Add: ui::external::editor::edit_content() --- src/ui/external/editor.rs | 57 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/src/ui/external/editor.rs b/src/ui/external/editor.rs index 08ab6314..fb43895c 100644 --- a/src/ui/external/editor.rs +++ b/src/ui/external/editor.rs @@ -49,3 +49,60 @@ pub fn let_user_provide_content(rt: &Runtime) -> Option { Some(contents) }).unwrap_or(None) } + +/** + * Edit some content in a temporary file. If anything failes within this routine, it returns the + * old content and false. + * If the editing succeeded, it returns the new content and true + */ +pub fn edit_content(rt: &Runtime, old_content: String) -> (String, bool) { + use std::io::Read; + use std::io::Write; + use std::fs::File; + use std::process::Command; + use std::process::exit; + + let filepath = "/tmp/imag-tmp.md"; + { + let mut file = match File::create(filepath) { + Ok(f) => f, + Err(e) => { + error!("Error creating file {}", filepath); + debug!("Error creating file at '{}', error = {}", filepath, e); + exit(1); + } + }; + + file.write(old_content.as_ref()); + } + debug!("Ready with putting old content into the file"); + + let output = { + let mut cmd = rt.editor(); + cmd.arg(filepath); + debug!("cmd = {:?}", cmd); + cmd.spawn() + .and_then(|child| child.wait_with_output()) + }; + + let process_out = output.map_err(|e| { + error!("Editor call failed"); + debug!("Editor call failed: {:?}", e); + return None as Option; + }).unwrap(); + + if !process_out.status.success() { + error!("Editor call failed"); + debug!("status = {:?}", process_out.status); + debug!("stdout = {:?}", String::from_utf8(process_out.stdout)); + debug!("stderr = {:?}", String::from_utf8(process_out.stderr)); + return (old_content, false); + } + + let mut contents = String::new(); + File::open(filepath).map(|mut file| { + file.read_to_string(&mut contents); + (contents, true) + }).unwrap_or((old_content, false)) +} +