Last active
July 21, 2018 12:52
-
-
Save fahrradflucht/37692f3d559b1cc3b68891525b812b01 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern crate tempfile; | |
use self::tempfile::NamedTempFile; | |
use std::error::Error; | |
use std::ffi::OsString; | |
use std::io::prelude::*; | |
use std::process::Command; | |
pub fn edit_string(s: &str) -> Result<String, Box<Error>> { | |
let mut file = NamedTempFile::new()?; | |
file.write_all(s.as_bytes())?; | |
editor_output(&mut file) | |
} | |
fn editor_output(file: &mut NamedTempFile) -> Result<String, Box<Error>> { | |
use std::io::SeekFrom::Start; | |
let status = Command::new(editor_command()?) | |
.arg(file.path().as_os_str()) | |
.spawn()? | |
.wait()?; | |
if !status.success() { | |
return Err("Editor did not exit successfully. Aborting".into()); | |
} | |
let mut buffer = String::new(); | |
file.reopen()?; | |
file.seek(Start(0))?; | |
file.read_to_string(&mut buffer)?; | |
Ok(buffer) | |
} | |
fn editor_command() -> Result<OsString, Box<Error>> { | |
use std::env; | |
env::var_os("VISUAL") | |
.or_else(|| env::var_os("EDITOR")) | |
.ok_or_else(|| "Either $VISUAL or $EDITOR must be set to edit files".into()) | |
} | |
fn main() { | |
let input = edit_string("Change Me"); | |
println!("{:?}", input); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment