|
| 1 | +use std::{ |
| 2 | + fmt::{Display, Formatter}, |
| 3 | + path::{Path, PathBuf}, |
| 4 | +}; |
| 5 | + |
| 6 | +use crate::todo_file::{FileReadErrorCause, IoError}; |
| 7 | + |
| 8 | +/// Describes the state of rebase when editing the rebase todo file. |
| 9 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 10 | +#[allow(clippy::exhaustive_enums)] |
| 11 | +pub enum State { |
| 12 | + /// Editing todo at start of a rebase. |
| 13 | + Initial, |
| 14 | + /// Editing todo in the middle of a rebase with --edit. |
| 15 | + Edit, |
| 16 | + /// Editing the todo file for git-revise |
| 17 | + Revise, |
| 18 | +} |
| 19 | + |
| 20 | +pub(crate) fn detect_state(filepath: &Path) -> Result<State, IoError> { |
| 21 | + if filepath.ends_with("git-revise-todo") { |
| 22 | + return Ok(State::Revise); |
| 23 | + } |
| 24 | + if let Some(parent) = filepath.parent() { |
| 25 | + if parent.join("stopped-sha").try_exists().map_err(|err| { |
| 26 | + IoError::FileRead { |
| 27 | + file: PathBuf::from(parent), |
| 28 | + cause: FileReadErrorCause::from(err), |
| 29 | + } |
| 30 | + })? { |
| 31 | + return Ok(State::Edit); |
| 32 | + } |
| 33 | + } |
| 34 | + return Ok(State::Initial); |
| 35 | +} |
| 36 | + |
| 37 | +impl State {} |
| 38 | + |
| 39 | +impl Display for State { |
| 40 | + #[inline] |
| 41 | + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { |
| 42 | + write!(f, "{}", match *self { |
| 43 | + Self::Initial => "initial", |
| 44 | + Self::Edit => "edit", |
| 45 | + Self::Revise => "revise", |
| 46 | + }) |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +#[cfg(test)] |
| 51 | +mod tests { |
| 52 | + use rstest::rstest; |
| 53 | + |
| 54 | + use super::*; |
| 55 | + |
| 56 | + #[rstest] |
| 57 | + #[case::edit(State::Initial, "initial")] |
| 58 | + #[case::edit(State::Edit, "edit")] |
| 59 | + #[case::edit(State::Revise, "revise")] |
| 60 | + fn to_string(#[case] action: State, #[case] expected: &str) { |
| 61 | + assert_eq!(format!("{action}"), expected); |
| 62 | + } |
| 63 | +} |
0 commit comments