use serde::{Deserialize, Serialize};
use std::str::FromStr;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FileCommentState {
Active,
Resolved,
Deleted,
}
impl Default for FileCommentState {
fn default() -> Self {
Self::Active
}
}
impl std::fmt::Display for FileCommentState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Active => write!(f, "active"),
Self::Resolved => write!(f, "resolved"),
Self::Deleted => write!(f, "deleted"),
}
}
}
impl FromStr for FileCommentState {
type Err = StateMachineError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"active" => Ok(Self::Active),
"resolved" => Ok(Self::Resolved),
"deleted" => Ok(Self::Deleted),
_ => Err(StateMachineError::InvalidState(s.to_string())),
}
}
}
impl FileCommentState {
pub fn is_initial(&self) -> bool {
matches!(self, Self::Active)
}
pub fn is_final(&self) -> bool {
matches!(self, Self::Deleted)
}
pub fn all() -> Vec<Self> {
vec![
Self::Active,
Self::Resolved,
Self::Deleted,
]
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FileCommentTransition {
Resolve,
Edit,
DeleteActive,
Reopen,
DeleteResolved,
}
impl std::fmt::Display for FileCommentTransition {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Resolve => write!(f, "resolve"),
Self::Edit => write!(f, "edit"),
Self::DeleteActive => write!(f, "delete_active"),
Self::Reopen => write!(f, "reopen"),
Self::DeleteResolved => write!(f, "delete_resolved"),
}
}
}
impl FromStr for FileCommentTransition {
type Err = StateMachineError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"resolve" => Ok(Self::Resolve),
"edit" => Ok(Self::Edit),
"delete_active" => Ok(Self::DeleteActive),
"reopen" => Ok(Self::Reopen),
"delete_resolved" => Ok(Self::DeleteResolved),
_ => Err(StateMachineError::InvalidTransition(s.to_string())),
}
}
}
impl FileCommentTransition {
pub fn target_state(&self) -> FileCommentState {
match self {
Self::Resolve => FileCommentState::Resolved,
Self::Edit => FileCommentState::Active,
Self::DeleteActive => FileCommentState::Deleted,
Self::Reopen => FileCommentState::Active,
Self::DeleteResolved => FileCommentState::Deleted,
}
}
pub fn all() -> Vec<Self> {
vec![
Self::Resolve,
Self::Edit,
Self::DeleteActive,
Self::Reopen,
Self::DeleteResolved,
]
}
pub fn allowed_roles(&self) -> &'static [&'static str] {
match self {
Self::Resolve => &["owner", "file_owner"],
Self::Edit => &["owner"],
Self::DeleteActive => &["owner", "file_owner"],
Self::Reopen => &["user"],
Self::DeleteResolved => &["owner", "file_owner"],
}
}
}
use super::StateMachineError;
#[derive(Debug, Clone)]
pub struct FileCommentStateMachine {
current_state: FileCommentState,
}
impl FileCommentStateMachine {
pub fn new() -> Self {
Self {
current_state: FileCommentState::default(),
}
}
pub fn from_state(state: FileCommentState) -> Self {
Self { current_state: state }
}
pub fn current_state(&self) -> FileCommentState {
self.current_state
}
pub fn can_transition(&self, transition: FileCommentTransition) -> bool {
if matches!(self.current_state, FileCommentState::Deleted) {
return false;
}
match (self.current_state, transition) {
(FileCommentState::Active, FileCommentTransition::Resolve) => true,
(FileCommentState::Active, FileCommentTransition::Edit) => true,
(FileCommentState::Active, FileCommentTransition::DeleteActive) => true,
(FileCommentState::Resolved, FileCommentTransition::Reopen) => true,
(FileCommentState::Resolved, FileCommentTransition::DeleteResolved) => true,
_ => false,
}
}
pub fn can_transition_with_role(&self, transition: FileCommentTransition, role: &str) -> bool {
if !self.can_transition(transition) {
return false;
}
let allowed_roles = transition.allowed_roles();
if allowed_roles.is_empty() {
return true; }
allowed_roles.iter().any(|r| *r == role || *r == "*")
}
pub fn transition(&mut self, transition: FileCommentTransition) -> Result<FileCommentState, StateMachineError> {
if !self.can_transition(transition) {
return Err(StateMachineError::TransitionNotAllowed {
transition: transition.to_string(),
from: self.current_state.to_string(),
});
}
self.current_state = transition.target_state();
Ok(self.current_state)
}
pub fn transition_with_role(&mut self, transition: FileCommentTransition, role: &str) -> Result<FileCommentState, StateMachineError> {
if !self.can_transition(transition) {
return Err(StateMachineError::TransitionNotAllowed {
transition: transition.to_string(),
from: self.current_state.to_string(),
});
}
if !self.can_transition_with_role(transition, role) {
return Err(StateMachineError::RoleNotAuthorized {
role: role.to_string(),
transition: transition.to_string(),
});
}
self.current_state = transition.target_state();
Ok(self.current_state)
}
pub fn available_transitions(&self) -> Vec<FileCommentTransition> {
FileCommentTransition::all()
.into_iter()
.filter(|t| self.can_transition(*t))
.collect()
}
pub fn available_transitions_for_role(&self, role: &str) -> Vec<FileCommentTransition> {
FileCommentTransition::all()
.into_iter()
.filter(|t| self.can_transition_with_role(*t, role))
.collect()
}
pub fn transition_to_state(&mut self, target: FileCommentState) -> Result<FileCommentState, StateMachineError> {
let valid = FileCommentTransition::all().into_iter()
.filter(|t| self.can_transition(*t))
.find(|t| t.target_state() == target);
match valid {
Some(t) => self.transition(t),
None => Err(StateMachineError::TransitionNotAllowed {
transition: target.to_string(),
from: self.current_state.to_string(),
}),
}
}
}
impl Default for FileCommentStateMachine {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_initial_state() {
let sm = FileCommentStateMachine::new();
assert_eq!(sm.current_state(), FileCommentState::Active);
assert!(sm.current_state().is_initial());
}
#[test]
fn test_valid_transition() {
let mut sm = FileCommentStateMachine::from_state(FileCommentState::Active);
assert!(sm.can_transition(FileCommentTransition::Resolve));
let result = sm.transition(FileCommentTransition::Resolve);
assert!(result.is_ok());
assert_eq!(sm.current_state(), FileCommentState::Resolved);
}
#[test]
fn test_invalid_transition() {
let mut sm = FileCommentStateMachine::from_state(FileCommentState::Active);
let result = sm.transition(FileCommentTransition::Reopen);
assert!(result.is_err());
}
#[test]
fn test_state_parsing() {
let state: FileCommentState = "active".parse().unwrap();
assert_eq!(state, FileCommentState::Active);
}
#[test]
fn test_available_transitions() {
let sm = FileCommentStateMachine::new();
let available = sm.available_transitions();
assert!(!available.is_empty() || sm.current_state().is_final());
}
}