edit.rs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. //
  2. // imag - the personal information management suite for the commandline
  3. // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
  4. //
  5. // This library is free software; you can redistribute it and/or
  6. // modify it under the terms of the GNU Lesser General Public
  7. // License as published by the Free Software Foundation; version
  8. // 2.1 of the License.
  9. //
  10. // This library is distributed in the hope that it will be useful,
  11. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. // Lesser General Public License for more details.
  14. //
  15. // You should have received a copy of the GNU Lesser General Public
  16. // License along with this library; if not, write to the Free Software
  17. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  18. //
  19. use std::ops::DerefMut;
  20. use libimagerror::into::IntoError;
  21. use libimagrt::runtime::Runtime;
  22. use libimagstore::store::Entry;
  23. use libimagstore::store::FileLockEntry;
  24. use result::Result;
  25. use error::EditErrorKind;
  26. use error::MapErrInto;
  27. pub trait Edit {
  28. fn edit_content(&mut self, rt: &Runtime) -> Result<()>;
  29. }
  30. impl Edit for String {
  31. fn edit_content(&mut self, rt: &Runtime) -> Result<()> {
  32. edit_in_tmpfile(rt, self).map(|_| ())
  33. }
  34. }
  35. impl Edit for Entry {
  36. fn edit_content(&mut self, rt: &Runtime) -> Result<()> {
  37. edit_in_tmpfile(rt, self.get_content_mut())
  38. .map(|_| ())
  39. }
  40. }
  41. impl<'a> Edit for FileLockEntry<'a> {
  42. fn edit_content(&mut self, rt: &Runtime) -> Result<()> {
  43. self.deref_mut().edit_content(rt)
  44. }
  45. }
  46. pub fn edit_in_tmpfile(rt: &Runtime, s: &mut String) -> Result<()> {
  47. use libimagutil::edit::edit_in_tmpfile_with_command;
  48. rt.editor()
  49. .ok_or(EditErrorKind::NoEditor.into_error())
  50. .and_then(|editor| {
  51. edit_in_tmpfile_with_command(editor, s)
  52. .map_err_into(EditErrorKind::IOError)
  53. .and_then(|worked| {
  54. if !worked {
  55. Err(EditErrorKind::ProcessExitFailure.into())
  56. } else {
  57. Ok(())
  58. }
  59. })
  60. })
  61. }