about summary refs log tree commit diff
path: root/src/actions/shift.rs
diff options
context:
space:
mode:
authorMel <einebeere@gmail.com>2021-09-20 22:25:55 +0200
committerMel <einebeere@gmail.com>2021-09-20 22:25:55 +0200
commitc25d22681f9bc6ddba512895182af0ce0252731b (patch)
treeeadcdec7d0b4d26d59e77169bd89b8db13e22fb6 /src/actions/shift.rs
parent8bcbf51cf4f7924600eae39db67ff653b48ad95d (diff)
downloadka-c25d22681f9bc6ddba512895182af0ce0252731b.tar.zst
ka-c25d22681f9bc6ddba512895182af0ce0252731b.zip
Split out common logic
Diffstat (limited to 'src/actions/shift.rs')
-rw-r--r--src/actions/shift.rs55
1 files changed, 55 insertions, 0 deletions
diff --git a/src/actions/shift.rs b/src/actions/shift.rs
new file mode 100644
index 0000000..c02f0ed
--- /dev/null
+++ b/src/actions/shift.rs
@@ -0,0 +1,55 @@
+use std::{
+    fs,
+    io::{self, Seek, Write},
+    path::Path,
+};
+
+use crate::{
+    files::{Locations, RepositoryPaths},
+    history::FileHistory,
+};
+
+use super::ActionOptions;
+
+pub fn shift(command_options: ActionOptions, path: &str, new_cursor: usize) -> io::Result<()> {
+    let locations = Locations::from(&command_options);
+
+    match RepositoryPaths::from_tracked(&locations, Path::new(path)) {
+        RepositoryPaths::Tracked(tracked) => {
+            let mut history_file = tracked.load_history_file()?;
+
+            let mut file_history = FileHistory::from_file(&mut history_file).unwrap();
+            file_history.set_cursor(new_cursor);
+
+            if file_history.file_is_deleted() {
+                fs::remove_file(path)?;
+            } else {
+                let new_content = file_history.get_content();
+                let mut tracked_file = tracked.create_tracked_file()?;
+
+                tracked_file.rewind()?;
+                tracked_file.set_len(0)?;
+
+                tracked_file.write_all(new_content.as_bytes())?;
+            }
+
+            file_history.write_to_file(&mut history_file)?;
+        }
+        RepositoryPaths::Deleted(deleted) => {
+            let mut history_file = deleted.load_history_file()?;
+
+            let mut file_history = FileHistory::from_file(&mut history_file).unwrap();
+            file_history.set_cursor(new_cursor);
+
+            if !file_history.file_is_deleted() {
+                let mut new_tracked_file = deleted.create_tracked_file(&locations)?;
+                let new_content = file_history.get_content();
+
+                new_tracked_file.write_all(new_content.as_bytes())?;
+            }
+        }
+        RepositoryPaths::Untracked(_) => panic!("File is not tracked with Ka."),
+    }
+
+    Ok(())
+}