repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/flow_model/flow_id_invalid_fmt.rs
workspace_tests/src/flow_model/flow_id_invalid_fmt.rs
use std::borrow::Cow; use peace::flow_model::FlowIdInvalidFmt; #[test] fn debug() { let flow_id_invalid_fmt = FlowIdInvalidFmt::new(Cow::Borrowed("invalid id")); assert_eq!( r#"FlowIdInvalidFmt { value: "invalid id" }"#, format!("{flow_id_invalid_fmt:?}") ); } #[test] fn display() { let flow_id_invalid_fmt = FlowIdInvalidFmt::new(Cow::Borrowed("invalid id")); assert_eq!( "`invalid id` is not a valid `FlowId`.\n\ `FlowId`s must begin with a letter or underscore, and contain only letters, numbers, or underscores.", format!("{flow_id_invalid_fmt}") ); }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/flow_model/flow_id.rs
workspace_tests/src/flow_model/flow_id.rs
use std::{borrow::Cow, collections::HashMap, str::FromStr}; use peace::{ flow_model::{FlowId, FlowIdInvalidFmt}, fmt::Presentable, }; use crate::{FnInvocation, FnTrackerPresenter}; #[test] fn from_str_returns_ok_owned_for_valid_id() -> Result<(), FlowIdInvalidFmt<'static>> { let flow_id = FlowId::from_str("good_id")?; assert_eq!("good_id", *flow_id); Ok(()) } #[test] fn underscore_is_valid_first_character() -> Result<(), FlowIdInvalidFmt<'static>> { let flow_id = FlowId::new("_good_id")?; assert_eq!("_good_id", *flow_id); Ok(()) } #[test] fn new_unchecked_does_not_validate_id() -> Result<(), FlowIdInvalidFmt<'static>> { let flow_id = FlowId::new_unchecked("!valid"); assert_eq!("!valid", *flow_id); Ok(()) } #[test] fn try_from_str_returns_ok_borrowed_for_valid_id() -> Result<(), FlowIdInvalidFmt<'static>> { let flow_id = FlowId::try_from("good_id")?; assert_eq!("good_id", *flow_id); Ok(()) } #[test] fn try_from_string_returns_ok_owned_for_valid_id() -> Result<(), FlowIdInvalidFmt<'static>> { let flow_id = FlowId::try_from(String::from("good_id"))?; assert_eq!("good_id", *flow_id); Ok(()) } #[test] fn from_str_returns_err_owned_for_invalid_id() { let error = FlowId::from_str("has space").unwrap_err(); assert!(matches!(error.value(), Cow::Owned(_))); assert_eq!("has space", error.value()); } #[test] fn try_from_str_returns_err_borrowed_for_invalid_id() { let error = FlowId::try_from("has space").unwrap_err(); assert!(matches!(error.value(), Cow::Borrowed(_))); assert_eq!("has space", error.value()); } #[test] fn try_from_string_returns_err_owned_for_invalid_id() { let error = FlowId::try_from(String::from("has space")).unwrap_err(); assert!(matches!(error.value(), Cow::Owned(_))); assert_eq!("has space", error.value()); } #[test] fn display_returns_inner_str() -> Result<(), FlowIdInvalidFmt<'static>> { let flow_id = FlowId::try_from("good_id")?; assert_eq!("good_id", flow_id.to_string()); Ok(()) } #[tokio::test] async fn present_uses_code_inline() -> Result<(), Box<dyn std::error::Error>> { let mut presenter = FnTrackerPresenter::new(); let flow_id = FlowId::try_from("flow_id")?; flow_id.present(&mut presenter).await?; assert_eq!( vec![FnInvocation::new( "code_inline", vec![Some(r#""flow_id""#.to_string())] )], presenter.fn_invocations() ); Ok(()) } #[test] fn clone() -> Result<(), FlowIdInvalidFmt<'static>> { let flow_id_0 = FlowId::new("id")?; #[allow(clippy::redundant_clone)] // https://github.com/rust-lang/rust-clippy/issues/9011 let flow_id_1 = flow_id_0.clone(); assert_eq!(flow_id_0, flow_id_1); Ok(()) } #[test] fn debug() -> Result<(), FlowIdInvalidFmt<'static>> { let flow_id = FlowId::new("id")?; assert_eq!(r#"FlowId("id")"#, format!("{flow_id:?}")); Ok(()) } #[test] fn hash() -> Result<(), FlowIdInvalidFmt<'static>> { let flow_id = FlowId::new("flow_id")?; let mut hash_map = HashMap::new(); hash_map.insert(flow_id, ()); Ok(()) } #[test] fn partial_eq_ne() -> Result<(), FlowIdInvalidFmt<'static>> { let flow_id_0 = FlowId::new("id0")?; let flow_id_1 = FlowId::new("id1")?; assert!(flow_id_0 != flow_id_1); Ok(()) } #[test] fn serialize() -> Result<(), Box<dyn std::error::Error>> { let flow_id = FlowId::new("flow_id")?; assert_eq!("flow_id\n", serde_yaml::to_string(&flow_id)?); Ok(()) } #[test] fn deserialize() -> Result<(), Box<dyn std::error::Error>> { let flow_id = FlowId::new("flow_id")?; assert_eq!(flow_id, serde_yaml::from_str("flow_id")?); Ok(()) }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/flow_model/flow_info.rs
workspace_tests/src/flow_model/flow_info.rs
use peace::{ data::fn_graph::{daggy::Dag, Edge, WouldCycle}, flow_model::{flow_id, FlowInfo, FlowSpecInfo, GraphInfo, ItemInfo, ItemSpecInfo}, flow_rt::{Flow, ItemGraph, ItemGraphBuilder}, item_model::item_id, }; use peace_items::blank::BlankItem; use crate::PeaceTestError; #[test] fn clone() -> Result<(), Box<dyn std::error::Error>> { let flow_info = flow_info()?; assert_eq!(flow_info, Clone::clone(&flow_info)); Ok(()) } #[test] fn debug() -> Result<(), Box<dyn std::error::Error>> { let flow_info = flow_info()?; assert_eq!( "FlowInfo { \ flow_id: FlowId(\"flow_id\"), \ graph_info: GraphInfo { \ graph: Dag { graph: Graph { Ty: \"Directed\", node_count: 6, edge_count: 9, edges: (0, 1), (0, 2), (1, 4), (2, 3), (3, 4), (5, 4), (1, 2), (5, 1), (0, 5), node weights: {0: ItemInfo { item_id: ItemId(\"a\") }, 1: ItemInfo { item_id: ItemId(\"b\") }, 2: ItemInfo { item_id: ItemId(\"c\") }, 3: ItemInfo { item_id: ItemId(\"d\") }, 4: ItemInfo { item_id: ItemId(\"e\") }, 5: ItemInfo { item_id: ItemId(\"f\") }}, edge weights: {0: Logic, 1: Logic, 2: Logic, 3: Logic, 4: Logic, 5: Logic, 6: Data, 7: Data, 8: Data} }, cycle_state: DfsSpace { dfs: Dfs { stack: [], discovered: FixedBitSet { data: 0x10, capacity: 0, length: 0 } } } } \ } \ }", format!("{flow_info:?}") ); Ok(()) } #[test] fn serialize() -> Result<(), Box<dyn std::error::Error>> { let flow_info = flow_info()?; assert_eq!( r#"flow_id: flow_id graph_info: graph: nodes: - item_id: a - item_id: b - item_id: c - item_id: d - item_id: e - item_id: f node_holes: [] edge_property: directed edges: - - 0 - 1 - Logic - - 0 - 2 - Logic - - 1 - 4 - Logic - - 2 - 3 - Logic - - 3 - 4 - Logic - - 5 - 4 - Logic - - 1 - 2 - Data - - 5 - 1 - Data - - 0 - 5 - Data "#, serde_yaml::to_string(&flow_info)? ); Ok(()) } #[test] fn deserialize() -> Result<(), Box<dyn std::error::Error>> { let flow_info = flow_info()?; assert_eq!( flow_info, serde_yaml::from_str( r#"flow_id: flow_id graph_info: graph: nodes: - item_id: a - item_id: b - item_id: c - item_id: d - item_id: e - item_id: f node_holes: [] edge_property: directed edges: - [0, 1, Logic] - [0, 2, Logic] - [1, 4, Logic] - [2, 3, Logic] - [3, 4, Logic] - [5, 4, Logic] - [1, 2, Data] - [5, 1, Data] - [0, 5, Data] "# )? ); Ok(()) } fn flow_info() -> Result<FlowInfo, WouldCycle<Edge>> { let flow = Flow::new(flow_id!("flow_id"), complex_graph()?); let FlowSpecInfo { flow_id, graph_info, } = flow.flow_spec_info(); let mut graph = graph_info.iter_insertion_with_indices().fold( Dag::new(), |mut graph, (_, item_spec_info)| { let ItemSpecInfo { item_id } = item_spec_info; let item_info = ItemInfo::new(item_id.clone()); graph.add_node(item_info); graph }, ); let edges = graph_info .raw_edges() .iter() .map(|e| (e.source(), e.target(), e.weight)); graph.add_edges(edges).expect( "Edges are all directed from the original graph, \ so this cannot cause a cycle.", ); let graph_info = GraphInfo::new(graph); let flow_info = FlowInfo::new(flow_id, graph_info); Ok(flow_info) } fn complex_graph() -> Result<ItemGraph<PeaceTestError>, WouldCycle<Edge>> { // a - b --------- e // \ / / // '-- c - d / // / // f --------' let mut item_graph_builder = ItemGraphBuilder::new(); let [fn_id_a, fn_id_b, fn_id_c, fn_id_d, fn_id_e, fn_id_f] = item_graph_builder.add_fns([ BlankItem::<()>::new(item_id!("a")).into(), BlankItem::<()>::new(item_id!("b")).into(), BlankItem::<()>::new(item_id!("c")).into(), BlankItem::<()>::new(item_id!("d")).into(), BlankItem::<()>::new(item_id!("e")).into(), BlankItem::<()>::new(item_id!("f")).into(), ]); item_graph_builder.add_logic_edges([ (fn_id_a, fn_id_b), (fn_id_a, fn_id_c), (fn_id_b, fn_id_e), (fn_id_c, fn_id_d), (fn_id_d, fn_id_e), (fn_id_f, fn_id_e), ])?; let item_graph = item_graph_builder.build(); Ok(item_graph) }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/flow_model/item_spec_info.rs
workspace_tests/src/flow_model/item_spec_info.rs
use peace::{flow_model::ItemSpecInfo, item_model::item_id}; #[test] fn clone() { let item_spec_info = ItemSpecInfo::new(item_id!("item_id")); assert_eq!(item_spec_info, Clone::clone(&item_spec_info)); } #[test] fn debug() { let item_spec_info = ItemSpecInfo::new(item_id!("item_id")); assert_eq!( "ItemSpecInfo { item_id: ItemId(\"item_id\") }", format!("{item_spec_info:?}") ); } #[test] fn serialize() -> Result<(), serde_yaml::Error> { let item_spec_info = ItemSpecInfo::new(item_id!("item_id")); assert_eq!( "item_id: item_id\n", serde_yaml::to_string(&item_spec_info)? ); Ok(()) } #[test] fn deserialize() -> Result<(), serde_yaml::Error> { let item_spec_info = ItemSpecInfo::new(item_id!("item_id")); assert_eq!(item_spec_info, serde_yaml::from_str("item_id: item_id\n")?); Ok(()) }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/cfg/stored.rs
workspace_tests/src/cfg/stored.rs
use std::any::TypeId; use peace::{ cfg::accessors::Stored, data::{fn_graph::Resources, Data, DataAccess, DataAccessDyn, TypeIds}, item_model::{item_id, ItemId}, resource_rt::{internal::StatesMut, states::StatesCurrentStored}, }; const ITEM_SPEC_ID_TEST: &ItemId = &item_id!("item_id_test"); const ITEM_SPEC_ID_OTHER: &ItemId = &item_id!("item_id_other"); #[test] fn retrieves_state_for_item() { let mut resources = Resources::new(); let states_current_stored = { let mut states_mut = StatesMut::new(); states_mut.insert(ITEM_SPEC_ID_TEST.clone(), 123u8); StatesCurrentStored::from(states_mut) }; resources.insert(states_current_stored); let stored = Stored::<'_, u8>::borrow(ITEM_SPEC_ID_TEST, &resources); assert_eq!(Some(123), stored.get().copied()); } #[test] fn does_not_retrieve_state_for_item_other() { let mut resources = Resources::new(); let states_current_stored = { let mut states_mut = StatesMut::new(); states_mut.insert(ITEM_SPEC_ID_OTHER.clone(), 123u8); StatesCurrentStored::from(states_mut) }; resources.insert(states_current_stored); let stored = Stored::<'_, u8>::borrow(ITEM_SPEC_ID_TEST, &resources); assert_eq!(None, stored.get().copied()); } #[test] fn data_access_borrows_returns_states_current_stored_type_id() { let mut type_ids = TypeIds::new(); type_ids.push(TypeId::of::<StatesCurrentStored>()); assert_eq!(type_ids, <Stored::<'_, u8> as DataAccess>::borrows()); } #[test] fn data_access_borrow_muts_is_empty() { let type_ids = TypeIds::new(); assert_eq!(type_ids, <Stored::<'_, u8> as DataAccess>::borrow_muts()); } #[test] fn data_access_dyn_borrows_returns_states_current_stored_type_id() { let mut resources = Resources::new(); let states_current_stored = StatesCurrentStored::from(StatesMut::new()); resources.insert(states_current_stored); let stored = Stored::<'_, u8>::borrow(ITEM_SPEC_ID_TEST, &resources); let mut type_ids = TypeIds::new(); type_ids.push(TypeId::of::<StatesCurrentStored>()); assert_eq!( type_ids, <Stored::<'_, u8> as DataAccessDyn>::borrows(&stored) ); } #[test] fn data_access_dyn_borrow_muts_is_empty() { let mut resources = Resources::new(); let states_current_stored = StatesCurrentStored::from(StatesMut::new()); resources.insert(states_current_stored); let stored = Stored::<'_, u8>::borrow(ITEM_SPEC_ID_TEST, &resources); let type_ids = TypeIds::new(); assert_eq!( type_ids, <Stored::<'_, u8> as DataAccessDyn>::borrow_muts(&stored) ); } #[test] fn debug() { let mut resources = Resources::new(); let states_current_stored = { let mut states_mut = StatesMut::new(); states_mut.insert(ITEM_SPEC_ID_TEST.clone(), 123u8); StatesCurrentStored::from(states_mut) }; resources.insert(states_current_stored); let stored = Stored::<'_, u8>::borrow(ITEM_SPEC_ID_TEST, &resources); assert_eq!( r#"Stored { item_id: ItemId("item_id_test"), states_current_stored: Some(Ref { inner: States({ItemId("item_id_test"): TypedValue { type: "u8", value: 123 }}, PhantomData<peace_resource_rt::states::ts::CurrentStored>) }), marker: PhantomData<u8> }"#, format!("{stored:?}") ); let stored = Stored::<'_, u8>::borrow(ITEM_SPEC_ID_OTHER, &resources); assert_eq!( r#"Stored { item_id: ItemId("item_id_other"), states_current_stored: Some(Ref { inner: States({ItemId("item_id_test"): TypedValue { type: "u8", value: 123 }}, PhantomData<peace_resource_rt::states::ts::CurrentStored>) }), marker: PhantomData<u8> }"#, format!("{stored:?}") ); }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/cfg/state.rs
workspace_tests/src/cfg/state.rs
mod external; mod external_opt; mod nothing;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/cfg/apply_check.rs
workspace_tests/src/cfg/apply_check.rs
use peace::cfg::ApplyCheck; #[test] fn serialize() -> Result<(), serde_yaml::Error> { assert_eq!( "ExecNotRequired\n", serde_yaml::to_string(&ApplyCheck::ExecNotRequired)? ); Ok(()) } #[test] fn deserialize() -> Result<(), serde_yaml::Error> { assert_eq!( ApplyCheck::ExecNotRequired, serde_yaml::from_str("ExecNotRequired")? ); Ok(()) }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/cfg/app_name.rs
workspace_tests/src/cfg/app_name.rs
use std::{borrow::Cow, collections::HashMap, str::FromStr}; use peace::{ cfg::{AppName, AppNameInvalidFmt}, fmt::Presentable, }; use crate::{FnInvocation, FnTrackerPresenter}; #[test] fn from_str_returns_ok_owned_for_valid_app_name() -> Result<(), AppNameInvalidFmt<'static>> { let app_name = AppName::from_str("good_app_name")?; assert_eq!("good_app_name", *app_name); Ok(()) } #[test] fn underscore_is_valid_first_character() -> Result<(), AppNameInvalidFmt<'static>> { let app_name = AppName::new("_good_app_name")?; assert_eq!("_good_app_name", *app_name); Ok(()) } #[test] fn new_unchecked_does_not_validate_app_name() -> Result<(), AppNameInvalidFmt<'static>> { let app_name = AppName::new_unchecked("!valid"); assert_eq!("!valid", *app_name); Ok(()) } #[test] fn try_from_str_returns_ok_borrowed_for_valid_app_name() -> Result<(), AppNameInvalidFmt<'static>> { let app_name = AppName::try_from("good_app_name")?; assert_eq!("good_app_name", *app_name); Ok(()) } #[test] fn try_from_string_returns_ok_owned_for_valid_app_name() -> Result<(), AppNameInvalidFmt<'static>> { let app_name = AppName::try_from(String::from("good_app_name"))?; assert_eq!("good_app_name", *app_name); Ok(()) } #[test] fn from_str_returns_err_owned_for_invalid_app_name() { let error = AppName::from_str("has space").unwrap_err(); assert!(matches!(error.value(), Cow::Owned(_))); assert_eq!("has space", error.value()); } #[test] fn try_from_str_returns_err_borrowed_for_invalid_app_name() { let error = AppName::try_from("has space").unwrap_err(); assert!(matches!(error.value(), Cow::Borrowed(_))); assert_eq!("has space", error.value()); } #[test] fn try_from_string_returns_err_owned_for_invalid_app_name() { let error = AppName::try_from(String::from("has space")).unwrap_err(); assert!(matches!(error.value(), Cow::Owned(_))); assert_eq!("has space", error.value()); } #[test] fn display_returns_inner_str() -> Result<(), AppNameInvalidFmt<'static>> { let app_name = AppName::try_from("good_app_name")?; assert_eq!("good_app_name", app_name.to_string()); Ok(()) } #[tokio::test] async fn present_uses_name() -> Result<(), Box<dyn std::error::Error>> { let mut presenter = FnTrackerPresenter::new(); let app = AppName::try_from("app")?; app.present(&mut presenter).await?; assert_eq!( vec![FnInvocation::new( "name", vec![Some(r#""app""#.to_string())] )], presenter.fn_invocations() ); Ok(()) } #[test] fn clone() -> Result<(), AppNameInvalidFmt<'static>> { let app_name_0 = AppName::new("app_name")?; #[allow(clippy::redundant_clone)] // https://github.com/rust-lang/rust-clippy/issues/9011 let app_name_1 = app_name_0.clone(); assert_eq!(app_name_0, app_name_1); Ok(()) } #[test] fn debug() -> Result<(), AppNameInvalidFmt<'static>> { let app_name = AppName::new("app_name")?; assert_eq!(r#"AppName("app_name")"#, format!("{app_name:?}")); Ok(()) } #[test] fn hash() -> Result<(), AppNameInvalidFmt<'static>> { let app_name = AppName::new("app_name")?; let mut hash_map = HashMap::new(); hash_map.insert(app_name, ()); Ok(()) } #[test] fn partial_eq_ne() -> Result<(), AppNameInvalidFmt<'static>> { let app_name_0 = AppName::new("app_name0")?; let app_name_1 = AppName::new("app_name1")?; assert!(app_name_0 != app_name_1); Ok(()) } #[test] fn serialize() -> Result<(), Box<dyn std::error::Error>> { let app_name = AppName::new("app_name")?; assert_eq!("app_name\n", serde_yaml::to_string(&app_name)?); Ok(()) } #[test] fn deserialize() -> Result<(), Box<dyn std::error::Error>> { let app_name = AppName::new("app_name")?; assert_eq!(app_name, serde_yaml::from_str("app_name")?); Ok(()) }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/cfg/state/external.rs
workspace_tests/src/cfg/state/external.rs
use peace::cfg::state::External; #[test] fn display() { assert_eq!("u8 not yet determined", format!("{}", External::<u8>::Tbd)); assert_eq!("u8: 123", format!("{}", External::<u8>::Value(123))); } #[test] fn clone() { let external = &External::<u8>::Tbd; assert_eq!(External::<u8>::Tbd, external.clone()); } #[test] fn debug() { assert_eq!("Tbd", format!("{:?}", External::<u8>::Tbd)); } #[test] fn serialize() -> Result<(), Box<dyn std::error::Error>> { assert_eq!("!Tbd null\n", serde_yaml::to_string(&External::<u8>::Tbd)?); assert_eq!( "!Value 123\n", serde_yaml::to_string(&External::<u8>::Value(123))? ); Ok(()) } #[test] fn deserialize() -> Result<(), Box<dyn std::error::Error>> { let external = serde_yaml::from_str::<External<u8>>("!Tbd null\n")?; assert_eq!(External::<u8>::Tbd, external); let external = serde_yaml::from_str::<External<u8>>("!Value 123\n")?; assert_eq!(External::<u8>::Value(123), external); Ok(()) }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/cfg/state/external_opt.rs
workspace_tests/src/cfg/state/external_opt.rs
use peace::cfg::state::ExternalOpt; #[test] fn display() { assert_eq!( "u8 not yet determined", format!("{}", ExternalOpt::<u8>::Tbd) ); assert_eq!( "u8 does not exist on source", format!("{}", ExternalOpt::<u8>::None) ); assert_eq!("u8: 123", format!("{}", ExternalOpt::<u8>::Value(123))); } #[test] fn clone() { let external_opt = &ExternalOpt::<u8>::Tbd; assert_eq!(ExternalOpt::<u8>::Tbd, external_opt.clone()); } #[test] fn debug() { assert_eq!("Tbd", format!("{:?}", ExternalOpt::<u8>::Tbd)); } #[test] fn serialize() -> Result<(), Box<dyn std::error::Error>> { assert_eq!( "!Tbd null\n", serde_yaml::to_string(&ExternalOpt::<u8>::Tbd)? ); assert_eq!( "!None null\n", serde_yaml::to_string(&ExternalOpt::<u8>::None)? ); assert_eq!( "!Value 123\n", serde_yaml::to_string(&ExternalOpt::<u8>::Value(123))? ); Ok(()) } #[test] fn deserialize() -> Result<(), Box<dyn std::error::Error>> { let external = serde_yaml::from_str::<ExternalOpt<u8>>("!Tbd null\n")?; assert_eq!(ExternalOpt::<u8>::Tbd, external); let external = serde_yaml::from_str::<ExternalOpt<u8>>("!None null\n")?; assert_eq!(ExternalOpt::<u8>::None, external); let external = serde_yaml::from_str::<ExternalOpt<u8>>("!Value 123\n")?; assert_eq!(ExternalOpt::<u8>::Value(123), external); Ok(()) }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/cfg/state/nothing.rs
workspace_tests/src/cfg/state/nothing.rs
use peace::cfg::state::Nothing; #[test] fn display() { assert_eq!("", format!("{Nothing}")); } #[test] fn clone() { let nothing = &Nothing; assert_eq!(Nothing, nothing.clone()); } #[test] fn debug() { assert_eq!("Nothing", format!("{Nothing:?}")); } #[test] fn serialize() -> Result<(), Box<dyn std::error::Error>> { assert_eq!("null\n", serde_yaml::to_string(&Nothing)?); Ok(()) } #[test] fn deserialize() -> Result<(), Box<dyn std::error::Error>> { let external = serde_yaml::from_str::<Nothing>("null\n")?; assert_eq!(Nothing, external); Ok(()) }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/items/sh_cmd_item.rs
workspace_tests/src/items/sh_cmd_item.rs
use peace::{ cfg::{app_name, profile}, cmd_ctx::{CmdCtxSpsf, CmdCtxTypes, ProfileSelection}, cmd_model::CmdOutcome, data::marker::Clean, flow_model::FlowId, flow_rt::{Flow, ItemGraphBuilder}, item_model::{item_id, ItemId}, rt::cmds::{CleanCmd, DiffCmd, EnsureCmd, StatesDiscoverCmd}, rt_model::{InMemoryTextOutput, Workspace, WorkspaceSpec}, }; use peace_items::sh_cmd::{ ShCmd, ShCmdError, ShCmdItem, ShCmdParams, ShCmdState, ShCmdStateDiff, ShCmdStateLogical, }; /// Creates a file. #[derive(Clone, Copy, Debug)] pub struct TestFileCreationShCmdItem; pub type TestFileCreationShCmdState = ShCmdState<TestFileCreationShCmdItem>; impl TestFileCreationShCmdItem { /// ID pub const ID: ItemId = item_id!("test_file_creation"); /// Returns a new `TestFileCreationShCmdItem`. pub fn new() -> ShCmdItem<Self> { ShCmdItem::new(Self::ID) } fn params() -> ShCmdParams<TestFileCreationShCmdItem> { #[cfg(unix)] let sh_cmd_params = { #[cfg(feature = "item_state_example")] let state_example_sh_cmd = ShCmd::new("bash").arg("-c").arg(include_str!( "sh_cmd_item/unix/test_file_creation_state_example.sh" )); let state_clean_sh_cmd = ShCmd::new("bash").arg("-c").arg(include_str!( "sh_cmd_item/unix/test_file_creation_state_clean.sh" )); let state_current_sh_cmd = ShCmd::new("bash").arg("-c").arg(include_str!( "sh_cmd_item/unix/test_file_creation_state_current.sh" )); let state_goal_sh_cmd = ShCmd::new("bash").arg("-c").arg(include_str!( "sh_cmd_item/unix/test_file_creation_state_goal.sh" )); let state_diff_sh_cmd = ShCmd::new("bash").arg("-c").arg(include_str!( "sh_cmd_item/unix/test_file_creation_state_diff.sh" )); let apply_check_sh_cmd = ShCmd::new("bash").arg("-c").arg(include_str!( "sh_cmd_item/unix/test_file_creation_apply_check.sh" )); let apply_exec_sh_cmd = ShCmd::new("bash").arg("-c").arg(include_str!( "sh_cmd_item/unix/test_file_creation_apply_exec.sh" )); ShCmdParams::<TestFileCreationShCmdItem>::new( #[cfg(feature = "item_state_example")] state_example_sh_cmd, state_clean_sh_cmd, state_current_sh_cmd, state_goal_sh_cmd, state_diff_sh_cmd, apply_check_sh_cmd, apply_exec_sh_cmd, ) }; #[cfg(windows)] let sh_cmd_params = { #[cfg(feature = "item_state_example")] let state_example_sh_cmd = ShCmd::new("Powershell.exe") .arg("-Command") .arg(include_str!( "sh_cmd_item/windows/test_file_creation_state_example.ps1" )); let state_clean_sh_cmd = ShCmd::new("Powershell.exe") .arg("-Command") .arg(include_str!( "sh_cmd_item/windows/test_file_creation_state_clean.ps1" )); let state_current_sh_cmd = ShCmd::new("Powershell.exe") .arg("-Command") .arg(include_str!( "sh_cmd_item/windows/test_file_creation_state_current.ps1" )); let state_goal_sh_cmd = ShCmd::new("Powershell.exe") .arg("-Command") .arg(include_str!( "sh_cmd_item/windows/test_file_creation_state_goal.ps1" )); let state_diff_sh_cmd = ShCmd::new("Powershell.exe").arg("-Command").arg(concat!( "& { ", include_str!("sh_cmd_item/windows/test_file_creation_state_diff.ps1"), " }" )); let apply_check_sh_cmd = ShCmd::new("Powershell.exe").arg("-Command").arg(concat!( "& { ", include_str!("sh_cmd_item/windows/test_file_creation_apply_check.ps1"), " }" )); let apply_exec_sh_cmd = ShCmd::new("Powershell.exe").arg("-Command").arg(concat!( "& { ", include_str!("sh_cmd_item/windows/test_file_creation_apply_exec.ps1"), " }" )); ShCmdParams::<TestFileCreationShCmdItem>::new( #[cfg(feature = "item_state_example")] state_example_sh_cmd, state_clean_sh_cmd, state_current_sh_cmd, state_goal_sh_cmd, state_diff_sh_cmd, apply_check_sh_cmd, apply_exec_sh_cmd, ) }; sh_cmd_params } } #[test] fn clone() { let _sh_cmd_item = Clone::clone(&TestFileCreationShCmdItem::new()); } #[test] fn debug() { let sh_cmd_item = TestFileCreationShCmdItem::new(); assert_eq!( "ShCmdItem { \ item_id: ItemId(\"test_file_creation\"), \ marker: PhantomData<workspace_tests::items::sh_cmd_item::TestFileCreationShCmdItem> \ }", format!("{sh_cmd_item:?}") ); } #[tokio::test] async fn state_clean_returns_shell_command_clean_state() -> Result<(), Box<dyn std::error::Error>> { let tempdir = tempfile::tempdir()?; let workspace = Workspace::new( app_name!(), WorkspaceSpec::Path(tempdir.path().to_path_buf()), )?; let graph = { let mut graph_builder = ItemGraphBuilder::<ShCmdError>::new(); graph_builder.add_fn(TestFileCreationShCmdItem::new().into()); graph_builder.build() }; let flow = Flow::new(FlowId::new(crate::fn_name_short!())?, graph); let output = InMemoryTextOutput::new(); let mut cmd_ctx = CmdCtxSpsf::<TestCctShCmd>::builder() .with_workspace(workspace.into()) .with_output(output.into()) .with_profile_selection(ProfileSelection::Specified(profile!("test_profile"))) .with_flow((&flow).into()) .with_item_params::<ShCmdItem<TestFileCreationShCmdItem>>( TestFileCreationShCmdItem::ID, TestFileCreationShCmdItem::params().into(), ) .await?; StatesDiscoverCmd::current_and_goal(&mut cmd_ctx).await?; CleanCmd::exec_dry(&mut cmd_ctx).await?; let state_clean = cmd_ctx .fields() .resources() .borrow::<Clean<TestFileCreationShCmdState>>(); let Some(state_clean) = state_clean.as_ref() else { panic!( "Expected `Clean<TestFileCreationShCmdState>` to be Some after `CleanCmd::exec_dry`." ); }; if let ShCmdStateLogical::Some { stdout, stderr, marker: _, } = &state_clean.0.logical { assert_eq!("not_exists", stdout); assert_eq!("`test_file` does not exist", stderr); } else { panic!("Expected `state_clean` to be `ShCmdState::Some` after `CleanCmd::exec_dry`."); } Ok(()) } #[tokio::test] async fn state_current_returns_shell_command_current_state( ) -> Result<(), Box<dyn std::error::Error>> { let tempdir = tempfile::tempdir()?; let workspace = Workspace::new( app_name!(), WorkspaceSpec::Path(tempdir.path().to_path_buf()), )?; let graph = { let mut graph_builder = ItemGraphBuilder::<ShCmdError>::new(); graph_builder.add_fn(TestFileCreationShCmdItem::new().into()); graph_builder.build() }; let flow = Flow::new(FlowId::new(crate::fn_name_short!())?, graph); let output = InMemoryTextOutput::new(); let mut cmd_ctx = CmdCtxSpsf::<TestCctShCmd>::builder() .with_workspace(workspace.into()) .with_output(output.into()) .with_profile_selection(ProfileSelection::Specified(profile!("test_profile"))) .with_flow((&flow).into()) .with_item_params::<ShCmdItem<TestFileCreationShCmdItem>>( TestFileCreationShCmdItem::ID, TestFileCreationShCmdItem::params().into(), ) .await?; let CmdOutcome::Complete { value: states_current, cmd_blocks_processed: _, } = StatesDiscoverCmd::current(&mut cmd_ctx).await? else { panic!("Expected `StatesDiscoverCmd::current` to complete successfully."); }; let state_current = states_current .get::<TestFileCreationShCmdState, _>(&TestFileCreationShCmdItem::ID) .unwrap(); if let ShCmdStateLogical::Some { stdout, stderr, marker: _, } = &state_current.0.logical { assert_eq!("not_exists", stdout); assert_eq!("`test_file` does not exist", stderr); } else { panic!( "Expected `state_current` to be `ShCmdState::Some` after `StatesCurrent` discovery." ); } Ok(()) } #[tokio::test] async fn state_goal_returns_shell_command_goal_state() -> Result<(), Box<dyn std::error::Error>> { let tempdir = tempfile::tempdir()?; let workspace = Workspace::new( app_name!(), WorkspaceSpec::Path(tempdir.path().to_path_buf()), )?; let graph = { let mut graph_builder = ItemGraphBuilder::<ShCmdError>::new(); graph_builder.add_fn(TestFileCreationShCmdItem::new().into()); graph_builder.build() }; let flow = Flow::new(FlowId::new(crate::fn_name_short!())?, graph); let output = InMemoryTextOutput::new(); let mut cmd_ctx = CmdCtxSpsf::<TestCctShCmd>::builder() .with_workspace(workspace.into()) .with_output(output.into()) .with_profile_selection(ProfileSelection::Specified(profile!("test_profile"))) .with_flow((&flow).into()) .with_item_params::<ShCmdItem<TestFileCreationShCmdItem>>( TestFileCreationShCmdItem::ID, TestFileCreationShCmdItem::params().into(), ) .await?; let CmdOutcome::Complete { value: states_goal, cmd_blocks_processed: _, } = StatesDiscoverCmd::goal(&mut cmd_ctx).await? else { panic!("Expected `StatesDiscoverCmd::goal` to complete successfully."); }; let state_goal = states_goal .get::<ShCmdState<TestFileCreationShCmdItem>, _>(&TestFileCreationShCmdItem::ID) .unwrap(); if let ShCmdStateLogical::Some { stdout, stderr, marker: _, } = &state_goal.0.logical { assert_eq!("exists", stdout); assert_eq!("`test_file` exists", stderr); } else { panic!("Expected `state_goal` to be `ShCmdState::Some` after `StatesGoal` discovery."); } Ok(()) } #[tokio::test] async fn state_diff_returns_shell_command_state_diff() -> Result<(), Box<dyn std::error::Error>> { let tempdir = tempfile::tempdir()?; let workspace = Workspace::new( app_name!(), WorkspaceSpec::Path(tempdir.path().to_path_buf()), )?; let graph = { let mut graph_builder = ItemGraphBuilder::<ShCmdError>::new(); graph_builder.add_fn(TestFileCreationShCmdItem::new().into()); graph_builder.build() }; let flow = Flow::new(FlowId::new(crate::fn_name_short!())?, graph); let output = InMemoryTextOutput::new(); let mut cmd_ctx = CmdCtxSpsf::<TestCctShCmd>::builder() .with_workspace(workspace.into()) .with_output(output.into()) .with_profile_selection(ProfileSelection::Specified(profile!("test_profile"))) .with_flow((&flow).into()) .with_item_params::<ShCmdItem<TestFileCreationShCmdItem>>( TestFileCreationShCmdItem::ID, TestFileCreationShCmdItem::params().into(), ) .await?; // Discover current and goal states. StatesDiscoverCmd::current_and_goal(&mut cmd_ctx).await?; // Diff current and goal states. let CmdOutcome::Complete { value: state_diffs, cmd_blocks_processed: _, } = DiffCmd::diff_stored(&mut cmd_ctx).await? else { panic!("Expected `DiffCmd::diff_stored` to complete successfully."); }; let state_diff = state_diffs .get::<ShCmdStateDiff, _>(&TestFileCreationShCmdItem::ID) .unwrap(); assert_eq!("creation_required", state_diff.stdout()); assert_eq!("`test_file` will be created", state_diff.stderr()); Ok(()) } #[tokio::test] async fn ensure_when_creation_required_executes_apply_exec_shell_command( ) -> Result<(), Box<dyn std::error::Error>> { let tempdir = tempfile::tempdir()?; let workspace = Workspace::new( app_name!(), WorkspaceSpec::Path(tempdir.path().to_path_buf()), )?; let graph = { let mut graph_builder = ItemGraphBuilder::<ShCmdError>::new(); graph_builder.add_fn(TestFileCreationShCmdItem::new().into()); graph_builder.build() }; let flow = Flow::new(FlowId::new(crate::fn_name_short!())?, graph); let output = InMemoryTextOutput::new(); let mut cmd_ctx = CmdCtxSpsf::<TestCctShCmd>::builder() .with_workspace(workspace.into()) .with_output(output.into()) .with_profile_selection(ProfileSelection::Specified(profile!("test_profile"))) .with_flow((&flow).into()) .with_item_params::<ShCmdItem<TestFileCreationShCmdItem>>( TestFileCreationShCmdItem::ID, TestFileCreationShCmdItem::params().into(), ) .await?; // Discover states current and goal StatesDiscoverCmd::current_and_goal(&mut cmd_ctx).await?; // Create the file let CmdOutcome::Complete { value: states_ensured, cmd_blocks_processed: _, } = EnsureCmd::exec(&mut cmd_ctx).await? else { panic!("Expected `EnsureCmd::exec` to complete successfully."); }; let state_ensured = states_ensured .get::<TestFileCreationShCmdState, _>(&TestFileCreationShCmdItem::ID) .unwrap(); if let ShCmdStateLogical::Some { stdout, stderr, marker: _, } = &state_ensured.0.logical { assert_eq!("exists", stdout); assert_eq!("`test_file` exists", stderr); } else { panic!("Expected `state_ensured` to be `ShCmdState::Some` after `EnsureCmd` execution."); } Ok(()) } #[tokio::test] async fn ensure_when_exists_sync_does_not_reexecute_apply_exec_shell_command( ) -> Result<(), Box<dyn std::error::Error>> { let tempdir = tempfile::tempdir()?; let workspace = Workspace::new( app_name!(), WorkspaceSpec::Path(tempdir.path().to_path_buf()), )?; let graph = { let mut graph_builder = ItemGraphBuilder::<ShCmdError>::new(); graph_builder.add_fn(TestFileCreationShCmdItem::new().into()); graph_builder.build() }; let flow = Flow::new(FlowId::new(crate::fn_name_short!())?, graph); let output = InMemoryTextOutput::new(); let mut cmd_ctx = CmdCtxSpsf::<TestCctShCmd>::builder() .with_workspace(workspace.into()) .with_output(output.into()) .with_profile_selection(ProfileSelection::Specified(profile!("test_profile"))) .with_flow((&flow).into()) .with_item_params::<ShCmdItem<TestFileCreationShCmdItem>>( TestFileCreationShCmdItem::ID, TestFileCreationShCmdItem::params().into(), ) .await?; // Discover states current and goal StatesDiscoverCmd::current_and_goal(&mut cmd_ctx).await?; // Create the file EnsureCmd::exec(&mut cmd_ctx).await?; // Diff state after creation let CmdOutcome::Complete { value: state_diffs, cmd_blocks_processed: _, } = DiffCmd::diff_stored(&mut cmd_ctx).await? else { panic!("Expected `DiffCmd::diff_stored` to complete successfully."); }; let state_diff = state_diffs .get::<ShCmdStateDiff, _>(&TestFileCreationShCmdItem::ID) .unwrap(); assert_eq!("exists_sync", state_diff.stdout()); assert_eq!("nothing to do", state_diff.stderr()); // Run again, for idempotence check let CmdOutcome::Complete { value: states_ensured, cmd_blocks_processed: _, } = EnsureCmd::exec(&mut cmd_ctx).await? else { panic!("Expected `EnsureCmd::exec` to complete successfully."); }; let state_ensured = states_ensured .get::<TestFileCreationShCmdState, _>(&TestFileCreationShCmdItem::ID) .unwrap(); if let ShCmdStateLogical::Some { stdout, stderr, marker: _, } = &state_ensured.0.logical { assert_eq!("exists", stdout); assert_eq!("`test_file` exists", stderr); } else { panic!("Expected `state_ensured` to be `ShCmdState::Some` after `EnsureCmd` execution."); } Ok(()) } #[tokio::test] async fn clean_when_exists_sync_executes_shell_command() -> Result<(), Box<dyn std::error::Error>> { let tempdir = tempfile::tempdir()?; let workspace = Workspace::new( app_name!(), WorkspaceSpec::Path(tempdir.path().to_path_buf()), )?; let graph = { let mut graph_builder = ItemGraphBuilder::<ShCmdError>::new(); graph_builder.add_fn(TestFileCreationShCmdItem::new().into()); graph_builder.build() }; let flow = Flow::new(FlowId::new(crate::fn_name_short!())?, graph); let output = InMemoryTextOutput::new(); let mut cmd_ctx = CmdCtxSpsf::<TestCctShCmd>::builder() .with_workspace(workspace.into()) .with_output(output.into()) .with_profile_selection(ProfileSelection::Specified(profile!("test_profile"))) .with_flow((&flow).into()) .with_item_params::<ShCmdItem<TestFileCreationShCmdItem>>( TestFileCreationShCmdItem::ID, TestFileCreationShCmdItem::params().into(), ) .await?; // Discover states current and goal StatesDiscoverCmd::current_and_goal(&mut cmd_ctx).await?; // Create the file EnsureCmd::exec(&mut cmd_ctx).await?; assert!(tempdir.path().join("test_file").exists()); // Clean the file CleanCmd::exec(&mut cmd_ctx).await?; assert!(!tempdir.path().join("test_file").exists()); // Run again, for idempotence check let CmdOutcome::Complete { value: states_cleaned, cmd_blocks_processed: _, } = CleanCmd::exec(&mut cmd_ctx).await? else { panic!("Expected `CleanCmd::exec` to complete successfully."); }; let state_cleaned = states_cleaned .get::<TestFileCreationShCmdState, _>(&TestFileCreationShCmdItem::ID) .unwrap(); if let ShCmdStateLogical::Some { stdout, stderr, marker: _, } = &state_cleaned.0.logical { assert_eq!("not_exists", stdout); assert_eq!("`test_file` does not exist", stderr); } else { panic!("Expected `state_cleaned` to be `ShCmdState::Some` after `CleanCmd` execution."); } Ok(()) } #[derive(Debug)] pub struct TestCctShCmd; impl CmdCtxTypes for TestCctShCmd { type AppError = ShCmdError; type FlowParamsKey = (); type MappingFns = (); type Output = InMemoryTextOutput; type ProfileParamsKey = (); type WorkspaceParamsKey = (); }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/items/tar_x_item.rs
workspace_tests/src/items/tar_x_item.rs
use std::{io::Cursor, path::PathBuf}; use peace::{ cfg::{app_name, ApplyCheck, Item}, cmd_ctx::{CmdCtxSpsf, CmdCtxSpsfFields, CmdCtxTypes, ProfileSelection}, cmd_model::CmdOutcome, data::Data, flow_model::FlowId, flow_rt::{Flow, ItemGraph, ItemGraphBuilder}, item_model::{item_id, ItemId}, params::{ParamsSpec, ValueResolutionCtx, ValueResolutionMode}, profile_model::{profile, Profile}, resource_rt::paths::{FlowDir, ProfileDir}, rt::cmds::{CleanCmd, DiffCmd, EnsureCmd, StatesDiscoverCmd}, rt_model::{InMemoryTextOutput, Workspace, WorkspaceSpec}, }; use peace_items::tar_x::{ FileMetadata, FileMetadatas, TarXData, TarXError, TarXItem, TarXParams, TarXStateDiff, }; use pretty_assertions::assert_eq; use tempfile::TempDir; #[derive(Clone, Copy, Debug, PartialEq)] struct TarXTest; impl TarXTest { const ID: &'static ItemId = &item_id!("tar_x_test"); } /// Contains two files: `a` and `sub/c`. const TAR_X1_TAR: &[u8] = include_bytes!("tar_x_item/tar_x1.tar"); /// Time that the `a` and `sub/c` files in `tar_x_1.tar` were modified. const TAR_X1_MTIME: u64 = 1671674955; /// Contains two files: `b` and `sub/d`. const TAR_X2_TAR: &[u8] = include_bytes!("tar_x_item/tar_x2.tar"); /// Time that the `b` and `sub/a` files in `tar_x.tar` were modified. const TAR_X2_MTIME: u64 = 1671675052; #[test] fn clone() { let _item = Clone::clone(&TarXItem::<()>::new(TarXTest::ID.clone())); } #[tokio::test] async fn state_current_returns_empty_file_metadatas_when_extraction_folder_not_exists( ) -> Result<(), Box<dyn std::error::Error>> { let flow_id = FlowId::new(crate::fn_name_short!())?; let TestEnv { tempdir: _tempdir, workspace, profile, graph, output, tar_path, dest, } = test_env(&flow_id, TAR_X2_TAR).await?; let flow = Flow::new(flow_id, graph); let mut cmd_ctx = CmdCtxSpsf::<TestCctTarX>::builder() .with_workspace(workspace.into()) .with_output(output.into()) .with_profile_selection(ProfileSelection::Specified(profile.clone())) .with_flow((&flow).into()) .with_item_params::<TarXItem<TarXTest>>( TarXTest::ID.clone(), TarXParams::<TarXTest>::new(tar_path, dest).into(), ) .await?; let CmdOutcome::Complete { value: states_current, cmd_blocks_processed: _, } = StatesDiscoverCmd::current(&mut cmd_ctx).await? else { panic!("Expected `StatesDiscoverCmd::current` to complete successfully."); }; let state_current = states_current .get::<FileMetadatas, _>(TarXTest::ID) .unwrap(); assert_eq!(&FileMetadatas::default(), state_current); Ok(()) } #[tokio::test] async fn state_current_returns_file_metadatas_when_extraction_folder_contains_file( ) -> Result<(), Box<dyn std::error::Error>> { let flow_id = FlowId::new(crate::fn_name_short!())?; let TestEnv { tempdir: _tempdir, workspace, profile, graph, output, tar_path, dest, } = test_env(&flow_id, TAR_X2_TAR).await?; let flow = Flow::new(flow_id, graph); let b_path = PathBuf::from("b"); let d_path = PathBuf::from("sub").join("d"); // Create files in the destination. tokio::fs::create_dir(&dest).await?; tar::Archive::new(Cursor::new(TAR_X2_TAR)).unpack(&dest)?; let mut cmd_ctx = CmdCtxSpsf::<TestCctTarX>::builder() .with_workspace(workspace.into()) .with_output(output.into()) .with_profile_selection(ProfileSelection::Specified(profile.clone())) .with_flow((&flow).into()) .with_item_params::<TarXItem<TarXTest>>( TarXTest::ID.clone(), TarXParams::<TarXTest>::new(tar_path, dest).into(), ) .await?; let CmdOutcome::Complete { value: states_current, cmd_blocks_processed: _, } = StatesDiscoverCmd::current(&mut cmd_ctx).await? else { panic!("Expected `StatesDiscoverCmd::current` to complete successfully."); }; let state_current = states_current .get::<FileMetadatas, _>(TarXTest::ID) .unwrap(); assert_eq!( &FileMetadatas::from(vec![ FileMetadata::new(b_path, TAR_X2_MTIME), FileMetadata::new(d_path, TAR_X2_MTIME), ]), state_current ); Ok(()) } #[tokio::test] async fn state_goal_returns_file_metadatas_from_tar() -> Result<(), Box<dyn std::error::Error>> { let flow_id = FlowId::new(crate::fn_name_short!())?; let TestEnv { tempdir: _tempdir, workspace, profile, graph, output, tar_path, dest, } = test_env(&flow_id, TAR_X2_TAR).await?; let flow = Flow::new(flow_id, graph); let b_path = PathBuf::from("b"); let d_path = PathBuf::from("sub").join("d"); let mut cmd_ctx = CmdCtxSpsf::<TestCctTarX>::builder() .with_workspace(workspace.into()) .with_output(output.into()) .with_profile_selection(ProfileSelection::Specified(profile.clone())) .with_flow((&flow).into()) .with_item_params::<TarXItem<TarXTest>>( TarXTest::ID.clone(), TarXParams::<TarXTest>::new(tar_path, dest).into(), ) .await?; let CmdOutcome::Complete { value: states_goal, cmd_blocks_processed: _, } = StatesDiscoverCmd::goal(&mut cmd_ctx).await? else { panic!("Expected `StatesDiscoverCmd::goal` to complete successfully."); }; let state_goal = states_goal.get::<FileMetadatas, _>(TarXTest::ID).unwrap(); assert_eq!( &FileMetadatas::from(vec![ FileMetadata::new(b_path, TAR_X2_MTIME), FileMetadata::new(d_path, TAR_X2_MTIME), ]), state_goal ); Ok(()) } #[tokio::test] async fn state_diff_includes_added_when_file_in_tar_is_not_in_dest( ) -> Result<(), Box<dyn std::error::Error>> { let flow_id = FlowId::new(crate::fn_name_short!())?; let TestEnv { tempdir: _tempdir, workspace, profile, graph, output, tar_path, dest, } = test_env(&flow_id, TAR_X2_TAR).await?; let flow = Flow::new(flow_id, graph); let b_path = PathBuf::from("b"); let d_path = PathBuf::from("sub").join("d"); let mut cmd_ctx = CmdCtxSpsf::<TestCctTarX>::builder() .with_workspace(workspace.into()) .with_output(output.into()) .with_profile_selection(ProfileSelection::Specified(profile.clone())) .with_flow((&flow).into()) .with_item_params::<TarXItem<TarXTest>>( TarXTest::ID.clone(), TarXParams::<TarXTest>::new(tar_path, dest).into(), ) .await?; StatesDiscoverCmd::current_and_goal(&mut cmd_ctx).await?; // Diff current and goal states. let CmdOutcome::Complete { value: state_diffs, cmd_blocks_processed: _, } = DiffCmd::diff_stored(&mut cmd_ctx).await? else { panic!("Expected `DiffCmd::diff_stored` to complete successfully."); }; let state_diff = state_diffs.get::<TarXStateDiff, _>(TarXTest::ID).unwrap(); assert_eq!( &TarXStateDiff::ExtractionOutOfSync { added: FileMetadatas::from(vec![ FileMetadata::new(b_path, TAR_X2_MTIME), FileMetadata::new(d_path, TAR_X2_MTIME), ]), modified: FileMetadatas::default(), removed: FileMetadatas::default() }, state_diff ); Ok(()) } #[tokio::test] async fn state_diff_includes_added_when_file_in_tar_is_not_in_dest_and_dest_file_name_greater( ) -> Result<(), Box<dyn std::error::Error>> { let flow_id = FlowId::new(crate::fn_name_short!())?; let TestEnv { tempdir: _tempdir, workspace, profile, graph, output, tar_path, dest, } = test_env(&flow_id, TAR_X2_TAR).await?; let flow = Flow::new(flow_id, graph); let a_path = PathBuf::from("a"); let b_path = PathBuf::from("b"); let c_path = PathBuf::from("sub").join("c"); let d_path = PathBuf::from("sub").join("d"); // Create files in the destination. tokio::fs::create_dir(&dest).await?; tar::Archive::new(Cursor::new(TAR_X1_TAR)).unpack(&dest)?; let mut cmd_ctx = CmdCtxSpsf::<TestCctTarX>::builder() .with_workspace(workspace.into()) .with_output(output.into()) .with_profile_selection(ProfileSelection::Specified(profile.clone())) .with_flow((&flow).into()) .with_item_params::<TarXItem<TarXTest>>( TarXTest::ID.clone(), TarXParams::<TarXTest>::new(tar_path, dest).into(), ) .await?; StatesDiscoverCmd::current_and_goal(&mut cmd_ctx).await?; // Diff current and goal states. let CmdOutcome::Complete { value: state_diffs, cmd_blocks_processed: _, } = DiffCmd::diff_stored(&mut cmd_ctx).await? else { panic!("Expected `DiffCmd::diff_stored` to complete successfully."); }; let state_diff = state_diffs.get::<TarXStateDiff, _>(TarXTest::ID).unwrap(); assert_eq!( &TarXStateDiff::ExtractionOutOfSync { added: FileMetadatas::from(vec![ FileMetadata::new(b_path, TAR_X2_MTIME), FileMetadata::new(d_path, TAR_X2_MTIME), ]), modified: FileMetadatas::default(), removed: FileMetadatas::from(vec![ FileMetadata::new(a_path, TAR_X1_MTIME), FileMetadata::new(c_path, TAR_X1_MTIME), ]) }, state_diff ); Ok(()) } #[tokio::test] async fn state_diff_includes_removed_when_file_in_dest_is_not_in_tar_and_tar_file_name_greater( ) -> Result<(), Box<dyn std::error::Error>> { let flow_id = FlowId::new(crate::fn_name_short!())?; let TestEnv { tempdir: _tempdir, workspace, profile, graph, output, tar_path, dest, } = test_env(&flow_id, TAR_X2_TAR).await?; let flow = Flow::new(flow_id, graph); let a_path = PathBuf::from("a"); let c_path = PathBuf::from("sub").join("c"); // Create files in the destination. tokio::fs::create_dir(&dest).await?; tar::Archive::new(Cursor::new(TAR_X1_TAR)).unpack(&dest)?; tar::Archive::new(Cursor::new(TAR_X2_TAR)).unpack(&dest)?; let mut cmd_ctx = CmdCtxSpsf::<TestCctTarX>::builder() .with_workspace(workspace.into()) .with_output(output.into()) .with_profile_selection(ProfileSelection::Specified(profile.clone())) .with_flow((&flow).into()) .with_item_params::<TarXItem<TarXTest>>( TarXTest::ID.clone(), TarXParams::<TarXTest>::new(tar_path, dest).into(), ) .await?; StatesDiscoverCmd::current_and_goal(&mut cmd_ctx).await?; // Diff current and goal states. let CmdOutcome::Complete { value: state_diffs, cmd_blocks_processed: _, } = DiffCmd::diff_stored(&mut cmd_ctx).await? else { panic!("Expected `DiffCmd::diff_stored` to complete successfully."); }; let state_diff = state_diffs.get::<TarXStateDiff, _>(TarXTest::ID).unwrap(); // `b` and `d` are not included in the diff assert_eq!( &TarXStateDiff::ExtractionOutOfSync { added: FileMetadatas::default(), modified: FileMetadatas::default(), removed: FileMetadatas::from(vec![ FileMetadata::new(a_path, TAR_X1_MTIME), FileMetadata::new(c_path, TAR_X1_MTIME), ]) }, state_diff ); Ok(()) } #[tokio::test] async fn state_diff_includes_removed_when_file_in_dest_is_not_in_tar_and_tar_file_name_lesser( ) -> Result<(), Box<dyn std::error::Error>> { let flow_id = FlowId::new(crate::fn_name_short!())?; let TestEnv { tempdir: _tempdir, workspace, profile, graph, output, tar_path, dest, } = test_env(&flow_id, TAR_X1_TAR).await?; let flow = Flow::new(flow_id, graph); let b_path = PathBuf::from("b"); let d_path = PathBuf::from("sub").join("d"); // Create files in the destination. tokio::fs::create_dir(&dest).await?; tar::Archive::new(Cursor::new(TAR_X1_TAR)).unpack(&dest)?; tar::Archive::new(Cursor::new(TAR_X2_TAR)).unpack(&dest)?; let mut cmd_ctx = CmdCtxSpsf::<TestCctTarX>::builder() .with_workspace(workspace.into()) .with_output(output.into()) .with_profile_selection(ProfileSelection::Specified(profile.clone())) .with_flow((&flow).into()) .with_item_params::<TarXItem<TarXTest>>( TarXTest::ID.clone(), TarXParams::<TarXTest>::new(tar_path, dest).into(), ) .await?; // Discover current and goal states. StatesDiscoverCmd::current_and_goal(&mut cmd_ctx).await?; // Diff current and goal states. let CmdOutcome::Complete { value: state_diffs, cmd_blocks_processed: _, } = DiffCmd::diff_stored(&mut cmd_ctx).await? else { panic!("Expected `DiffCmd::diff_stored` to complete successfully."); }; let state_diff = state_diffs.get::<TarXStateDiff, _>(TarXTest::ID).unwrap(); // `b` and `d` are not included in the diff assert_eq!( &TarXStateDiff::ExtractionOutOfSync { added: FileMetadatas::default(), modified: FileMetadatas::default(), removed: FileMetadatas::from(vec![ FileMetadata::new(b_path, TAR_X2_MTIME), FileMetadata::new(d_path, TAR_X2_MTIME), ]) }, state_diff ); Ok(()) } #[tokio::test] async fn state_diff_includes_modified_when_dest_mtime_is_different( ) -> Result<(), Box<dyn std::error::Error>> { let flow_id = FlowId::new(crate::fn_name_short!())?; let TestEnv { tempdir: _tempdir, workspace, profile, graph, output, tar_path, dest, } = test_env(&flow_id, TAR_X2_TAR).await?; let flow = Flow::new(flow_id, graph); // Create files in the destination. let sub_path = dest.join("sub"); tokio::fs::create_dir_all(sub_path).await?; tar::Archive::new(Cursor::new(TAR_X1_TAR)).unpack(&dest)?; tokio::fs::write(&dest.join("b"), []).await?; tokio::fs::write(&dest.join("sub").join("d"), []).await?; let a_path = PathBuf::from("a"); let c_path = PathBuf::from("sub").join("c"); let b_path = PathBuf::from("b"); let d_path = PathBuf::from("sub").join("d"); let mut cmd_ctx = CmdCtxSpsf::<TestCctTarX>::builder() .with_workspace(workspace.into()) .with_output(output.into()) .with_profile_selection(ProfileSelection::Specified(profile.clone())) .with_flow((&flow).into()) .with_item_params::<TarXItem<TarXTest>>( TarXTest::ID.clone(), TarXParams::<TarXTest>::new(tar_path, dest).into(), ) .await?; // Discover current and goal states. StatesDiscoverCmd::current_and_goal(&mut cmd_ctx).await?; // Diff current and goal states. let CmdOutcome::Complete { value: state_diffs, cmd_blocks_processed: _, } = DiffCmd::diff_stored(&mut cmd_ctx).await? else { panic!("Expected `DiffCmd::diff_stored` to complete successfully."); }; let state_diff = state_diffs.get::<TarXStateDiff, _>(TarXTest::ID).unwrap(); assert_eq!( &TarXStateDiff::ExtractionOutOfSync { added: FileMetadatas::default(), modified: FileMetadatas::from(vec![ FileMetadata::new(b_path, TAR_X2_MTIME), FileMetadata::new(d_path, TAR_X2_MTIME), ]), removed: FileMetadatas::from(vec![ FileMetadata::new(a_path, TAR_X1_MTIME), FileMetadata::new(c_path, TAR_X1_MTIME), ]) }, state_diff ); Ok(()) } #[tokio::test] async fn state_diff_returns_extraction_in_sync_when_tar_and_dest_in_sync( ) -> Result<(), Box<dyn std::error::Error>> { let flow_id = FlowId::new(crate::fn_name_short!())?; let TestEnv { tempdir: _tempdir, workspace, profile, graph, output, tar_path, dest, } = test_env(&flow_id, TAR_X2_TAR).await?; let flow = Flow::new(flow_id, graph); // Create files in the destination. tokio::fs::create_dir(&dest).await?; tar::Archive::new(Cursor::new(TAR_X2_TAR)).unpack(&dest)?; let mut cmd_ctx = CmdCtxSpsf::<TestCctTarX>::builder() .with_workspace(workspace.into()) .with_output(output.into()) .with_profile_selection(ProfileSelection::Specified(profile.clone())) .with_flow((&flow).into()) .with_item_params::<TarXItem<TarXTest>>( TarXTest::ID.clone(), TarXParams::<TarXTest>::new(tar_path, dest).into(), ) .await?; // Discover current and goal states. StatesDiscoverCmd::current_and_goal(&mut cmd_ctx).await?; // Diff current and goal states. let CmdOutcome::Complete { value: state_diffs, cmd_blocks_processed: _, } = DiffCmd::diff_stored(&mut cmd_ctx).await? else { panic!("Expected `DiffCmd::diff_stored` to complete successfully."); }; let state_diff = state_diffs.get::<TarXStateDiff, _>(TarXTest::ID).unwrap(); assert_eq!(&TarXStateDiff::ExtractionInSync, state_diff); Ok(()) } #[tokio::test] async fn ensure_check_returns_exec_not_required_when_tar_and_dest_in_sync( ) -> Result<(), Box<dyn std::error::Error>> { let flow_id = FlowId::new(crate::fn_name_short!())?; let TestEnv { tempdir: _tempdir, workspace, profile, graph, output, tar_path, dest, } = test_env(&flow_id, TAR_X2_TAR).await?; let flow = Flow::new(flow_id, graph); // Create files in the destination. tokio::fs::create_dir(&dest).await?; tar::Archive::new(Cursor::new(TAR_X2_TAR)).unpack(&dest)?; let mut cmd_ctx = CmdCtxSpsf::<TestCctTarX>::builder() .with_workspace(workspace.into()) .with_output(output.into()) .with_profile_selection(ProfileSelection::Specified(profile.clone())) .with_flow((&flow).into()) .with_item_params::<TarXItem<TarXTest>>( TarXTest::ID.clone(), TarXParams::<TarXTest>::new(tar_path, dest).into(), ) .await?; let CmdOutcome::Complete { value: (states_current, states_goal), cmd_blocks_processed: _, } = StatesDiscoverCmd::current_and_goal(&mut cmd_ctx).await? else { panic!("Expected `StatesDiscoverCmd::current_and_goal` to complete successfully."); }; let state_current = states_current .get::<FileMetadatas, _>(TarXTest::ID) .unwrap(); let CmdOutcome::Complete { value: state_diffs, cmd_blocks_processed: _, } = DiffCmd::diff_stored(&mut cmd_ctx).await? else { panic!("Expected `DiffCmd::diff_stored` to complete successfully."); }; let state_goal = states_goal.get::<FileMetadatas, _>(TarXTest::ID).unwrap(); let state_diff = state_diffs.get::<TarXStateDiff, _>(TarXTest::ID).unwrap(); let CmdCtxSpsfFields { params_specs, mapping_fn_reg, resources, .. } = cmd_ctx.fields(); let tar_x_params_spec = params_specs .get::<ParamsSpec<TarXParams<TarXTest>>, _>(TarXTest::ID) .unwrap(); let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, TarXTest::ID.clone(), tynm::type_name::<TarXParams<TarXTest>>(), ); let tar_x_params = tar_x_params_spec .resolve(&mapping_fn_reg, resources, &mut value_resolution_ctx) .unwrap(); assert_eq!( ApplyCheck::ExecNotRequired, <TarXItem::<TarXTest> as Item>::apply_check( &tar_x_params, <TarXData<TarXTest> as Data>::borrow(TarXTest::ID, resources), state_current, state_goal, state_diff ) .await? ); Ok(()) } #[tokio::test] async fn ensure_unpacks_tar_when_files_not_exists() -> Result<(), Box<dyn std::error::Error>> { let flow_id = FlowId::new(crate::fn_name_short!())?; let TestEnv { tempdir: _tempdir, workspace, profile, graph, output, tar_path, dest, } = test_env(&flow_id, TAR_X2_TAR).await?; let flow = Flow::new(flow_id, graph); let mut cmd_ctx = CmdCtxSpsf::<TestCctTarX>::builder() .with_workspace(workspace.into()) .with_output(output.into()) .with_profile_selection(ProfileSelection::Specified(profile.clone())) .with_flow((&flow).into()) .with_item_params::<TarXItem<TarXTest>>( TarXTest::ID.clone(), TarXParams::<TarXTest>::new(tar_path, dest).into(), ) .await?; StatesDiscoverCmd::current_and_goal(&mut cmd_ctx).await?; let CmdOutcome::Complete { value: states_ensured, cmd_blocks_processed: _, } = EnsureCmd::exec(&mut cmd_ctx).await? else { panic!("Expected `EnsureCmd::exec` to complete successfully."); }; let state_ensured = states_ensured .get::<FileMetadatas, _>(TarXTest::ID) .unwrap(); let b_path = PathBuf::from("b"); let d_path = PathBuf::from("sub").join("d"); assert_eq!( &FileMetadatas::from(vec![ FileMetadata::new(b_path, TAR_X2_MTIME), FileMetadata::new(d_path, TAR_X2_MTIME), ]), state_ensured ); Ok(()) } #[tokio::test] async fn ensure_removes_other_files_and_is_idempotent() -> Result<(), Box<dyn std::error::Error>> { let flow_id = FlowId::new(crate::fn_name_short!())?; let TestEnv { tempdir: _tempdir, workspace, profile, graph, output, tar_path, dest, } = test_env(&flow_id, TAR_X2_TAR).await?; let flow = Flow::new(flow_id, graph); // Create files in the destination. let sub_path = dest.join("sub"); tokio::fs::create_dir_all(sub_path).await?; tar::Archive::new(Cursor::new(TAR_X1_TAR)).unpack(&dest)?; tokio::fs::write(&dest.join("b"), []).await?; tokio::fs::write(&dest.join("sub").join("d"), []).await?; let b_path = PathBuf::from("b"); let d_path = PathBuf::from("sub").join("d"); let mut cmd_ctx = CmdCtxSpsf::<TestCctTarX>::builder() .with_workspace(workspace.into()) .with_output(output.into()) .with_profile_selection(ProfileSelection::Specified(profile.clone())) .with_flow((&flow).into()) .with_item_params::<TarXItem<TarXTest>>( TarXTest::ID.clone(), TarXParams::<TarXTest>::new(tar_path, dest).into(), ) .await?; StatesDiscoverCmd::current_and_goal(&mut cmd_ctx).await?; // Overwrite changed files and remove extra files let CmdOutcome::Complete { value: states_ensured, cmd_blocks_processed: _, } = EnsureCmd::exec(&mut cmd_ctx).await? else { panic!("Expected `EnsureCmd::exec` to complete successfully."); }; let state_ensured = states_ensured .get::<FileMetadatas, _>(TarXTest::ID) .unwrap(); assert_eq!( &FileMetadatas::from(vec![ FileMetadata::new(b_path.clone(), TAR_X2_MTIME), FileMetadata::new(d_path.clone(), TAR_X2_MTIME), ]), state_ensured ); // Execute again to check idempotence let CmdOutcome::Complete { value: states_ensured, cmd_blocks_processed: _, } = EnsureCmd::exec(&mut cmd_ctx).await? else { panic!("Expected `EnsureCmd::exec` to complete successfully."); }; let state_ensured = states_ensured .get::<FileMetadatas, _>(TarXTest::ID) .unwrap(); assert_eq!( &FileMetadatas::from(vec![ FileMetadata::new(b_path, TAR_X2_MTIME), FileMetadata::new(d_path, TAR_X2_MTIME), ]), state_ensured ); Ok(()) } #[tokio::test] async fn clean_removes_files_in_dest_directory() -> Result<(), Box<dyn std::error::Error>> { let flow_id = FlowId::new(crate::fn_name_short!())?; let TestEnv { tempdir: _tempdir, workspace, profile, graph, output, tar_path, dest, } = test_env(&flow_id, TAR_X2_TAR).await?; let flow = Flow::new(flow_id, graph); let mut cmd_ctx = CmdCtxSpsf::<TestCctTarX>::builder() .with_workspace(workspace.into()) .with_output(output.into()) .with_profile_selection(ProfileSelection::Specified(profile.clone())) .with_flow((&flow).into()) .with_item_params::<TarXItem<TarXTest>>( TarXTest::ID.clone(), TarXParams::<TarXTest>::new(tar_path, dest.clone()).into(), ) .await?; StatesDiscoverCmd::current_and_goal(&mut cmd_ctx).await?; let CmdOutcome::Complete { value: states_cleaned, cmd_blocks_processed: _, } = CleanCmd::exec(&mut cmd_ctx).await? else { panic!("Expected `CleanCmd::exec` to complete successfully."); }; let state_cleaned = states_cleaned .get::<FileMetadatas, _>(TarXTest::ID) .unwrap(); assert_eq!(&FileMetadatas::default(), state_cleaned); assert!(!dest.join("b").exists()); assert!(!dest.join("sub").join("d").exists()); Ok(()) } async fn test_env( flow_id: &FlowId, tar_bytes: &[u8], ) -> Result<TestEnv, Box<dyn std::error::Error>> { let tempdir = tempfile::tempdir()?; let workspace = Workspace::new( app_name!(), WorkspaceSpec::Path(tempdir.path().to_path_buf()), )?; let profile = profile!("test_profile"); let flow_dir = { let profile_dir = ProfileDir::from((workspace.dirs().peace_app_dir(), &profile)); FlowDir::from((&profile_dir, flow_id)) }; let graph = { let mut graph_builder = ItemGraphBuilder::<TarXError>::new(); graph_builder.add_fn(TarXItem::<TarXTest>::new(TarXTest::ID.clone()).into()); graph_builder.build() }; let output = InMemoryTextOutput::new(); let tar_path = { let tar_path = flow_dir.join("tar_x.tar"); tokio::fs::create_dir_all(&flow_dir).await?; tokio::fs::write(&tar_path, tar_bytes).await?; tar_path }; let dest = flow_dir.join("tar_dest"); Ok(TestEnv { tempdir, workspace, profile, graph, output, tar_path, dest, }) } #[derive(Debug)] struct TestEnv { tempdir: TempDir, workspace: Workspace, profile: Profile, graph: ItemGraph<TarXError>, output: InMemoryTextOutput, tar_path: PathBuf, dest: PathBuf, } #[derive(Debug)] pub struct TestCctTarX; impl CmdCtxTypes for TestCctTarX { type AppError = TarXError; type FlowParamsKey = (); type MappingFns = (); type Output = InMemoryTextOutput; type ProfileParamsKey = (); type WorkspaceParamsKey = (); }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/fmt/either.rs
workspace_tests/src/fmt/either.rs
use peace::{ cli::output::{CliColorizeOpt, CliMdPresenter}, fmt::{ presentable::{Bold, CodeInline}, Either, Presentable, PresentableExt, }, }; use crate::fmt::cli_output; #[tokio::test] async fn either_left_present() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Never); let mut presenter = CliMdPresenter::new(&mut cli_output); let presentable: Either<Bold<_>, CodeInline> = Bold::new("abc").left_presentable(); presentable.present(&mut presenter).await?; let output = String::from_utf8(cli_output.writer().clone())?; assert!(matches!(&presentable, Either::Left(_))); assert_eq!("**abc**", output); Ok(()) } #[tokio::test] async fn either_right_present() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Never); let mut presenter = CliMdPresenter::new(&mut cli_output); let presentable: Either<CodeInline, Bold<_>> = Bold::new("abc").right_presentable(); presentable.present(&mut presenter).await?; let output = String::from_utf8(cli_output.writer().clone())?; assert!(matches!(&presentable, Either::Right(_))); assert_eq!("**abc**", output); Ok(()) } #[test] fn clone() { let either: Either<Bold<_>, CodeInline> = Bold::new("abc").left_presentable(); let clone = Clone::clone(&either); assert_eq!(either, clone); } #[test] fn debug() { let either: Either<Bold<_>, CodeInline> = Bold::new("abc").left_presentable(); assert_eq!("Left(Bold(\"abc\"))", format!("{either:?}")); } #[test] fn serialize() -> Result<(), serde_yaml::Error> { let either: Either<Bold<_>, CodeInline> = Bold::new("abc").left_presentable(); assert_eq!("!Left abc\n", serde_yaml::to_string(&either)?); Ok(()) } #[test] fn deserialize() -> Result<(), serde_yaml::Error> { let either = CodeInline::new("abc".into()).right_presentable(); assert_eq!( either, serde_yaml::from_str::<Either<Bold<&'static str>, CodeInline>>("!Right abc")? ); Ok(()) }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/fmt/presentable.rs
workspace_tests/src/fmt/presentable.rs
mod bold; mod code_inline; mod heading; mod list_bulleted; mod list_bulleted_aligned; mod list_numbered; mod list_numbered_aligned; use peace::fmt::Presentable; use crate::{FnInvocation, FnTrackerPresenter}; #[tokio::test] async fn ref_t_is_presentable_when_t_is_presentable() -> Result<(), Box<dyn std::error::Error>> { let mut presenter = FnTrackerPresenter::new(); let s: String = String::from("hello"); <&String as Presentable>::present(&&s, &mut presenter).await?; assert_eq!( vec![FnInvocation::new( "text", vec![Some(r#""hello""#.to_string())] ),], presenter.fn_invocations() ); Ok(()) } #[tokio::test] async fn ref_str_is_presentable() -> Result<(), Box<dyn std::error::Error>> { let mut presenter = FnTrackerPresenter::new(); let s = "hello"; <&str as Presentable>::present(&s, &mut presenter).await?; assert_eq!( vec![FnInvocation::new( "text", vec![Some(r#""hello""#.to_string())] ),], presenter.fn_invocations() ); Ok(()) } #[tokio::test] async fn string_is_presentable() -> Result<(), Box<dyn std::error::Error>> { let mut presenter = FnTrackerPresenter::new(); let s: String = String::from("hello"); <String as Presentable>::present(&s, &mut presenter).await?; assert_eq!( vec![FnInvocation::new( "text", vec![Some(r#""hello""#.to_string())] ),], presenter.fn_invocations() ); Ok(()) } #[tokio::test] async fn vec_t_is_presentable_when_t_is_presentable() -> Result<(), Box<dyn std::error::Error>> { let mut presenter = FnTrackerPresenter::new(); let list = vec![String::from("one"), String::from("two")]; <Vec<String> as Presentable>::present(&list, &mut presenter).await?; assert_eq!( vec![FnInvocation::new("list_numbered", vec![None])], presenter.fn_invocations() ); Ok(()) } #[tokio::test] async fn array_t_is_presentable_when_t_is_presentable() -> Result<(), Box<dyn std::error::Error>> { let mut presenter = FnTrackerPresenter::new(); let list = [String::from("one"), String::from("two")]; <[String] as Presentable>::present(&list, &mut presenter).await?; assert_eq!( vec![FnInvocation::new("list_numbered", vec![None])], presenter.fn_invocations() ); Ok(()) }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/fmt/presentable/list_numbered.rs
workspace_tests/src/fmt/presentable/list_numbered.rs
use peace::{ cli::output::{CliColorizeOpt, CliMdPresenter}, fmt::{presentable::ListNumbered, Presentable}, }; use crate::fmt::cli_output; #[tokio::test] async fn present() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Always); let mut presenter = CliMdPresenter::new(&mut cli_output); let list_numbered = ListNumbered::new((1..=11).map(|n| format!("Item {n}")).collect::<Vec<_>>()); list_numbered.present(&mut presenter).await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!( " \u{1b}[38;5;15m1.\u{1b}[0m Item 1 \u{1b}[38;5;15m2.\u{1b}[0m Item 2 \u{1b}[38;5;15m3.\u{1b}[0m Item 3 \u{1b}[38;5;15m4.\u{1b}[0m Item 4 \u{1b}[38;5;15m5.\u{1b}[0m Item 5 \u{1b}[38;5;15m6.\u{1b}[0m Item 6 \u{1b}[38;5;15m7.\u{1b}[0m Item 7 \u{1b}[38;5;15m8.\u{1b}[0m Item 8 \u{1b}[38;5;15m9.\u{1b}[0m Item 9 \u{1b}[38;5;15m10.\u{1b}[0m Item 10 \u{1b}[38;5;15m11.\u{1b}[0m Item 11 ", output ); assert_eq!( r#" 1. Item 1 2. Item 2 3. Item 3 4. Item 4 5. Item 5 6. Item 6 7. Item 7 8. Item 8 9. Item 9 10. Item 10 11. Item 11 "#, console::strip_ansi_codes(&output) ); Ok(()) } #[test] fn debug() { assert_eq!( r#"ListNumbered(["abc"])"#, format!("{:?}", ListNumbered::new(vec!["abc"])) ) } #[test] fn serialize() -> Result<(), serde_yaml::Error> { assert_eq!( "- abc\n", serde_yaml::to_string(&ListNumbered::new(vec!["abc"]))? ); Ok(()) } #[test] fn deserialize() -> Result<(), serde_yaml::Error> { assert_eq!( ListNumbered::new(vec![(String::from("abc"))]), serde_yaml::from_str("- abc")?, ); Ok(()) } #[test] fn from() { assert_eq!( ListNumbered::new(vec!["abc"]), ListNumbered::from(vec!["abc"]) ); }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/fmt/presentable/list_numbered_aligned.rs
workspace_tests/src/fmt/presentable/list_numbered_aligned.rs
use peace::{ cli::output::{CliColorizeOpt, CliMdPresenter}, fmt::{ presentable::{Bold, CodeInline, ListNumberedAligned}, Presentable, }, }; use crate::fmt::cli_output; #[tokio::test] async fn present() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Always); let mut presenter = CliMdPresenter::new(&mut cli_output); let list_numbered_aligned = ListNumberedAligned::new( (1..=11) .map(|n| { ( Bold::new(format!("Item {n}")), ( String::from("description with "), CodeInline::new("code".into()), ), ) }) .collect::<Vec<_>>(), ); list_numbered_aligned.present(&mut presenter).await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!( " \u{1b}[38;5;15m1.\u{1b}[0m **\u{1b}[1mItem 1\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m2.\u{1b}[0m **\u{1b}[1mItem 2\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m3.\u{1b}[0m **\u{1b}[1mItem 3\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m4.\u{1b}[0m **\u{1b}[1mItem 4\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m5.\u{1b}[0m **\u{1b}[1mItem 5\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m6.\u{1b}[0m **\u{1b}[1mItem 6\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m7.\u{1b}[0m **\u{1b}[1mItem 7\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m8.\u{1b}[0m **\u{1b}[1mItem 8\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m9.\u{1b}[0m **\u{1b}[1mItem 9\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m10.\u{1b}[0m **\u{1b}[1mItem 10\u{1b}[0m**: description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m11.\u{1b}[0m **\u{1b}[1mItem 11\u{1b}[0m**: description with \u{1b}[38;5;75m`code`\u{1b}[0m ", output ); assert_eq!( " 1. **Item 1** : description with `code` 2. **Item 2** : description with `code` 3. **Item 3** : description with `code` 4. **Item 4** : description with `code` 5. **Item 5** : description with `code` 6. **Item 6** : description with `code` 7. **Item 7** : description with `code` 8. **Item 8** : description with `code` 9. **Item 9** : description with `code` 10. **Item 10**: description with `code` 11. **Item 11**: description with `code` ", console::strip_ansi_codes(&output) ); Ok(()) } #[test] fn debug() { assert_eq!( r#"ListNumberedAligned([("abc", "def")])"#, format!("{:?}", ListNumberedAligned::new(vec![("abc", "def")])) ) } #[test] fn serialize() -> Result<(), serde_yaml::Error> { assert_eq!( r#"- - abc - def "#, serde_yaml::to_string(&ListNumberedAligned::new(vec![("abc", "def")]))? ); Ok(()) } #[test] fn deserialize() -> Result<(), serde_yaml::Error> { assert_eq!( ListNumberedAligned::new(vec![(String::from("abc"), String::from("def"))]), serde_yaml::from_str("- [abc, def]")?, ); Ok(()) } #[test] fn from() { assert_eq!( ListNumberedAligned::new(vec![("abc", "def")]), ListNumberedAligned::from(vec![("abc", "def")]) ); }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/fmt/presentable/heading.rs
workspace_tests/src/fmt/presentable/heading.rs
use futures::{stream, StreamExt, TryStreamExt}; use peace::{ cli::output::{CliColorizeOpt, CliMdPresenter}, fmt::{ presentable::{CodeInline, Heading, HeadingLevel}, Presentable, }, }; use crate::fmt::cli_output; #[tokio::test] async fn present() -> Result<(), Box<dyn std::error::Error>> { stream::iter([ ( HeadingLevel::Level1, "\u{1b}[38;5;243m\u{1b}[1m#\u{1b}[0m \u{1b}[38;5;75m\u{1b}[1m`code`\u{1b}[0m\n\n", "# `code`\n\n", ), ( HeadingLevel::Level2, "\u{1b}[38;5;243m\u{1b}[1m##\u{1b}[0m \u{1b}[38;5;75m\u{1b}[1m`code`\u{1b}[0m\n\n", "## `code`\n\n", ), ( HeadingLevel::Level3, "\u{1b}[38;5;243m\u{1b}[1m###\u{1b}[0m \u{1b}[38;5;75m\u{1b}[1m`code`\u{1b}[0m\n\n", "### `code`\n\n", ), ( HeadingLevel::Level4, "\u{1b}[38;5;243m\u{1b}[1m####\u{1b}[0m \u{1b}[38;5;75m\u{1b}[1m`code`\u{1b}[0m\n\n", "#### `code`\n\n", ), ( HeadingLevel::Level5, "\u{1b}[38;5;243m\u{1b}[1m#####\u{1b}[0m \u{1b}[38;5;75m\u{1b}[1m`code`\u{1b}[0m\n\n", "##### `code`\n\n", ), ( HeadingLevel::Level6, "\u{1b}[38;5;243m\u{1b}[1m######\u{1b}[0m \u{1b}[38;5;75m\u{1b}[1m`code`\u{1b}[0m\n\n", "###### `code`\n\n", ), ]) .map(Result::<_, Box<dyn std::error::Error>>::Ok) .try_for_each(|(heading_level, expected_colorized, expected)| async move { let mut cli_output = cli_output(CliColorizeOpt::Always); let mut presenter = CliMdPresenter::new(&mut cli_output); let heading = Heading::new(heading_level, CodeInline::new("code".into())); heading.present(&mut presenter).await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!(expected_colorized, output); assert_eq!(expected, console::strip_ansi_codes(&output)); Ok(()) }) .await } #[test] fn debug() { assert_eq!( "Heading { \ level: Level1, \ presentable: \"abc\" \ }", format!("{:?}", Heading::new(HeadingLevel::Level1, "abc")) ) } #[test] fn serialize() -> Result<(), serde_yaml::Error> { assert_eq!( "\ level: Level1\n\ presentable: abc\n\ ", serde_yaml::to_string(&Heading::new(HeadingLevel::Level1, "abc"))? ); Ok(()) } #[test] fn deserialize() -> Result<(), serde_yaml::Error> { assert_eq!( Heading::new(HeadingLevel::Level1, "abc"), serde_yaml::from_str( "\ level: Level1\n\ presentable: abc\n\ " )?, ); Ok(()) }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/fmt/presentable/list_bulleted_aligned.rs
workspace_tests/src/fmt/presentable/list_bulleted_aligned.rs
use peace::{ cli::output::{CliColorizeOpt, CliMdPresenter}, fmt::{ presentable::{Bold, CodeInline, ListBulletedAligned}, Presentable, }, }; use crate::fmt::cli_output; #[tokio::test] async fn present() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Always); let mut presenter = CliMdPresenter::new(&mut cli_output); let list_bulleted_aligned = ListBulletedAligned::new( (1..=11) .map(|n| { ( Bold::new(format!("Item {n}")), ( String::from("description with "), CodeInline::new("code".into()), ), ) }) .collect::<Vec<_>>(), ); list_bulleted_aligned.present(&mut presenter).await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!( "\u{1b}[38;5;15m*\u{1b}[0m **\u{1b}[1mItem 1\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m*\u{1b}[0m **\u{1b}[1mItem 2\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m*\u{1b}[0m **\u{1b}[1mItem 3\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m*\u{1b}[0m **\u{1b}[1mItem 4\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m*\u{1b}[0m **\u{1b}[1mItem 5\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m*\u{1b}[0m **\u{1b}[1mItem 6\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m*\u{1b}[0m **\u{1b}[1mItem 7\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m*\u{1b}[0m **\u{1b}[1mItem 8\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m*\u{1b}[0m **\u{1b}[1mItem 9\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m*\u{1b}[0m **\u{1b}[1mItem 10\u{1b}[0m**: description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m*\u{1b}[0m **\u{1b}[1mItem 11\u{1b}[0m**: description with \u{1b}[38;5;75m`code`\u{1b}[0m ", output ); assert_eq!( "* **Item 1** : description with `code` * **Item 2** : description with `code` * **Item 3** : description with `code` * **Item 4** : description with `code` * **Item 5** : description with `code` * **Item 6** : description with `code` * **Item 7** : description with `code` * **Item 8** : description with `code` * **Item 9** : description with `code` * **Item 10**: description with `code` * **Item 11**: description with `code` ", console::strip_ansi_codes(&output) ); Ok(()) } #[test] fn debug() { assert_eq!( r#"ListBulletedAligned([("abc", "def")])"#, format!("{:?}", ListBulletedAligned::new(vec![("abc", "def")])) ) } #[test] fn serialize() -> Result<(), serde_yaml::Error> { assert_eq!( r#"- - abc - def "#, serde_yaml::to_string(&ListBulletedAligned::new(vec![("abc", "def")]))? ); Ok(()) } #[test] fn deserialize() -> Result<(), serde_yaml::Error> { assert_eq!( ListBulletedAligned::new(vec![(String::from("abc"), String::from("def"))]), serde_yaml::from_str("- [abc, def]")?, ); Ok(()) } #[test] fn from() { assert_eq!( ListBulletedAligned::new(vec![("abc", "def")]), ListBulletedAligned::from(vec![("abc", "def")]) ); }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/fmt/presentable/bold.rs
workspace_tests/src/fmt/presentable/bold.rs
use peace::{ cli::output::{CliColorizeOpt, CliMdPresenter}, fmt::{presentable::Bold, Presentable}, }; use crate::fmt::cli_output; #[tokio::test] async fn present() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Always); let mut presenter = CliMdPresenter::new(&mut cli_output); Bold::new(String::from("bold")) .present(&mut presenter) .await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!("**\u{1b}[1mbold\u{1b}[0m**", output); assert_eq!("**bold**", console::strip_ansi_codes(&output)); Ok(()) } #[test] fn debug() { assert_eq!("Bold(\"abc\")", format!("{:?}", Bold::new("abc"))) } #[test] fn serialize() -> Result<(), serde_yaml::Error> { assert_eq!( "abc\n\ ", serde_yaml::to_string(&Bold::new("abc"))? ); Ok(()) } #[test] fn deserialize() -> Result<(), serde_yaml::Error> { assert_eq!(Bold::new("abc"), serde_yaml::from_str("abc")?,); Ok(()) }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/fmt/presentable/code_inline.rs
workspace_tests/src/fmt/presentable/code_inline.rs
use peace::{ cli::output::{CliColorizeOpt, CliMdPresenter}, fmt::{presentable::CodeInline, Presentable}, }; use crate::fmt::cli_output; #[tokio::test] async fn present() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Always); let mut presenter = CliMdPresenter::new(&mut cli_output); CodeInline::new("code_inline".into()) .present(&mut presenter) .await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!("\u{1b}[38;5;75m`code_inline`\u{1b}[0m", output); assert_eq!("`code_inline`", console::strip_ansi_codes(&output)); Ok(()) } #[test] fn debug() { assert_eq!( "CodeInline(\"abc\")", format!("{:?}", CodeInline::new("abc".into())) ) } #[test] fn serialize() -> Result<(), serde_yaml::Error> { assert_eq!( "abc\n\ ", serde_yaml::to_string(&CodeInline::new("abc".into()))? ); Ok(()) } #[test] fn deserialize() -> Result<(), serde_yaml::Error> { assert_eq!(CodeInline::new("abc".into()), serde_yaml::from_str("abc")?,); Ok(()) }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/fmt/presentable/list_bulleted.rs
workspace_tests/src/fmt/presentable/list_bulleted.rs
use peace::{ cli::output::{CliColorizeOpt, CliMdPresenter}, fmt::{presentable::ListBulleted, Presentable}, }; use crate::fmt::cli_output; #[tokio::test] async fn present() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Always); let mut presenter = CliMdPresenter::new(&mut cli_output); let list_bulleted = ListBulleted::new((1..=11).map(|n| format!("Item {n}")).collect::<Vec<_>>()); list_bulleted.present(&mut presenter).await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!( "\u{1b}[38;5;15m*\u{1b}[0m Item 1 \u{1b}[38;5;15m*\u{1b}[0m Item 2 \u{1b}[38;5;15m*\u{1b}[0m Item 3 \u{1b}[38;5;15m*\u{1b}[0m Item 4 \u{1b}[38;5;15m*\u{1b}[0m Item 5 \u{1b}[38;5;15m*\u{1b}[0m Item 6 \u{1b}[38;5;15m*\u{1b}[0m Item 7 \u{1b}[38;5;15m*\u{1b}[0m Item 8 \u{1b}[38;5;15m*\u{1b}[0m Item 9 \u{1b}[38;5;15m*\u{1b}[0m Item 10 \u{1b}[38;5;15m*\u{1b}[0m Item 11 ", output ); assert_eq!( r#"* Item 1 * Item 2 * Item 3 * Item 4 * Item 5 * Item 6 * Item 7 * Item 8 * Item 9 * Item 10 * Item 11 "#, console::strip_ansi_codes(&output) ); Ok(()) } #[test] fn debug() { assert_eq!( r#"ListBulleted(["abc"])"#, format!("{:?}", ListBulleted::new(vec!["abc"])) ) } #[test] fn serialize() -> Result<(), serde_yaml::Error> { assert_eq!( "- abc\n", serde_yaml::to_string(&ListBulleted::new(vec!["abc"]))? ); Ok(()) } #[test] fn deserialize() -> Result<(), serde_yaml::Error> { assert_eq!( ListBulleted::new(vec![(String::from("abc"))]), serde_yaml::from_str("- abc")?, ); Ok(()) } #[test] fn from() { assert_eq!( ListBulleted::new(vec!["abc"]), ListBulleted::from(vec!["abc"]) ); }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/profile_model/profile_invalid_fmt.rs
workspace_tests/src/profile_model/profile_invalid_fmt.rs
use std::borrow::Cow; use peace::profile_model::ProfileInvalidFmt; #[test] fn debug() { let item_id_invalid_fmt = ProfileInvalidFmt::new(Cow::Borrowed("invalid profile")); assert_eq!( r#"ProfileInvalidFmt { value: "invalid profile" }"#, format!("{item_id_invalid_fmt:?}") ); } #[test] fn display() { let item_id_invalid_fmt = ProfileInvalidFmt::new(Cow::Borrowed("invalid profile")); assert_eq!( "`invalid profile` is not a valid `Profile`.\n\ `Profile`s must begin with a letter or underscore, and contain only letters, numbers, or underscores.", format!("{item_id_invalid_fmt}") ); }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/profile_model/profile.rs
workspace_tests/src/profile_model/profile.rs
use std::{borrow::Cow, collections::HashMap, str::FromStr}; use peace::{ fmt::Presentable, profile_model::{Profile, ProfileInvalidFmt}, }; use crate::{FnInvocation, FnTrackerPresenter}; #[test] fn from_str_returns_ok_owned_for_valid_profile() -> Result<(), ProfileInvalidFmt<'static>> { let profile = Profile::from_str("good_profile")?; assert_eq!("good_profile", *profile); Ok(()) } #[test] fn underscore_is_valid_first_character() -> Result<(), ProfileInvalidFmt<'static>> { let profile = Profile::new("_good_profile")?; assert_eq!("_good_profile", *profile); Ok(()) } #[test] fn new_unchecked_does_not_validate_profile() -> Result<(), ProfileInvalidFmt<'static>> { let profile = Profile::new_unchecked("!valid"); assert_eq!("!valid", *profile); Ok(()) } #[test] fn try_from_str_returns_ok_borrowed_for_valid_profile() -> Result<(), ProfileInvalidFmt<'static>> { let profile = Profile::try_from("good_profile")?; assert_eq!("good_profile", *profile); Ok(()) } #[test] fn try_from_string_returns_ok_owned_for_valid_profile() -> Result<(), ProfileInvalidFmt<'static>> { let profile = Profile::try_from(String::from("good_profile"))?; assert_eq!("good_profile", *profile); Ok(()) } #[test] fn from_str_returns_err_owned_for_invalid_profile() { let error = Profile::from_str("has space").unwrap_err(); assert!(matches!(error.value(), Cow::Owned(_))); assert_eq!("has space", error.value()); } #[test] fn try_from_str_returns_err_borrowed_for_invalid_profile() { let error = Profile::try_from("has space").unwrap_err(); assert!(matches!(error.value(), Cow::Borrowed(_))); assert_eq!("has space", error.value()); } #[test] fn try_from_string_returns_err_owned_for_invalid_profile() { let error = Profile::try_from(String::from("has space")).unwrap_err(); assert!(matches!(error.value(), Cow::Owned(_))); assert_eq!("has space", error.value()); } #[test] fn display_returns_inner_str() -> Result<(), ProfileInvalidFmt<'static>> { let profile = Profile::try_from("good_profile")?; assert_eq!("good_profile", profile.to_string()); Ok(()) } #[tokio::test] async fn present_uses_tag() -> Result<(), Box<dyn std::error::Error>> { let mut presenter = FnTrackerPresenter::new(); let profile = Profile::try_from("profile")?; profile.present(&mut presenter).await?; assert_eq!( vec![FnInvocation::new( "tag", vec![Some(r#""profile""#.to_string())] )], presenter.fn_invocations() ); Ok(()) } #[test] fn clone() -> Result<(), ProfileInvalidFmt<'static>> { let profile_0 = Profile::new("profile")?; #[allow(clippy::redundant_clone)] // https://github.com/rust-lang/rust-clippy/issues/9011 let profile_1 = profile_0.clone(); assert_eq!(profile_0, profile_1); Ok(()) } #[test] fn debug() -> Result<(), ProfileInvalidFmt<'static>> { let profile = Profile::new("profile")?; assert_eq!(r#"Profile("profile")"#, format!("{profile:?}")); Ok(()) } #[test] fn hash() -> Result<(), ProfileInvalidFmt<'static>> { let profile = Profile::new("profile")?; let mut hash_map = HashMap::new(); hash_map.insert(profile, ()); Ok(()) } #[test] fn partial_eq_ne() -> Result<(), ProfileInvalidFmt<'static>> { let profile_0 = Profile::new("profile0")?; let profile_1 = Profile::new("profile1")?; assert!(profile_0 != profile_1); Ok(()) } #[test] fn serialize() -> Result<(), Box<dyn std::error::Error>> { let profile = Profile::new("profile")?; assert_eq!("profile\n", serde_yaml::to_string(&profile)?); Ok(()) } #[test] fn deserialize() -> Result<(), Box<dyn std::error::Error>> { let profile = Profile::new("profile")?; assert_eq!(profile, serde_yaml::from_str("profile")?); Ok(()) }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/cli/output.rs
workspace_tests/src/cli/output.rs
mod cli_colorize_opt; mod cli_colorize_opt_parse_error; mod cli_md_presenter; mod cli_output; mod cli_output_builder; mod cli_output_target; cfg_if::cfg_if! { if #[cfg(feature = "output_progress")] { mod cli_progress_format_opt; mod cli_progress_format_opt_parse_error; } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/cli/output/cli_progress_format_opt.rs
workspace_tests/src/cli/output/cli_progress_format_opt.rs
use std::str::FromStr; use peace::cli::output::{CliProgressFormatOpt, CliProgressFormatOptParseError}; #[test] fn from_str_returns_ok_for_auto() { assert_eq!( Ok(CliProgressFormatOpt::Auto), CliProgressFormatOpt::from_str("auto") ) } #[test] fn from_str_returns_ok_for_outcome() { assert_eq!( Ok(CliProgressFormatOpt::Outcome), CliProgressFormatOpt::from_str("outcome") ) } #[test] fn from_str_returns_ok_for_pb() { assert_eq!( Ok(CliProgressFormatOpt::ProgressBar), CliProgressFormatOpt::from_str("pb") ) } #[test] fn from_str_returns_ok_for_progress_bar() { assert_eq!( Ok(CliProgressFormatOpt::ProgressBar), CliProgressFormatOpt::from_str("progress_bar") ) } #[test] fn from_str_returns_ok_for_none() { assert_eq!( Ok(CliProgressFormatOpt::None), CliProgressFormatOpt::from_str("none") ) } #[test] fn from_str_returns_err_for_unknown_string() { assert_eq!( Err(CliProgressFormatOptParseError("rara".to_string())), CliProgressFormatOpt::from_str("rara") ) } #[test] fn clone() { let cli_progress_format = CliProgressFormatOpt::Auto; let cli_progress_format_clone = cli_progress_format; assert_eq!(cli_progress_format, cli_progress_format_clone); } #[test] fn debug() { let cli_progress_format = CliProgressFormatOpt::Auto; assert_eq!(r#"Auto"#, format!("{cli_progress_format:?}")); }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/cli/output/cli_colorize_opt.rs
workspace_tests/src/cli/output/cli_colorize_opt.rs
use std::str::FromStr; use peace::cli::output::{CliColorizeOpt, CliColorizeOptParseError}; #[test] fn from_str_returns_ok_for_auto() { assert_eq!(Ok(CliColorizeOpt::Auto), CliColorizeOpt::from_str("auto")) } #[test] fn from_str_returns_ok_for_always() { assert_eq!( Ok(CliColorizeOpt::Always), CliColorizeOpt::from_str("always") ) } #[test] fn from_str_returns_ok_for_never() { assert_eq!(Ok(CliColorizeOpt::Never), CliColorizeOpt::from_str("never")) } #[test] fn from_str_returns_err_for_unknown_string() { assert_eq!( Err(CliColorizeOptParseError("rara".to_string())), CliColorizeOpt::from_str("rara") ) } #[test] fn clone() { let cli_colorize = CliColorizeOpt::Auto; let cli_colorize_clone = cli_colorize; assert_eq!(cli_colorize, cli_colorize_clone); } #[test] fn debug() { let cli_colorize = CliColorizeOpt::Auto; assert_eq!(r#"Auto"#, format!("{cli_colorize:?}")); }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/cli/output/cli_output_builder.rs
workspace_tests/src/cli/output/cli_output_builder.rs
use peace::{ cli::output::{CliColorize, CliColorizeOpt, CliOutputBuilder}, cli_model::OutputFormat, }; #[cfg(feature = "output_progress")] use peace::cli::output::{CliOutputTarget, CliProgressFormat, CliProgressFormatOpt}; #[tokio::test] async fn new_uses_sensible_defaults() -> Result<(), Box<dyn std::error::Error>> { let builder = CliOutputBuilder::new(); assert_eq!(OutputFormat::Text, builder.outcome_format()); assert_eq!(CliColorizeOpt::Auto, builder.colorize()); #[cfg(feature = "output_progress")] assert_eq!(&CliOutputTarget::Stderr, builder.progress_target()); #[cfg(feature = "output_progress")] assert_eq!(CliProgressFormatOpt::Auto, builder.progress_format()); Ok(()) } #[tokio::test] async fn with_outcome_format_sets_outcome_format() -> Result<(), Box<dyn std::error::Error>> { let builder = CliOutputBuilder::new().with_outcome_format(OutputFormat::Yaml); assert_eq!(OutputFormat::Yaml, builder.outcome_format()); Ok(()) } #[tokio::test] async fn with_colorize_sets_colorize() -> Result<(), Box<dyn std::error::Error>> { let builder = CliOutputBuilder::new().with_colorize(CliColorizeOpt::Always); assert_eq!(CliColorizeOpt::Always, builder.colorize()); Ok(()) } #[cfg(feature = "output_progress")] #[tokio::test] async fn with_progress_target_sets_progress_target() -> Result<(), Box<dyn std::error::Error>> { let builder = CliOutputBuilder::new().with_progress_target(CliOutputTarget::Stdout); assert_eq!(&CliOutputTarget::Stdout, builder.progress_target()); Ok(()) } #[cfg(feature = "output_progress")] #[tokio::test] async fn with_progress_format_sets_progress_format() -> Result<(), Box<dyn std::error::Error>> { let builder = CliOutputBuilder::new().with_progress_format(CliProgressFormatOpt::Outcome); assert_eq!(CliProgressFormatOpt::Outcome, builder.progress_format()); Ok(()) } #[tokio::test] async fn build_passes_through_outcome_format() -> Result<(), Box<dyn std::error::Error>> { let builder = CliOutputBuilder::new().with_outcome_format(OutputFormat::Yaml); let cli_output = builder.build(); assert_eq!(OutputFormat::Yaml, cli_output.outcome_format()); Ok(()) } #[tokio::test] async fn build_passes_through_colorize() -> Result<(), Box<dyn std::error::Error>> { let builder = CliOutputBuilder::new().with_colorize(CliColorizeOpt::Always); let cli_output = builder.build(); assert_eq!(CliColorize::Colored, cli_output.colorize()); Ok(()) } #[cfg(feature = "output_progress")] #[tokio::test] async fn build_passes_through_progress_target() -> Result<(), Box<dyn std::error::Error>> { let builder = CliOutputBuilder::new().with_progress_target(CliOutputTarget::Stdout); let cli_output = builder.build(); assert_eq!(&CliOutputTarget::Stdout, cli_output.progress_target()); Ok(()) } #[cfg(feature = "output_progress")] #[tokio::test] async fn build_passes_through_progress_format() -> Result<(), Box<dyn std::error::Error>> { let builder = CliOutputBuilder::new().with_progress_format(CliProgressFormatOpt::Outcome); let cli_output = builder.build(); assert_eq!(CliProgressFormat::Outcome, cli_output.progress_format()); Ok(()) } // Auto default tests // TODO: Test interactive terminal. // // Options: // // * Implement a trait for `tokio::io::Stdout`, `tokio::io::Stderr`, `Vec<u8>` // * Build a small executable and run it via `process::Command`. #[tokio::test] async fn build_colorize_auto_passes_uncolored_for_non_interactive_terminal( ) -> Result<(), Box<dyn std::error::Error>> { let cli_output = CliOutputBuilder::new().build(); assert_eq!(CliColorize::Uncolored, cli_output.colorize()); Ok(()) } #[cfg(feature = "output_progress")] #[tokio::test] async fn build_progress_format_auto_passes_stderr_for_non_interactive_terminal( ) -> Result<(), Box<dyn std::error::Error>> { let cli_output = CliOutputBuilder::new().build(); assert_eq!(CliProgressFormat::Outcome, cli_output.progress_format()); Ok(()) }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/cli/output/cli_output.rs
workspace_tests/src/cli/output/cli_output.rs
use peace::{ cfg::State, cli::output::{CliColorizeOpt, CliOutput, CliOutputBuilder}, cli_model::OutputFormat, item_model::item_id, resource_rt::{ internal::{StateDiffsMut, StatesMut}, states::{StateDiffs, StatesCurrentStored}, }, rt_model::output::OutputWrite, }; cfg_if::cfg_if! { if #[cfg(feature = "output_progress")] { use peace::{ cli::output::{CliOutputTarget, CliProgressFormatOpt}, progress_model::{ ProgressComplete, ProgressDelta, ProgressLimit, ProgressMsgUpdate, ProgressStatus, ProgressTracker, ProgressUpdate, ProgressUpdateAndId, }, rt_model::{ indicatif::{MultiProgress, ProgressBar, ProgressDrawTarget}, CmdProgressTracker, IndexMap, }, }; } } #[tokio::test] async fn outputs_states_as_text() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(OutputFormat::Text); let states_current_stored = { let mut states = StatesMut::new(); states.insert(item_id!("item_0"), State::new("logical", 1.1)); states.insert(item_id!("item_1"), State::new(1u8, true)); StatesCurrentStored::from(states) }; <CliOutput<_> as OutputWrite>::present(&mut cli_output, &states_current_stored).await?; assert_eq!( "\ 1. `item_0`: logical, 1.1\n\ 2. `item_1`: 1, true\n\ ", String::from_utf8(cli_output.writer().clone())? ); Ok(()) } #[tokio::test] async fn outputs_state_diffs_as_text() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(OutputFormat::Text); let state_diffs = { let mut state_diffs_mut = StateDiffsMut::new(); state_diffs_mut.insert(item_id!("item_0"), "need one more server"); state_diffs_mut.insert(item_id!("item_1"), 1); StateDiffs::from(state_diffs_mut) }; <CliOutput<_> as OutputWrite>::present(&mut cli_output, &state_diffs).await?; assert_eq!( "\ 1. `item_0`: need one more server\n\ 2. `item_1`: 1\n\ ", String::from_utf8(cli_output.writer().clone())? ); Ok(()) } #[tokio::test] async fn outputs_error_as_text() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(OutputFormat::Text); let error = Error::CliOutputTest; <CliOutput<_> as OutputWrite>::write_err(&mut cli_output, &error).await?; #[cfg(not(feature = "error_reporting"))] assert_eq!( "CliOutputTest display message.\n", String::from_utf8(cli_output.writer().clone())? ); #[cfg(feature = "error_reporting")] assert_eq!( r#"workspace_tests::cli::output::cli_output_test × CliOutputTest display message. help: Try fixing the test. "#, String::from_utf8(cli_output.writer().clone())? ); Ok(()) } #[tokio::test] async fn outputs_states_as_text_colorized() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output_colorized(OutputFormat::Text); let states_current_stored = { let mut states = StatesMut::new(); states.insert(item_id!("item_0"), State::new("logical", 1.1)); states.insert(item_id!("item_1"), State::new(1u8, true)); StatesCurrentStored::from(states) }; <CliOutput<_> as OutputWrite>::present(&mut cli_output, &states_current_stored).await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!( "\ \u{1b}[38;5;15m1.\u{1b}[0m \u{1b}[38;5;75m`item_0`\u{1b}[0m: logical, 1.1\n\ \u{1b}[38;5;15m2.\u{1b}[0m \u{1b}[38;5;75m`item_1`\u{1b}[0m: 1, true\n", output ); assert_eq!( "\ 1. `item_0`: logical, 1.1\n\ 2. `item_1`: 1, true\n\ ", console::strip_ansi_codes(&output) ); Ok(()) } #[tokio::test] async fn outputs_state_diffs_as_text_colorized() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output_colorized(OutputFormat::Text); let state_diffs = { let mut state_diffs_mut = StateDiffsMut::new(); state_diffs_mut.insert(item_id!("item_0"), "need one more server"); state_diffs_mut.insert(item_id!("item_1"), 1); StateDiffs::from(state_diffs_mut) }; <CliOutput<_> as OutputWrite>::present(&mut cli_output, &state_diffs).await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!( "\ \u{1b}[38;5;15m1.\u{1b}[0m \u{1b}[38;5;75m`item_0`\u{1b}[0m: need one more server\n\ \u{1b}[38;5;15m2.\u{1b}[0m \u{1b}[38;5;75m`item_1`\u{1b}[0m: 1\n", output ); assert_eq!( "\ 1. `item_0`: need one more server\n\ 2. `item_1`: 1\n\ ", console::strip_ansi_codes(&output) ); Ok(()) } #[tokio::test] async fn outputs_error_as_text_colorized() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output_colorized(OutputFormat::Text); let error = Error::CliOutputTest; <CliOutput<_> as OutputWrite>::write_err(&mut cli_output, &error).await?; #[cfg(not(feature = "error_reporting"))] assert_eq!( "CliOutputTest display message.\n", String::from_utf8(cli_output.writer().clone())? ); #[cfg(feature = "error_reporting")] assert_eq!( concat!( "\u{1b}[31mworkspace_tests::cli::output::cli_output_test\u{1b}[0m\n", "\n", " \u{1b}[31m×\u{1b}[0m CliOutputTest display message.\n", "\u{1b}[36m help: \u{1b}[0mTry fixing the test.\n\n" ), String::from_utf8(cli_output.writer().clone())? ); Ok(()) } #[tokio::test] async fn outputs_states_as_yaml() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(OutputFormat::Yaml); let states_current_stored = { let mut states = StatesMut::new(); states.insert(item_id!("item_0"), State::new("logical", 1.1)); states.insert(item_id!("item_1"), State::new(1u8, true)); StatesCurrentStored::from(states) }; <CliOutput<_> as OutputWrite>::present(&mut cli_output, &states_current_stored).await?; assert_eq!( r#"item_0: logical: logical physical: 1.1 item_1: logical: 1 physical: true "#, String::from_utf8(cli_output.writer().clone())? ); Ok(()) } #[tokio::test] async fn outputs_state_diffs_as_yaml() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(OutputFormat::Yaml); let state_diffs = { let mut state_diffs_mut = StateDiffsMut::new(); state_diffs_mut.insert(item_id!("item_0"), "need one more server"); state_diffs_mut.insert(item_id!("item_1"), 1); StateDiffs::from(state_diffs_mut) }; <CliOutput<_> as OutputWrite>::present(&mut cli_output, &state_diffs).await?; assert_eq!( r#"item_0: need one more server item_1: 1 "#, String::from_utf8(cli_output.writer().clone())? ); Ok(()) } #[tokio::test] async fn outputs_error_as_yaml() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(OutputFormat::Yaml); let error = Error::CliOutputTest; <CliOutput<_> as OutputWrite>::write_err(&mut cli_output, &error).await?; assert_eq!( r#"CliOutputTest display message. "#, String::from_utf8(cli_output.writer().clone())? ); Ok(()) } #[tokio::test] async fn outputs_states_as_json() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(OutputFormat::Json); let states_current_stored = { let mut states = StatesMut::new(); states.insert(item_id!("item_0"), State::new("logical", 1.1)); states.insert(item_id!("item_1"), State::new(1u8, true)); StatesCurrentStored::from(states) }; <CliOutput<_> as OutputWrite>::present(&mut cli_output, &states_current_stored).await?; assert_eq!( r#"{"item_0":{"logical":"logical","physical":1.1},"item_1":{"logical":1,"physical":true}}"#, String::from_utf8(cli_output.writer().clone())? ); Ok(()) } #[tokio::test] async fn outputs_state_diffs_as_json() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(OutputFormat::Json); let state_diffs = { let mut state_diffs_mut = StateDiffsMut::new(); state_diffs_mut.insert(item_id!("item_0"), "need one more server"); state_diffs_mut.insert(item_id!("item_1"), 1); StateDiffs::from(state_diffs_mut) }; <CliOutput<_> as OutputWrite>::present(&mut cli_output, &state_diffs).await?; assert_eq!( r#"{"item_0":"need one more server","item_1":1}"#, String::from_utf8(cli_output.writer().clone())? ); Ok(()) } #[tokio::test] async fn outputs_error_as_json() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(OutputFormat::Json); let error = Error::CliOutputTest; <CliOutput<_> as OutputWrite>::write_err(&mut cli_output, &error).await?; assert_eq!( r#""CliOutputTest display message.""#, String::from_utf8(cli_output.writer().clone())? ); Ok(()) } #[tokio::test] async fn coverage_writer_mut() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(OutputFormat::Json); let error = Error::CliOutputTest; <CliOutput<_> as OutputWrite>::write_err(&mut cli_output, &error).await?; assert_eq!( r#""CliOutputTest display message.""#, String::from_utf8(cli_output.writer_mut().clone())? ); Ok(()) } #[cfg(feature = "output_progress")] mod color_always { use super::*; #[tokio::test] async fn progress_begin_sets_prefix_and_progress_bar_style() { let mut cli_output = cli_output_progress( OutputFormat::Text, CliColorizeOpt::Always, CliProgressFormatOpt::ProgressBar, ); let (cmd_progress_tracker, progress_bar) = cmd_progress_tracker(&cli_output); <CliOutput<_> as OutputWrite>::progress_begin(&mut cli_output, &cmd_progress_tracker).await; // Hack: because we enable this in `progress_begin` // Remove when we properly tick progress updates in `ApplyCmd`. progress_bar.disable_steady_tick(); // We can't inspect `ProgressStyle`'s fields, so we have to render the progress // and compare the output. assert_eq!( "\u{1b}[38;5;15m1.\u{1b}[0m \u{1b}[38;5;75mtest_item_id\u{1b}[0m", progress_bar.prefix() ); let CliOutputTarget::InMemory(in_memory_term) = cli_output.progress_target() else { ({ #[cfg_attr(coverage_nightly, coverage(off))] || -> ! { unreachable!("This is set in `cli_output_progress`.") } })(); }; assert_eq!( r#"⚫ 1. test_item_id ▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱ (el: 0s, eta: 0s)"#, // ^ ^ ^ ^ // '-- 15 chars -' '-------------- 40 chars --------------' in_memory_term.contents() ); } #[tokio::test] async fn progress_update_with_limit_sets_progress_bar_style() { let mut cli_output = cli_output_progress( OutputFormat::Text, CliColorizeOpt::Always, CliProgressFormatOpt::ProgressBar, ); let (mut cmd_progress_tracker, progress_bar) = cmd_progress_tracker(&cli_output); <CliOutput<_> as OutputWrite>::progress_begin(&mut cli_output, &cmd_progress_tracker).await; // Hack: because we enable this in `progress_begin` // Remove when we properly tick progress updates in `ApplyCmd`. progress_bar.disable_steady_tick(); let progress_trackers = cmd_progress_tracker.progress_trackers_mut(); let progress_tracker = progress_trackers .get_mut(&item_id!("test_item_id")) .unwrap(); // Adjust progress_bar length and units. progress_tracker.set_progress_status(ProgressStatus::Running); progress_tracker.set_progress_limit(ProgressLimit::Steps(100)); progress_bar.set_length(100); let progress_update_and_id = ProgressUpdateAndId { item_id: item_id!("test_item_id"), progress_update: ProgressUpdate::Limit(ProgressLimit::Steps(100)), msg_update: ProgressMsgUpdate::NoChange, }; <CliOutput<_> as OutputWrite>::progress_update( &mut cli_output, progress_tracker, &progress_update_and_id, ) .await; assert_eq!( "\u{1b}[38;5;15m1.\u{1b}[0m \u{1b}[38;5;75mtest_item_id\u{1b}[0m", progress_bar.prefix() ); let CliOutputTarget::InMemory(in_memory_term) = cli_output.progress_target() else { ({ #[cfg_attr(coverage_nightly, coverage(off))] || -> ! { unreachable!("This is set in `cli_output_progress`.") } })(); }; progress_bar.set_position(20); assert_eq!( r#"🔵 1. test_item_id ▰▰▰▰▰▰▰▰▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱ 20/100 (el: 0s, eta: 0s)"#, in_memory_term.contents() ); progress_bar.set_position(21); assert_eq!( r#"🔵 1. test_item_id ▰▰▰▰▰▰▰▰▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱ 21/100 (el: 0s, eta: 0s)"#, in_memory_term.contents() ); progress_bar.set_position(22); assert_eq!( r#"🔵 1. test_item_id ▰▰▰▰▰▰▰▰▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱ 22/100 (el: 0s, eta: 0s)"#, in_memory_term.contents() ); } #[tokio::test] async fn progress_update_with_complete_success_finishes_progress_bar() { let mut cli_output = cli_output_progress( OutputFormat::Text, CliColorizeOpt::Always, CliProgressFormatOpt::ProgressBar, ); let (mut cmd_progress_tracker, progress_bar) = cmd_progress_tracker(&cli_output); <CliOutput<_> as OutputWrite>::progress_begin(&mut cli_output, &cmd_progress_tracker).await; // Hack: because we enable this in `progress_begin` // Remove when we properly tick progress updates in `ApplyCmd`. progress_bar.disable_steady_tick(); let progress_trackers = cmd_progress_tracker.progress_trackers_mut(); let progress_tracker = progress_trackers .get_mut(&item_id!("test_item_id")) .unwrap(); // Adjust progress_bar length and units. progress_tracker.set_progress_status(ProgressStatus::Running); progress_tracker.set_progress_limit(ProgressLimit::Steps(100)); progress_bar.set_length(100); let progress_update_and_id = ProgressUpdateAndId { item_id: item_id!("test_item_id"), progress_update: ProgressUpdate::Limit(ProgressLimit::Steps(100)), msg_update: ProgressMsgUpdate::NoChange, }; <CliOutput<_> as OutputWrite>::progress_update( &mut cli_output, progress_tracker, &progress_update_and_id, ) .await; // Check current position let CliOutputTarget::InMemory(in_memory_term) = cli_output.progress_target() else { ({ #[cfg_attr(coverage_nightly, coverage(off))] || -> ! { unreachable!("This is set in `cli_output_progress`.") } })(); }; progress_bar.set_position(20); assert_eq!( r#"🔵 1. test_item_id ▰▰▰▰▰▰▰▰▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱ 20/100 (el: 0s, eta: 0s)"#, in_memory_term.contents() ); let progress_complete = ProgressComplete::Success; progress_tracker.set_progress_status(ProgressStatus::Complete(progress_complete.clone())); progress_tracker.set_message(Some(String::from("done"))); let progress_update_and_id = ProgressUpdateAndId { item_id: item_id!("test_item_id"), progress_update: ProgressUpdate::Complete(progress_complete), msg_update: ProgressMsgUpdate::Set(String::from("done")), }; <CliOutput<_> as OutputWrite>::progress_update( &mut cli_output, progress_tracker, &progress_update_and_id, ) .await; let CliOutputTarget::InMemory(in_memory_term) = cli_output.progress_target() else { ({ #[cfg_attr(coverage_nightly, coverage(off))] || -> ! { unreachable!("This is set in `cli_output_progress`.") } })(); }; assert_eq!( r#"✅ 1. test_item_id ▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰ done"#, in_memory_term.contents(), ); } #[tokio::test] async fn progress_update_with_complete_fail_abandons_progress_bar() { let mut cli_output = cli_output_progress( OutputFormat::Text, CliColorizeOpt::Always, CliProgressFormatOpt::ProgressBar, ); let (mut cmd_progress_tracker, progress_bar) = cmd_progress_tracker(&cli_output); <CliOutput<_> as OutputWrite>::progress_begin(&mut cli_output, &cmd_progress_tracker).await; // Hack: because we enable this in `progress_begin` // Remove when we properly tick progress updates in `ApplyCmd`. progress_bar.disable_steady_tick(); let progress_trackers = cmd_progress_tracker.progress_trackers_mut(); let progress_tracker = progress_trackers .get_mut(&item_id!("test_item_id")) .unwrap(); // Adjust progress_bar length and units. progress_tracker.set_progress_status(ProgressStatus::Running); progress_tracker.set_progress_limit(ProgressLimit::Steps(100)); progress_bar.set_length(100); let progress_update_and_id = ProgressUpdateAndId { item_id: item_id!("test_item_id"), progress_update: ProgressUpdate::Limit(ProgressLimit::Steps(100)), msg_update: ProgressMsgUpdate::NoChange, }; <CliOutput<_> as OutputWrite>::progress_update( &mut cli_output, progress_tracker, &progress_update_and_id, ) .await; // Check current position let CliOutputTarget::InMemory(in_memory_term) = cli_output.progress_target() else { ({ #[cfg_attr(coverage_nightly, coverage(off))] || -> ! { unreachable!("This is set in `cli_output_progress`.") } })(); }; progress_bar.set_position(20); assert_eq!( r#"🔵 1. test_item_id ▰▰▰▰▰▰▰▰▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱ 20/100 (el: 0s, eta: 0s)"#, in_memory_term.contents() ); let progress_complete = ProgressComplete::Fail; progress_tracker.set_progress_status(ProgressStatus::Complete(progress_complete.clone())); progress_tracker.set_message(Some(String::from("done"))); let progress_update_and_id = ProgressUpdateAndId { item_id: item_id!("test_item_id"), progress_update: ProgressUpdate::Complete(progress_complete), msg_update: ProgressMsgUpdate::Set(String::from("done")), }; <CliOutput<_> as OutputWrite>::progress_update( &mut cli_output, progress_tracker, &progress_update_and_id, ) .await; let CliOutputTarget::InMemory(in_memory_term) = cli_output.progress_target() else { ({ #[cfg_attr(coverage_nightly, coverage(off))] || -> ! { unreachable!("This is set in `cli_output_progress`.") } })(); }; assert_eq!( r#"❌ 1. test_item_id ▰▰▰▰▰▰▰▰▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱ 20/100 done"#, in_memory_term.contents() ); } #[tokio::test] async fn progress_update_delta_with_progress_format_outcome_writes_yaml() { let mut cli_output = cli_output_progress( OutputFormat::Text, CliColorizeOpt::Always, CliProgressFormatOpt::Outcome, ); let (mut cmd_progress_tracker, progress_bar) = cmd_progress_tracker(&cli_output); <CliOutput<_> as OutputWrite>::progress_begin(&mut cli_output, &cmd_progress_tracker).await; // Hack: because we enable this in `progress_begin` // Remove when we properly tick progress updates in `ApplyCmd`. progress_bar.disable_steady_tick(); let progress_trackers = cmd_progress_tracker.progress_trackers_mut(); let progress_tracker = progress_trackers .get_mut(&item_id!("test_item_id")) .unwrap(); let progress_update_and_id = ProgressUpdateAndId { item_id: item_id!("test_item_id"), progress_update: ProgressUpdate::Limit(ProgressLimit::Steps(100)), msg_update: ProgressMsgUpdate::NoChange, }; <CliOutput<_> as OutputWrite>::progress_update( &mut cli_output, progress_tracker, &progress_update_and_id, ) .await; // Adjust progress_bar length and units. progress_tracker.set_progress_status(ProgressStatus::Running); progress_tracker.set_progress_limit(ProgressLimit::Steps(100)); progress_bar.set_length(100); let progress_update_and_id = ProgressUpdateAndId { item_id: item_id!("test_item_id"), progress_update: ProgressUpdate::Delta(ProgressDelta::Inc(21)), msg_update: ProgressMsgUpdate::NoChange, }; <CliOutput<_> as OutputWrite>::progress_update( &mut cli_output, progress_tracker, &progress_update_and_id, ) .await; let CliOutputTarget::InMemory(in_memory_term) = cli_output.progress_target() else { ({ #[cfg_attr(coverage_nightly, coverage(off))] || -> ! { unreachable!("This is set in `cli_output_progress`.") } })(); }; assert_eq!( r#"--- item_id: test_item_id progress_update: !Limit Steps: 100 msg_update: NoChange --- item_id: test_item_id progress_update: !Delta Inc: 21 msg_update: NoChange"#, in_memory_term.contents() ); } #[cfg(feature = "output_progress")] #[tokio::test] async fn progress_update_delta_with_progress_format_outcome_writes_json() { let mut cli_output = cli_output_progress( OutputFormat::Json, CliColorizeOpt::Always, CliProgressFormatOpt::Outcome, ); let (mut cmd_progress_tracker, progress_bar) = cmd_progress_tracker(&cli_output); <CliOutput<_> as OutputWrite>::progress_begin(&mut cli_output, &cmd_progress_tracker).await; // Hack: because we enable this in `progress_begin` // Remove when we properly tick progress updates in `ApplyCmd`. progress_bar.disable_steady_tick(); let progress_trackers = cmd_progress_tracker.progress_trackers_mut(); let progress_tracker = progress_trackers .get_mut(&item_id!("test_item_id")) .unwrap(); let progress_update_and_id = ProgressUpdateAndId { item_id: item_id!("test_item_id"), progress_update: ProgressUpdate::Limit(ProgressLimit::Steps(100)), msg_update: ProgressMsgUpdate::NoChange, }; <CliOutput<_> as OutputWrite>::progress_update( &mut cli_output, progress_tracker, &progress_update_and_id, ) .await; // Adjust progress_bar length and units. progress_tracker.set_progress_status(ProgressStatus::Running); progress_tracker.set_progress_limit(ProgressLimit::Steps(100)); progress_bar.set_length(100); let progress_update_and_id = ProgressUpdateAndId { item_id: item_id!("test_item_id"), progress_update: ProgressUpdate::Delta(ProgressDelta::Inc(21)), msg_update: ProgressMsgUpdate::NoChange, }; <CliOutput<_> as OutputWrite>::progress_update( &mut cli_output, progress_tracker, &progress_update_and_id, ) .await; let CliOutputTarget::InMemory(in_memory_term) = cli_output.progress_target() else { ({ #[cfg_attr(coverage_nightly, coverage(off))] || -> ! { unreachable!("This is set in `cli_output_progress`.") } })(); }; assert_eq!( r#"{"item_id":"test_item_id","progress_update":{"Limit":{"Steps":100}},"msg_update":"NoChange"} {"item_id":"test_item_id","progress_update":{"Delta":{"Inc":21}},"msg_update":"NoChange"}"#, in_memory_term.contents() ); } } #[cfg(feature = "output_progress")] mod color_never { use super::*; #[tokio::test] async fn progress_begin_sets_prefix_and_progress_bar_style() { let mut cli_output = cli_output_progress( OutputFormat::Text, CliColorizeOpt::Never, CliProgressFormatOpt::ProgressBar, ); let (cmd_progress_tracker, progress_bar) = cmd_progress_tracker(&cli_output); <CliOutput<_> as OutputWrite>::progress_begin(&mut cli_output, &cmd_progress_tracker).await; // Hack: because we enable this in `progress_begin` // Remove when we properly tick progress updates in `ApplyCmd`. progress_bar.disable_steady_tick(); // We can't inspect `ProgressStyle`'s fields, so we have to render the progress // and compare the output. assert_eq!("1. test_item_id", progress_bar.prefix()); let CliOutputTarget::InMemory(in_memory_term) = cli_output.progress_target() else { ({ #[cfg_attr(coverage_nightly, coverage(off))] || -> ! { unreachable!("This is set in `cli_output_progress`.") } })(); }; assert_eq!( r#"⚫ 1. test_item_id ▰▰▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱ (el: 0s, eta: 0s)"#, // ^ ^ ^ ^ // '-- 15 chars -' '-------------- 40 chars --------------' in_memory_term.contents() ); } #[tokio::test] async fn progress_update_with_limit_sets_progress_bar_style() { let mut cli_output = cli_output_progress( OutputFormat::Text, CliColorizeOpt::Never, CliProgressFormatOpt::ProgressBar, ); let (mut cmd_progress_tracker, progress_bar) = cmd_progress_tracker(&cli_output); <CliOutput<_> as OutputWrite>::progress_begin(&mut cli_output, &cmd_progress_tracker).await; // Hack: because we enable this in `progress_begin` // Remove when we properly tick progress updates in `ApplyCmd`. progress_bar.disable_steady_tick(); let progress_trackers = cmd_progress_tracker.progress_trackers_mut(); let progress_tracker = progress_trackers .get_mut(&item_id!("test_item_id")) .unwrap(); // Adjust progress_bar length and units. progress_tracker.set_progress_status(ProgressStatus::Running); progress_tracker.set_progress_limit(ProgressLimit::Steps(100)); progress_bar.set_length(100); let progress_update_and_id = ProgressUpdateAndId { item_id: item_id!("test_item_id"), progress_update: ProgressUpdate::Limit(ProgressLimit::Steps(100)), msg_update: ProgressMsgUpdate::NoChange, }; <CliOutput<_> as OutputWrite>::progress_update( &mut cli_output, progress_tracker, &progress_update_and_id, ) .await; assert_eq!("1. test_item_id", progress_bar.prefix()); let CliOutputTarget::InMemory(in_memory_term) = cli_output.progress_target() else { ({ #[cfg_attr(coverage_nightly, coverage(off))] || -> ! { unreachable!("This is set in `cli_output_progress`.") } })(); }; progress_bar.set_position(20); assert_eq!( r#"🔵 1. test_item_id ▰▰▰▰▰▰▰▰▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱ 20/100 (el: 0s, eta: 0s)"#, in_memory_term.contents() ); progress_bar.set_position(21); assert_eq!( r#"🔵 1. test_item_id ▰▰▰▰▰▰▰▰▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱ 21/100 (el: 0s, eta: 0s)"#, in_memory_term.contents() ); progress_bar.set_position(22); assert_eq!( r#"🔵 1. test_item_id ▰▰▰▰▰▰▰▰▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱ 22/100 (el: 0s, eta: 0s)"#, in_memory_term.contents() ); } #[tokio::test] async fn progress_update_with_complete_success_finishes_progress_bar() { let mut cli_output = cli_output_progress( OutputFormat::Text, CliColorizeOpt::Never, CliProgressFormatOpt::ProgressBar, ); let (mut cmd_progress_tracker, progress_bar) = cmd_progress_tracker(&cli_output); <CliOutput<_> as OutputWrite>::progress_begin(&mut cli_output, &cmd_progress_tracker).await; // Hack: because we enable this in `progress_begin` // Remove when we properly tick progress updates in `ApplyCmd`. progress_bar.disable_steady_tick(); let progress_trackers = cmd_progress_tracker.progress_trackers_mut(); let progress_tracker = progress_trackers .get_mut(&item_id!("test_item_id")) .unwrap(); // Adjust progress_bar length and units. progress_tracker.set_progress_status(ProgressStatus::Running); progress_tracker.set_progress_limit(ProgressLimit::Steps(100)); progress_bar.set_length(100); let progress_update_and_id = ProgressUpdateAndId { item_id: item_id!("test_item_id"), progress_update: ProgressUpdate::Limit(ProgressLimit::Steps(100)), msg_update: ProgressMsgUpdate::NoChange, }; <CliOutput<_> as OutputWrite>::progress_update( &mut cli_output, progress_tracker, &progress_update_and_id, ) .await; // Check current position let CliOutputTarget::InMemory(in_memory_term) = cli_output.progress_target() else { ({ #[cfg_attr(coverage_nightly, coverage(off))] || -> ! { unreachable!("This is set in `cli_output_progress`.") } })(); }; progress_bar.set_position(20); assert_eq!( r#"🔵 1. test_item_id ▰▰▰▰▰▰▰▰▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱ 20/100 (el: 0s, eta: 0s)"#, in_memory_term.contents() ); let progress_complete = ProgressComplete::Success; progress_tracker.set_progress_status(ProgressStatus::Complete(progress_complete.clone())); progress_tracker.set_message(Some(String::from("done"))); let progress_update_and_id = ProgressUpdateAndId { item_id: item_id!("test_item_id"), progress_update: ProgressUpdate::Complete(progress_complete), msg_update: ProgressMsgUpdate::Set(String::from("done")), }; <CliOutput<_> as OutputWrite>::progress_update( &mut cli_output, progress_tracker,
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
true
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/cli/output/cli_md_presenter.rs
workspace_tests/src/cli/output/cli_md_presenter.rs
use futures::stream::{self, StreamExt, TryStreamExt}; use peace::{ cli::output::{CliMdPresenter, CliOutput, CliOutputBuilder}, cli_model::OutputFormat, fmt::{ presentable::{Bold, CodeInline, HeadingLevel}, Presenter, }, }; use peace::cli::output::CliColorizeOpt; #[tokio::test] async fn presents_heading_with_hashes_color_disabled() -> Result<(), Box<dyn std::error::Error>> { stream::iter([ (HeadingLevel::Level1, "# `code`\n\n"), (HeadingLevel::Level2, "## `code`\n\n"), (HeadingLevel::Level3, "### `code`\n\n"), (HeadingLevel::Level4, "#### `code`\n\n"), (HeadingLevel::Level5, "##### `code`\n\n"), (HeadingLevel::Level6, "###### `code`\n\n"), ]) .map(Result::<_, Box<dyn std::error::Error>>::Ok) .try_for_each(|(heading_level, expected)| async move { let mut cli_output = cli_output(CliColorizeOpt::Never); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter .heading(heading_level, &CodeInline::new("code".into())) .await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!(expected, output); Ok(()) }) .await } #[tokio::test] async fn presents_heading_with_hashes_color_enabled() -> Result<(), Box<dyn std::error::Error>> { stream::iter([ ( HeadingLevel::Level1, "\u{1b}[38;5;243m\u{1b}[1m#\u{1b}[0m \u{1b}[38;5;75m\u{1b}[1m`code`\u{1b}[0m\n\n", "# `code`\n\n", ), ( HeadingLevel::Level2, "\u{1b}[38;5;243m\u{1b}[1m##\u{1b}[0m \u{1b}[38;5;75m\u{1b}[1m`code`\u{1b}[0m\n\n", "## `code`\n\n", ), ( HeadingLevel::Level3, "\u{1b}[38;5;243m\u{1b}[1m###\u{1b}[0m \u{1b}[38;5;75m\u{1b}[1m`code`\u{1b}[0m\n\n", "### `code`\n\n", ), ( HeadingLevel::Level4, "\u{1b}[38;5;243m\u{1b}[1m####\u{1b}[0m \u{1b}[38;5;75m\u{1b}[1m`code`\u{1b}[0m\n\n", "#### `code`\n\n", ), ( HeadingLevel::Level5, "\u{1b}[38;5;243m\u{1b}[1m#####\u{1b}[0m \u{1b}[38;5;75m\u{1b}[1m`code`\u{1b}[0m\n\n", "##### `code`\n\n", ), ( HeadingLevel::Level6, "\u{1b}[38;5;243m\u{1b}[1m######\u{1b}[0m \u{1b}[38;5;75m\u{1b}[1m`code`\u{1b}[0m\n\n", "###### `code`\n\n", ), ]) .map(Result::<_, Box<dyn std::error::Error>>::Ok) .try_for_each(|(heading_level, expected_colorized, expected)| async move { let mut cli_output = cli_output(CliColorizeOpt::Always); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter .heading(heading_level, &CodeInline::new("code".into())) .await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!(expected_colorized, output); assert_eq!(expected, console::strip_ansi_codes(&output)); Ok(()) }) .await } #[tokio::test] async fn presents_bold_with_double_asterisk_color_disabled( ) -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Never); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter.bold(&String::from("bold")).await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!("**bold**", output); assert_eq!("**bold**", console::strip_ansi_codes(&output)); Ok(()) } #[tokio::test] async fn presents_bold_with_double_asterisk_color_enabled() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Always); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter.bold(&String::from("bold")).await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!("**\u{1b}[1mbold\u{1b}[0m**", output); assert_eq!("**bold**", console::strip_ansi_codes(&output)); Ok(()) } #[tokio::test] async fn presents_bold_wrapping_code_inline_with_double_asterisk_color_disabled( ) -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Never); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter.bold(&CodeInline::new("code".into())).await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!("**`code`**", output); assert_eq!("**`code`**", console::strip_ansi_codes(&output)); Ok(()) } #[tokio::test] async fn presents_bold_wrapping_code_inline_with_double_asterisk_color_enabled( ) -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Always); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter.bold(&CodeInline::new("code".into())).await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!("**\u{1b}[38;5;75m\u{1b}[1m`code`\u{1b}[0m**", output); assert_eq!("**`code`**", console::strip_ansi_codes(&output)); Ok(()) } #[tokio::test] async fn presents_id_as_plain_text_color_disabled() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Never); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter.id("an_id").await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!("an_id", output); Ok(()) } #[tokio::test] async fn presents_id_as_blue_text_color_enabled() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Always); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter.id("an_id").await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!("\u{1b}[38;5;75man_id\u{1b}[0m", output); assert_eq!("an_id", console::strip_ansi_codes(&output)); Ok(()) } #[tokio::test] async fn presents_name_with_double_asterisk_color_disabled( ) -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Never); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter.name("A Name").await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!("**A Name**", output); Ok(()) } #[tokio::test] async fn presents_name_with_double_asterisk_bold_text_color_enabled( ) -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Always); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter.name("A Name").await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!("\u{1b}[1m**A Name**\u{1b}[0m", output); assert_eq!("**A Name**", console::strip_ansi_codes(&output)); Ok(()) } #[tokio::test] async fn presents_text_as_plain_text_color_disabled() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Never); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter.text("hello").await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!("hello", output); Ok(()) } #[tokio::test] async fn presents_text_as_plain_text_color_enabled() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Always); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter.text("hello").await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!("hello", output); Ok(()) } #[tokio::test] async fn presents_tag_with_black_tortoise_shell_plain_text_color_disabled( ) -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Never); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter.tag("tag").await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!("⦗tag⦘", output); Ok(()) } #[tokio::test] async fn presents_tag_with_black_tortoise_shell_purple_text_color_enabled( ) -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Always); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter.tag("tag").await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!("\u{1b}[38;5;219m\u{1b}[1m⦗tag⦘\u{1b}[0m", output); assert_eq!("⦗tag⦘", console::strip_ansi_codes(&output)); Ok(()) } #[tokio::test] async fn presents_code_inline_with_backticks_color_disabled( ) -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Never); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter.code_inline("code_inline").await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!("`code_inline`", output); Ok(()) } #[tokio::test] async fn presents_code_inline_with_backticks_blue_text_color_enabled( ) -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Always); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter.code_inline("code_inline").await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!("\u{1b}[38;5;75m`code_inline`\u{1b}[0m", output); assert_eq!("`code_inline`", console::strip_ansi_codes(&output)); Ok(()) } #[tokio::test] async fn presents_list_numbered_color_disabled() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Never); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter .list_numbered(&[String::from("Item 1"), String::from("Item 2")]) .await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!( "\ 1. Item 1\n\ 2. Item 2\n\ ", output ); Ok(()) } #[tokio::test] async fn presents_list_numbered_white_text_color_enabled() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Always); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter .list_numbered(&[String::from("Item 1"), String::from("Item 2")]) .await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!( "\ \u{1b}[38;5;15m1.\u{1b}[0m Item 1\n\ \u{1b}[38;5;15m2.\u{1b}[0m Item 2\n\ ", output ); assert_eq!( "\ 1. Item 1\n\ 2. Item 2\n\ ", console::strip_ansi_codes(&output) ); Ok(()) } #[tokio::test] async fn presents_list_numbered_padding_color_disabled() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Never); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter .list_numbered( &(1..=11) .map(|n| format!("Item {n}")) .collect::<Vec<String>>(), ) .await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!( r#" 1. Item 1 2. Item 2 3. Item 3 4. Item 4 5. Item 5 6. Item 6 7. Item 7 8. Item 8 9. Item 9 10. Item 10 11. Item 11 "#, output ); Ok(()) } #[tokio::test] async fn presents_list_numbered_padding_color_enabled() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Always); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter .list_numbered( &(1..=11) .map(|n| format!("Item {n}")) .collect::<Vec<String>>(), ) .await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!( " \u{1b}[38;5;15m1.\u{1b}[0m Item 1 \u{1b}[38;5;15m2.\u{1b}[0m Item 2 \u{1b}[38;5;15m3.\u{1b}[0m Item 3 \u{1b}[38;5;15m4.\u{1b}[0m Item 4 \u{1b}[38;5;15m5.\u{1b}[0m Item 5 \u{1b}[38;5;15m6.\u{1b}[0m Item 6 \u{1b}[38;5;15m7.\u{1b}[0m Item 7 \u{1b}[38;5;15m8.\u{1b}[0m Item 8 \u{1b}[38;5;15m9.\u{1b}[0m Item 9 \u{1b}[38;5;15m10.\u{1b}[0m Item 10 \u{1b}[38;5;15m11.\u{1b}[0m Item 11 ", output ); assert_eq!( r#" 1. Item 1 2. Item 2 3. Item 3 4. Item 4 5. Item 5 6. Item 6 7. Item 7 8. Item 8 9. Item 9 10. Item 10 11. Item 11 "#, console::strip_ansi_codes(&output) ); Ok(()) } #[tokio::test] async fn presents_list_numbered_with_color_disabled() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Never); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter .list_numbered_with(&[true, false], |first| { if *first { String::from("Item 1") } else { String::from("Item 2") } }) .await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!( "\ 1. Item 1\n\ 2. Item 2\n\ ", output ); Ok(()) } #[tokio::test] async fn presents_list_numbered_with_white_text_color_enabled( ) -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Always); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter .list_numbered_with(&[true, false], |first| { if *first { String::from("Item 1") } else { String::from("Item 2") } }) .await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!( "\ \u{1b}[38;5;15m1.\u{1b}[0m Item 1\n\ \u{1b}[38;5;15m2.\u{1b}[0m Item 2\n\ ", output ); assert_eq!( "\ 1. Item 1\n\ 2. Item 2\n\ ", console::strip_ansi_codes(&output) ); Ok(()) } #[tokio::test] async fn presents_list_numbered_with_padding_color_disabled( ) -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Never); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter .list_numbered_with(1..=11, |n| format!("Item {n}")) .await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!( r#" 1. Item 1 2. Item 2 3. Item 3 4. Item 4 5. Item 5 6. Item 6 7. Item 7 8. Item 8 9. Item 9 10. Item 10 11. Item 11 "#, output ); Ok(()) } #[tokio::test] async fn presents_list_numbered_with_padding_color_enabled( ) -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Always); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter .list_numbered_with(1..=11, |n| format!("Item {n}")) .await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!( " \u{1b}[38;5;15m1.\u{1b}[0m Item 1 \u{1b}[38;5;15m2.\u{1b}[0m Item 2 \u{1b}[38;5;15m3.\u{1b}[0m Item 3 \u{1b}[38;5;15m4.\u{1b}[0m Item 4 \u{1b}[38;5;15m5.\u{1b}[0m Item 5 \u{1b}[38;5;15m6.\u{1b}[0m Item 6 \u{1b}[38;5;15m7.\u{1b}[0m Item 7 \u{1b}[38;5;15m8.\u{1b}[0m Item 8 \u{1b}[38;5;15m9.\u{1b}[0m Item 9 \u{1b}[38;5;15m10.\u{1b}[0m Item 10 \u{1b}[38;5;15m11.\u{1b}[0m Item 11 ", output ); assert_eq!( r#" 1. Item 1 2. Item 2 3. Item 3 4. Item 4 5. Item 5 6. Item 6 7. Item 7 8. Item 8 9. Item 9 10. Item 10 11. Item 11 "#, console::strip_ansi_codes(&output) ); Ok(()) } #[tokio::test] async fn presents_list_numbered_aligned_color_disabled() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Never); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter .list_numbered_aligned(&[ ( Bold::new(String::from("Short")), ( String::from("description with "), CodeInline::new("code".into()), ), ), ( Bold::new(String::from("Long Name")), ( String::from("another description "), CodeInline::new("code".into()), ), ), ]) .await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!( "\ 1. **Short** : description with `code`\n\ 2. **Long Name**: another description `code`\n\ ", output ); Ok(()) } #[tokio::test] async fn presents_list_numbered_aligned_white_text_color_enabled( ) -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Always); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter .list_numbered_aligned(&[ ( Bold::new(String::from("Short")), ( String::from("description with "), CodeInline::new("code".into()), ), ), ( Bold::new(String::from("Long Name")), ( String::from("another description "), CodeInline::new("code".into()), ), ), ]) .await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!( "\ \u{1b}[38;5;15m1.\u{1b}[0m **\u{1b}[1mShort\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m\n\ \u{1b}[38;5;15m2.\u{1b}[0m **\u{1b}[1mLong Name\u{1b}[0m**: another description \u{1b}[38;5;75m`code`\u{1b}[0m\n\ ", output ); assert_eq!( "\ 1. **Short** : description with `code`\n\ 2. **Long Name**: another description `code`\n\ ", console::strip_ansi_codes(&output) ); Ok(()) } #[tokio::test] async fn presents_list_numbered_aligned_padding_color_disabled( ) -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Never); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter .list_numbered_aligned( &(1..=11) .map(|n| { ( Bold::new(format!("Item {n}")), ( String::from("description with "), CodeInline::new("code".into()), ), ) }) .collect::<Vec<_>>(), ) .await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!( " 1. **Item 1** : description with `code` 2. **Item 2** : description with `code` 3. **Item 3** : description with `code` 4. **Item 4** : description with `code` 5. **Item 5** : description with `code` 6. **Item 6** : description with `code` 7. **Item 7** : description with `code` 8. **Item 8** : description with `code` 9. **Item 9** : description with `code` 10. **Item 10**: description with `code` 11. **Item 11**: description with `code` ", output ); Ok(()) } #[tokio::test] async fn presents_list_numbered_aligned_padding_color_enabled( ) -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Always); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter .list_numbered_aligned( &(1..=11) .map(|n| { ( Bold::new(format!("Item {n}")), ( String::from("description with "), CodeInline::new("code".into()), ), ) }) .collect::<Vec<_>>(), ) .await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!( " \u{1b}[38;5;15m1.\u{1b}[0m **\u{1b}[1mItem 1\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m2.\u{1b}[0m **\u{1b}[1mItem 2\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m3.\u{1b}[0m **\u{1b}[1mItem 3\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m4.\u{1b}[0m **\u{1b}[1mItem 4\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m5.\u{1b}[0m **\u{1b}[1mItem 5\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m6.\u{1b}[0m **\u{1b}[1mItem 6\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m7.\u{1b}[0m **\u{1b}[1mItem 7\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m8.\u{1b}[0m **\u{1b}[1mItem 8\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m9.\u{1b}[0m **\u{1b}[1mItem 9\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m10.\u{1b}[0m **\u{1b}[1mItem 10\u{1b}[0m**: description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m11.\u{1b}[0m **\u{1b}[1mItem 11\u{1b}[0m**: description with \u{1b}[38;5;75m`code`\u{1b}[0m ", output ); assert_eq!( " 1. **Item 1** : description with `code` 2. **Item 2** : description with `code` 3. **Item 3** : description with `code` 4. **Item 4** : description with `code` 5. **Item 5** : description with `code` 6. **Item 6** : description with `code` 7. **Item 7** : description with `code` 8. **Item 8** : description with `code` 9. **Item 9** : description with `code` 10. **Item 10**: description with `code` 11. **Item 11**: description with `code` ", console::strip_ansi_codes(&output) ); Ok(()) } #[tokio::test] async fn presents_list_bulleted_color_disabled() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Never); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter .list_bulleted(&[String::from("Item 1"), String::from("Item 2")]) .await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!( "\ * Item 1\n\ * Item 2\n\ ", output ); Ok(()) } #[tokio::test] async fn presents_list_bulleted_white_text_color_enabled() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Always); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter .list_bulleted(&[String::from("Item 1"), String::from("Item 2")]) .await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!( "\ \u{1b}[38;5;15m*\u{1b}[0m Item 1\n\ \u{1b}[38;5;15m*\u{1b}[0m Item 2\n\ ", output ); assert_eq!( "\ * Item 1\n\ * Item 2\n\ ", console::strip_ansi_codes(&output) ); Ok(()) } #[tokio::test] async fn presents_list_bulleted_with_color_disabled() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Never); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter .list_bulleted_with(&[true, false], |first| { if *first { String::from("Item 1") } else { String::from("Item 2") } }) .await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!( "\ * Item 1\n\ * Item 2\n\ ", output ); Ok(()) } #[tokio::test] async fn presents_list_bulleted_with_white_text_color_enabled( ) -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Always); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter .list_bulleted_with(&[true, false], |first| { if *first { String::from("Item 1") } else { String::from("Item 2") } }) .await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!( "\ \u{1b}[38;5;15m*\u{1b}[0m Item 1\n\ \u{1b}[38;5;15m*\u{1b}[0m Item 2\n\ ", output ); assert_eq!( "\ * Item 1\n\ * Item 2\n\ ", console::strip_ansi_codes(&output) ); Ok(()) } #[tokio::test] async fn presents_list_bulleted_aligned_color_disabled() -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Never); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter .list_bulleted_aligned(&[ ( Bold::new(String::from("Short")), ( String::from("description with "), CodeInline::new("code".into()), ), ), ( Bold::new(String::from("Long Name")), ( String::from("another description "), CodeInline::new("code".into()), ), ), ]) .await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!( "\ * **Short** : description with `code`\n\ * **Long Name**: another description `code`\n\ ", output ); Ok(()) } #[tokio::test] async fn presents_list_bulleted_aligned_white_text_color_enabled( ) -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Always); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter .list_bulleted_aligned(&[ ( Bold::new(String::from("Short")), ( String::from("description with "), CodeInline::new("code".into()), ), ), ( Bold::new(String::from("Long Name")), ( String::from("another description "), CodeInline::new("code".into()), ), ), ]) .await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!( "\ \u{1b}[38;5;15m*\u{1b}[0m **\u{1b}[1mShort\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m\n\ \u{1b}[38;5;15m*\u{1b}[0m **\u{1b}[1mLong Name\u{1b}[0m**: another description \u{1b}[38;5;75m`code`\u{1b}[0m\n\ ", output ); assert_eq!( "\ * **Short** : description with `code`\n\ * **Long Name**: another description `code`\n\ ", console::strip_ansi_codes(&output) ); Ok(()) } #[tokio::test] async fn presents_list_bulleted_aligned_padding_color_disabled( ) -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Never); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter .list_bulleted_aligned( &(1..=11) .map(|n| { ( Bold::new(format!("Item {n}")), ( String::from("description with "), CodeInline::new("code".into()), ), ) }) .collect::<Vec<_>>(), ) .await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!( "* **Item 1** : description with `code` * **Item 2** : description with `code` * **Item 3** : description with `code` * **Item 4** : description with `code` * **Item 5** : description with `code` * **Item 6** : description with `code` * **Item 7** : description with `code` * **Item 8** : description with `code` * **Item 9** : description with `code` * **Item 10**: description with `code` * **Item 11**: description with `code` ", output ); Ok(()) } #[tokio::test] async fn presents_list_bulleted_aligned_padding_color_enabled( ) -> Result<(), Box<dyn std::error::Error>> { let mut cli_output = cli_output(CliColorizeOpt::Always); let mut presenter = CliMdPresenter::new(&mut cli_output); presenter .list_bulleted_aligned( &(1..=11) .map(|n| { ( Bold::new(format!("Item {n}")), ( String::from("description with "), CodeInline::new("code".into()), ), ) }) .collect::<Vec<_>>(), ) .await?; let output = String::from_utf8(cli_output.writer().clone())?; assert_eq!( "\u{1b}[38;5;15m*\u{1b}[0m **\u{1b}[1mItem 1\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m*\u{1b}[0m **\u{1b}[1mItem 2\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m*\u{1b}[0m **\u{1b}[1mItem 3\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m*\u{1b}[0m **\u{1b}[1mItem 4\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m*\u{1b}[0m **\u{1b}[1mItem 5\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m*\u{1b}[0m **\u{1b}[1mItem 6\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m*\u{1b}[0m **\u{1b}[1mItem 7\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m*\u{1b}[0m **\u{1b}[1mItem 8\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m*\u{1b}[0m **\u{1b}[1mItem 9\u{1b}[0m** : description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m*\u{1b}[0m **\u{1b}[1mItem 10\u{1b}[0m**: description with \u{1b}[38;5;75m`code`\u{1b}[0m \u{1b}[38;5;15m*\u{1b}[0m **\u{1b}[1mItem 11\u{1b}[0m**: description with \u{1b}[38;5;75m`code`\u{1b}[0m ", output ); assert_eq!( "* **Item 1** : description with `code` * **Item 2** : description with `code` * **Item 3** : description with `code` * **Item 4** : description with `code` * **Item 5** : description with `code` * **Item 6** : description with `code` * **Item 7** : description with `code` * **Item 8** : description with `code` * **Item 9** : description with `code` * **Item 10**: description with `code` * **Item 11**: description with `code` ", console::strip_ansi_codes(&output) ); Ok(()) } fn cli_output(colorize: CliColorizeOpt) -> CliOutput<Vec<u8>> { CliOutputBuilder::new_with_writer(Vec::new()) .with_outcome_format(OutputFormat::Text) .with_colorize(colorize) .build() }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/cli/output/cli_progress_format_opt_parse_error.rs
workspace_tests/src/cli/output/cli_progress_format_opt_parse_error.rs
use peace::cli::output::CliProgressFormatOptParseError; #[test] fn display_includes_auto_output_pb_progress_bar() { let error = CliProgressFormatOptParseError("rara".to_string()); assert_eq!( "Failed to parse CLI progress format from string: `\"rara\"`.\n\ Valid values are [\"auto\", \"outcome\", \"pb\", \"progress_bar\", \"none\"]", format!("{error}") ); } #[test] fn clone() { let error = CliProgressFormatOptParseError("rara".to_string()); #[allow(clippy::redundant_clone)] // https://github.com/rust-lang/rust-clippy/issues/9011 let error_clone = error.clone(); assert_eq!(error, error_clone); } #[test] fn debug() { let error = CliProgressFormatOptParseError("rara".to_string()); assert_eq!( r#"CliProgressFormatOptParseError("rara")"#, format!("{error:?}") ); }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/cli/output/cli_colorize_opt_parse_error.rs
workspace_tests/src/cli/output/cli_colorize_opt_parse_error.rs
use peace::cli::output::CliColorizeOptParseError; #[test] fn display_includes_auto_always_never() { let error = CliColorizeOptParseError("rara".to_string()); assert_eq!( "Failed to parse CLI colorize from string: `\"rara\"`.\n\ Valid values are [\"auto\", \"always\", \"never\"]", format!("{error}") ); } #[test] fn clone() { let error = CliColorizeOptParseError("rara".to_string()); #[allow(clippy::redundant_clone)] // https://github.com/rust-lang/rust-clippy/issues/9011 let error_clone = error.clone(); assert_eq!(error, error_clone); } #[test] fn debug() { let error = CliColorizeOptParseError("rara".to_string()); assert_eq!(r#"CliColorizeOptParseError("rara")"#, format!("{error:?}")); }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/cli/output/cli_output_target.rs
workspace_tests/src/cli/output/cli_output_target.rs
use peace::cli::output::CliOutputTarget; #[test] fn clone() { let _cli_output_target = Clone::clone(&CliOutputTarget::Stderr); } #[test] fn debug() { assert_eq!("Stderr", format!("{:?}", CliOutputTarget::Stderr)); } #[test] fn partial_eq() { assert_eq!(CliOutputTarget::Stderr, CliOutputTarget::Stderr); assert_ne!(CliOutputTarget::Stdout, CliOutputTarget::Stderr); #[cfg(feature = "output_in_memory")] { use peace::rt_model::indicatif::TermLike; let mut term_0 = CliOutputTarget::in_memory(100, 20); let term_1 = CliOutputTarget::in_memory(100, 20); let term_2 = CliOutputTarget::in_memory(101, 20); assert_eq!(term_0, term_1); // Currently we define equality in terms of the contents, // and don't consider terminal width and height. assert_eq!(term_0, term_2); if let CliOutputTarget::InMemory(term_0) = &mut term_0 { term_0 .write_line("abc") .expect("Expected to write line to in-memory term."); } assert_ne!(term_0, term_1); } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/data/w_maybe.rs
workspace_tests/src/data/w_maybe.rs
use std::any::TypeId; use peace::{ data::{accessors::WMaybe, Data, DataAccess, DataAccessDyn, Resources, TypeIds}, item_model::{item_id, ItemId}, }; const ITEM_SPEC_ID_UNUSED: &ItemId = &item_id!("test_item_id"); #[test] fn data_borrow_returns_t_when_present() { let mut resources = Resources::new(); resources.insert(1u8); let maybe_mut = <WMaybe<'_, u8> as Data>::borrow(ITEM_SPEC_ID_UNUSED, &resources); assert_eq!(Some(1u8), maybe_mut.as_deref().copied()) } #[test] fn data_borrow_returns_none_when_absent() { let resources = Resources::new(); let maybe_mut = <WMaybe<'_, u8> as Data>::borrow(ITEM_SPEC_ID_UNUSED, &resources); assert_eq!(None, maybe_mut.as_deref().copied()) } #[test] fn data_access_borrows_returns_nothing() { let type_ids_actual = <WMaybe<'_, u8> as DataAccess>::borrows(); let type_ids_expected = TypeIds::new(); assert_eq!(type_ids_expected, type_ids_actual) } #[test] fn data_access_borrow_muts_returns_t() { let type_ids_actual = <WMaybe<'_, u8> as DataAccess>::borrow_muts(); let mut type_ids_expected = TypeIds::new(); type_ids_expected.push(TypeId::of::<u8>()); assert_eq!(type_ids_expected, type_ids_actual) } #[test] fn data_access_dyn_borrows_returns_nothing() { let type_ids_actual = <WMaybe<'_, u8> as DataAccessDyn>::borrows(&WMaybe::from(None)); let type_ids_expected = TypeIds::new(); assert_eq!(type_ids_expected, type_ids_actual) } #[test] fn data_access_dyn_borrow_muts_returns_t() { let type_ids_actual = <WMaybe<'_, u8> as DataAccessDyn>::borrow_muts(&WMaybe::from(None)); let mut type_ids_expected = TypeIds::new(); type_ids_expected.push(TypeId::of::<u8>()); assert_eq!(type_ids_expected, type_ids_actual) } #[test] fn debug() { let mut resources = Resources::new(); resources.insert(1u8); let maybe_mut = <WMaybe<'_, u8> as Data>::borrow(ITEM_SPEC_ID_UNUSED, &resources); assert_eq!( r#"WMaybe(Some(RefMut { inner: 1 }))"#, format!("{maybe_mut:?}") ) } #[test] fn partial_eq() { let mut resources = Resources::new(); resources.insert(1u8); let maybe_mut_0 = <WMaybe<'_, u8> as Data>::borrow(ITEM_SPEC_ID_UNUSED, &resources); let mut resources = Resources::new(); resources.insert(1u8); let maybe_mut_1 = <WMaybe<'_, u8> as Data>::borrow(ITEM_SPEC_ID_UNUSED, &resources); assert_eq!(maybe_mut_0, maybe_mut_1) }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/data/r_maybe.rs
workspace_tests/src/data/r_maybe.rs
use std::any::TypeId; use peace::{ data::{accessors::RMaybe, Data, DataAccess, DataAccessDyn, Resources, TypeIds}, item_model::{item_id, ItemId}, }; const ITEM_SPEC_ID_UNUSED: &ItemId = &item_id!("test_item_id"); #[test] fn data_borrow_returns_t_when_present() { let mut resources = Resources::new(); resources.insert(1u8); let maybe = <RMaybe<'_, u8> as Data>::borrow(ITEM_SPEC_ID_UNUSED, &resources); assert_eq!(Some(1u8), maybe.as_deref().copied()) } #[test] fn data_borrow_returns_none_when_absent() { let resources = Resources::new(); let maybe = <RMaybe<'_, u8> as Data>::borrow(ITEM_SPEC_ID_UNUSED, &resources); assert_eq!(None, maybe.as_deref().copied()) } #[test] fn data_access_borrows_returns_t() { let type_ids_actual = <RMaybe<'_, u8> as DataAccess>::borrows(); let mut type_ids_expected = TypeIds::new(); type_ids_expected.push(TypeId::of::<u8>()); assert_eq!(type_ids_expected, type_ids_actual) } #[test] fn data_access_borrow_muts_returns_nothing() { let type_ids_actual = <RMaybe<'_, u8> as DataAccess>::borrow_muts(); let type_ids_expected = TypeIds::new(); assert_eq!(type_ids_expected, type_ids_actual) } #[test] fn data_access_dyn_borrows_returns_t() { let type_ids_actual = <RMaybe<'_, u8> as DataAccessDyn>::borrows(&RMaybe::from(None)); let mut type_ids_expected = TypeIds::new(); type_ids_expected.push(TypeId::of::<u8>()); assert_eq!(type_ids_expected, type_ids_actual) } #[test] fn data_access_dyn_borrow_muts_returns_t() { let type_ids_actual = <RMaybe<'_, u8> as DataAccessDyn>::borrow_muts(&RMaybe::from(None)); let type_ids_expected = TypeIds::new(); assert_eq!(type_ids_expected, type_ids_actual) } #[test] fn clone() { let mut resources = Resources::new(); resources.insert(1u8); let maybe = <RMaybe<'_, u8> as Data>::borrow(ITEM_SPEC_ID_UNUSED, &resources); let maybe_clone = maybe.clone(); assert_eq!(maybe, maybe_clone) } #[test] fn debug() { let mut resources = Resources::new(); resources.insert(1u8); let maybe = <RMaybe<'_, u8> as Data>::borrow(ITEM_SPEC_ID_UNUSED, &resources); assert_eq!(r#"RMaybe(Some(Ref { inner: 1 }))"#, format!("{maybe:?}")) }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/data/derive.rs
workspace_tests/src/data/derive.rs
use std::{any::TypeId, marker::PhantomData}; use peace::data::{ accessors::{R, W}, Data, DataAccess, TypeIds, }; #[test] fn data_named_fields_borrows() { let mut type_ids_expected = TypeIds::new(); type_ids_expected.push(TypeId::of::<A>()); type_ids_expected.push(TypeId::of::<B>()); let type_ids_actual = <DataNamedFields<'_> as DataAccess>::borrows(); assert_eq!(type_ids_expected, type_ids_actual); } #[test] fn data_unnamed_fields_borrows() { let mut type_ids_expected = TypeIds::new(); type_ids_expected.push(TypeId::of::<A>()); type_ids_expected.push(TypeId::of::<B>()); let type_ids_actual = <DataUnnamedFields<'_> as DataAccess>::borrows(); assert_eq!(type_ids_expected, type_ids_actual); } #[test] fn data_mix_fields_borrows() { let mut type_ids_expected = TypeIds::new(); type_ids_expected.push(TypeId::of::<A>()); let type_ids_actual = <DataMixFields<'_> as DataAccess>::borrows(); assert_eq!(type_ids_expected, type_ids_actual); } #[test] fn r_borrows() { let mut type_ids_expected = TypeIds::new(); type_ids_expected.push(TypeId::of::<A>()); let type_ids_actual = <R<'_, A> as DataAccess>::borrows(); assert_eq!(type_ids_expected, type_ids_actual); } #[test] fn w_borrows() { let type_ids_expected = TypeIds::new(); let type_ids_actual = <W<'_, A> as DataAccess>::borrows(); assert_eq!(type_ids_expected, type_ids_actual); } #[test] fn data_named_fields_borrow_muts() { let type_ids_expected = TypeIds::new(); let type_ids_actual = <DataNamedFields<'_> as DataAccess>::borrow_muts(); assert_eq!(type_ids_expected, type_ids_actual); } #[test] fn data_unnamed_fields_borrow_muts() { let type_ids_expected = TypeIds::new(); let type_ids_actual = <DataUnnamedFields<'_> as DataAccess>::borrow_muts(); assert_eq!(type_ids_expected, type_ids_actual); } #[test] fn data_mut_fields_borrow_muts() { let mut type_ids_expected = TypeIds::new(); type_ids_expected.push(TypeId::of::<A>()); type_ids_expected.push(TypeId::of::<B>()); let type_ids_actual = <DataMutFields<'_> as DataAccess>::borrow_muts(); assert_eq!(type_ids_expected, type_ids_actual); } #[test] fn data_mix_fields_borrow_muts() { let mut type_ids_expected = TypeIds::new(); type_ids_expected.push(TypeId::of::<B>()); let type_ids_actual = <DataMixFields<'_> as DataAccess>::borrow_muts(); assert_eq!(type_ids_expected, type_ids_actual); } #[test] fn r_borrow_muts() { let type_ids_expected = TypeIds::new(); let type_ids_actual = <R<'_, A> as DataAccess>::borrow_muts(); assert_eq!(type_ids_expected, type_ids_actual); } #[test] fn w_borrow_muts() { let mut type_ids_expected = TypeIds::new(); type_ids_expected.push(TypeId::of::<A>()); let type_ids_actual = <W<'_, A> as DataAccess>::borrow_muts(); assert_eq!(type_ids_expected, type_ids_actual); } #[derive(Debug, Data)] struct DataNamedFields<'exec> { a_imm: R<'exec, A>, b_imm: R<'exec, B>, } #[derive(Debug, Data)] struct DataUnnamedFields<'exec>(R<'exec, A>, R<'exec, B>); #[derive(Debug, Data)] struct DataMutFields<'exec> { a_mut: W<'exec, A>, b_mut: W<'exec, B>, } #[derive(Debug, Data)] struct DataMixFields<'exec> { a_imm: R<'exec, A>, phantom_0: PhantomData<()>, b_mut: W<'exec, B>, phantom_1: PhantomData<()>, } #[derive(Clone, Copy, Debug, PartialEq)] struct A(u32); #[derive(Clone, Copy, Debug, PartialEq)] struct B(u32);
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/data/marker.rs
workspace_tests/src/data/marker.rs
use peace::data::marker::{ApplyDry, Clean, Current, Goal}; #[test] fn debug() { assert_eq!("ApplyDry(Some(1))", format!("{:?}", ApplyDry(Some(1u8)))); assert_eq!("Clean(Some(1))", format!("{:?}", Clean(Some(1u8)))); assert_eq!("Current(Some(1))", format!("{:?}", Current(Some(1u8)))); assert_eq!("Goal(Some(1))", format!("{:?}", Goal(Some(1u8)))); }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/peace_cmd_ctx_types/test_cct_fn_tracker_output.rs
workspace_tests/src/peace_cmd_ctx_types/test_cct_fn_tracker_output.rs
use peace::cmd_ctx::CmdCtxTypes; use crate::{FnTrackerOutput, PeaceTestError}; #[derive(Debug)] pub struct TestCctFnTrackerOutput; impl CmdCtxTypes for TestCctFnTrackerOutput { type AppError = PeaceTestError; type FlowParamsKey = (); type MappingFns = (); type Output = FnTrackerOutput; type ProfileParamsKey = (); type WorkspaceParamsKey = (); }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/peace_cmd_ctx_types/test_cct_no_op_output.rs
workspace_tests/src/peace_cmd_ctx_types/test_cct_no_op_output.rs
use peace::cmd_ctx::CmdCtxTypes; use crate::{NoOpOutput, PeaceTestError}; #[derive(Debug)] pub struct TestCctNoOpOutput; impl CmdCtxTypes for TestCctNoOpOutput { type AppError = PeaceTestError; type FlowParamsKey = (); type MappingFns = (); type Output = NoOpOutput; type ProfileParamsKey = (); type WorkspaceParamsKey = (); }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/item_interaction_model/item_interaction.rs
workspace_tests/src/item_interaction_model/item_interaction.rs
use peace::item_interaction_model::{ ItemInteraction, ItemInteractionPull, ItemInteractionPush, ItemInteractionWithin, ItemLocation, }; mod item_interaction_pull; mod item_interaction_push; mod item_interaction_within; #[test] fn from_item_interaction_push() { let item_interaction_push = ItemInteractionPush::new( vec![ItemLocation::localhost()].into(), vec![ItemLocation::host("server".to_string())].into(), ); let item_interaction = ItemInteraction::from(item_interaction_push.clone()); assert_eq!( ItemInteraction::Push(item_interaction_push), item_interaction ); } #[test] fn from_item_interaction_pull() { let item_interaction_pull = ItemInteractionPull::new( vec![ItemLocation::localhost()].into(), vec![ItemLocation::host("server".to_string())].into(), ); let item_interaction = ItemInteraction::from(item_interaction_pull.clone()); assert_eq!( ItemInteraction::Pull(item_interaction_pull), item_interaction ); } #[test] fn from_item_interaction_within() { let item_interaction_within = ItemInteractionWithin::new(vec![ItemLocation::localhost()].into()); let item_interaction = ItemInteraction::from(item_interaction_within.clone()); assert_eq!( ItemInteraction::Within(item_interaction_within), item_interaction ); }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/item_interaction_model/item_location.rs
workspace_tests/src/item_interaction_model/item_location.rs
use std::{ffi::OsStr, path::Path}; use peace::item_interaction_model::{url::ParseError, ItemLocation, ItemLocationType, Url}; #[test] fn group() { let item_location = ItemLocation::group("Cloud".to_string()); assert_eq!( ItemLocation::new( peace::item_interaction_model::ItemLocationType::Group, "Cloud".to_string(), ), item_location ); } #[test] fn host() { let item_location = ItemLocation::host("Server".to_string()); assert_eq!( ItemLocation::new( peace::item_interaction_model::ItemLocationType::Host, "Server".to_string(), ), item_location ); } #[test] fn host_unknown() { let item_location = ItemLocation::host_unknown(); assert_eq!( ItemLocation::new( peace::item_interaction_model::ItemLocationType::Host, ItemLocation::HOST_UNKNOWN.to_string(), ), item_location ); } #[test] fn host_from_url_https() -> Result<(), ParseError> { let item_location = ItemLocation::host_from_url(&Url::parse("https://example.com/resource")?); assert_eq!( ItemLocation::new( peace::item_interaction_model::ItemLocationType::Host, "🌐 example.com".to_string(), ), item_location ); Ok(()) } #[test] fn host_from_url_file() -> Result<(), ParseError> { let item_location = ItemLocation::host_from_url(&Url::parse("file:///path/to/resource")?); assert_eq!( ItemLocation::new( peace::item_interaction_model::ItemLocationType::Host, ItemLocation::LOCALHOST.to_string(), ), item_location ); Ok(()) } #[test] fn localhost() { let item_location = ItemLocation::localhost(); assert_eq!( ItemLocation::new( peace::item_interaction_model::ItemLocationType::Host, ItemLocation::LOCALHOST.to_string(), ), item_location ); } #[test] fn path() { let item_location = ItemLocation::path("/path/to/resource".to_string()); assert_eq!( ItemLocation::new( peace::item_interaction_model::ItemLocationType::Path, "/path/to/resource".to_string(), ), item_location ); } #[test] fn path_lossy() { let path = unsafe { Path::new(OsStr::from_encoded_bytes_unchecked( b"/path/to/lossy_fo\xF0\x90\x80.txt", )) }; let item_location = ItemLocation::path_lossy(path); assert_eq!( ItemLocation::new( peace::item_interaction_model::ItemLocationType::Path, "/path/to/lossy_fo�.txt".to_string(), ), item_location ); } #[test] fn name() { let item_location = ItemLocation::path("/path/to/resource".to_string()); assert_eq!("/path/to/resource", item_location.name()); } #[test] fn r#type() { let item_location = ItemLocation::path("/path/to/resource".to_string()); assert_eq!(ItemLocationType::Path, item_location.r#type()); }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/item_interaction_model/item_interaction/item_interaction_pull.rs
workspace_tests/src/item_interaction_model/item_interaction/item_interaction_pull.rs
use peace::item_interaction_model::{ItemInteractionPull, ItemLocation}; #[test] fn location_client() { let item_interaction_pull = ItemInteractionPull::new( vec![ItemLocation::localhost()].into(), vec![ItemLocation::host("server".to_string())].into(), ); assert_eq!( vec![ItemLocation::localhost()], item_interaction_pull.location_client() ); } #[test] fn location_server() { let item_interaction_pull = ItemInteractionPull::new( vec![ItemLocation::localhost()].into(), vec![ItemLocation::host("server".to_string())].into(), ); assert_eq!( vec![ItemLocation::host("server".to_string())], item_interaction_pull.location_server() ); }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/item_interaction_model/item_interaction/item_interaction_within.rs
workspace_tests/src/item_interaction_model/item_interaction/item_interaction_within.rs
use peace::item_interaction_model::{ItemInteractionWithin, ItemLocation}; #[test] fn location() { let item_interaction_within = ItemInteractionWithin::new(vec![ItemLocation::localhost()].into()); assert_eq!( vec![ItemLocation::localhost()], item_interaction_within.location() ); }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/item_interaction_model/item_interaction/item_interaction_push.rs
workspace_tests/src/item_interaction_model/item_interaction/item_interaction_push.rs
use peace::item_interaction_model::{ItemInteractionPush, ItemLocation}; #[test] fn location_from() { let item_interaction_push = ItemInteractionPush::new( vec![ItemLocation::localhost()].into(), vec![ItemLocation::host("server".to_string())].into(), ); assert_eq!( vec![ItemLocation::localhost()], item_interaction_push.location_from() ); } #[test] fn location_to() { let item_interaction_push = ItemInteractionPush::new( vec![ItemLocation::localhost()].into(), vec![ItemLocation::host("server".to_string())].into(), ); assert_eq!( vec![ItemLocation::host("server".to_string())], item_interaction_push.location_to() ); }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/item_model/item_id.rs
workspace_tests/src/item_model/item_id.rs
use std::{borrow::Cow, str::FromStr}; use peace::{ fmt::Presentable, item_model::{ItemId, ItemIdInvalidFmt}, }; use crate::{FnInvocation, FnTrackerPresenter}; #[test] fn from_str_returns_ok_owned_for_valid_id() -> Result<(), ItemIdInvalidFmt<'static>> { let item_id = ItemId::from_str("good_id")?; assert_eq!("good_id", *item_id); Ok(()) } #[test] fn underscore_is_valid_first_character() -> Result<(), ItemIdInvalidFmt<'static>> { let item_id = ItemId::new("_good_id")?; assert_eq!("_good_id", *item_id); Ok(()) } #[test] fn new_unchecked_does_not_validate_id() -> Result<(), ItemIdInvalidFmt<'static>> { let item_id = ItemId::new_unchecked("!valid"); assert_eq!("!valid", *item_id); Ok(()) } #[test] fn try_from_str_returns_ok_borrowed_for_valid_id() -> Result<(), ItemIdInvalidFmt<'static>> { let item_id = ItemId::try_from("good_id")?; assert_eq!("good_id", *item_id); Ok(()) } #[test] fn try_from_string_returns_ok_owned_for_valid_id() -> Result<(), ItemIdInvalidFmt<'static>> { let item_id = ItemId::try_from(String::from("good_id"))?; assert_eq!("good_id", *item_id); Ok(()) } #[test] fn from_str_returns_err_owned_for_invalid_id() { let error = ItemId::from_str("has space").unwrap_err(); assert!(matches!(error.value(), Cow::Owned(_))); assert_eq!("has space", error.value()); } #[test] fn try_from_str_returns_err_borrowed_for_invalid_id() { let error = ItemId::try_from("has space").unwrap_err(); assert!(matches!(error.value(), Cow::Borrowed(_))); assert_eq!("has space", error.value()); } #[test] fn try_from_string_returns_err_owned_for_invalid_id() { let error = ItemId::try_from(String::from("has space")).unwrap_err(); assert!(matches!(error.value(), Cow::Owned(_))); assert_eq!("has space", error.value()); } #[test] fn display_returns_inner_str() -> Result<(), ItemIdInvalidFmt<'static>> { let item_id = ItemId::try_from("good_id")?; assert_eq!("good_id", item_id.to_string()); Ok(()) } #[tokio::test] async fn present_uses_code_inline() -> Result<(), Box<dyn std::error::Error>> { let mut presenter = FnTrackerPresenter::new(); let item_id = ItemId::try_from("item_id")?; item_id.present(&mut presenter).await?; assert_eq!( vec![FnInvocation::new( "code_inline", vec![Some(r#""item_id""#.to_string())] )], presenter.fn_invocations() ); Ok(()) } #[test] fn clone() -> Result<(), ItemIdInvalidFmt<'static>> { let item_id_0 = ItemId::new("id")?; #[allow(clippy::redundant_clone)] // https://github.com/rust-lang/rust-clippy/issues/9011 let item_id_1 = item_id_0.clone(); assert_eq!(item_id_0, item_id_1); Ok(()) } #[test] fn debug() -> Result<(), ItemIdInvalidFmt<'static>> { let item_id = ItemId::new("id")?; assert_eq!(r#"ItemId("id")"#, format!("{item_id:?}")); Ok(()) } #[test] fn partial_eq_ne() -> Result<(), ItemIdInvalidFmt<'static>> { let item_id_0 = ItemId::new("id0")?; let item_id_1 = ItemId::new("id1")?; assert!(item_id_0 != item_id_1); Ok(()) }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/item_model/item_id_invalid_fmt.rs
workspace_tests/src/item_model/item_id_invalid_fmt.rs
use std::borrow::Cow; use peace::item_model::ItemIdInvalidFmt; #[test] fn debug() { let item_id_invalid_fmt = ItemIdInvalidFmt::new(Cow::Borrowed("invalid id")); assert_eq!( r#"ItemIdInvalidFmt { value: "invalid id" }"#, format!("{item_id_invalid_fmt:?}") ); } #[test] fn display() { let item_id_invalid_fmt = ItemIdInvalidFmt::new(Cow::Borrowed("invalid id")); assert_eq!( "`invalid id` is not a valid `ItemId`.\n\ `ItemId`s must begin with a letter or underscore, and contain only letters, numbers, or underscores.", format!("{item_id_invalid_fmt}") ); }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/src/lib.rs
src/lib.rs
//! 🕊️ peace -- zero stress automation // Re-exports so consumers don't need to depend on crates individually. pub use enum_iterator; #[cfg(feature = "error_reporting")] pub use miette; pub use peace_cfg as cfg; #[cfg(feature = "cli")] pub use peace_cli as cli; #[cfg(feature = "cli")] pub use peace_cli_model as cli_model; pub use peace_cmd_ctx as cmd_ctx; pub use peace_cmd_model as cmd_model; pub use peace_cmd_rt as cmd_rt; pub use peace_data as data; pub use peace_diff as diff; pub use peace_flow_model as flow_model; pub use peace_flow_rt as flow_rt; pub use peace_fmt as fmt; #[cfg(feature = "item_interactions")] pub use peace_item_interaction_model as item_interaction_model; pub use peace_item_model as item_model; pub use peace_params as params; pub use peace_profile_model as profile_model; #[cfg(feature = "output_progress")] pub use peace_progress_model as progress_model; pub use peace_resource_rt as resource_rt; pub use peace_rt as rt; pub use peace_rt_model as rt_model; pub use peace_state_rt as state_rt; #[cfg(feature = "webi")] pub use peace_webi as webi; #[cfg(feature = "webi")] pub use peace_webi_components as webi_components; #[cfg(feature = "webi")] pub use peace_webi_model as webi_model; // We still can't build with `--all-features`, even with `indicatif 0.17.4`. // // The error we get is the same as in // <https://github.com/rustwasm/wasm-bindgen/issues/2160>. // // This likely means at least one of the transitive dependencies of `indicatif` // uses `std::env::*`. // // `console` is at lesat one of these dependencies. #[cfg(all(target_arch = "wasm32", feature = "output_progress"))] compile_error!( r#"The `"output_progress"` feature does not work on WASM, pending support from `indicatif`. See <https://github.com/console-rs/indicatif/issues/513>."# );
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/lib.rs
examples/envman/src/lib.rs
//! Peace framework web application lifecycle example //! //! This example demonstrates management of a web application's lifecycle. This //! includes: //! //! 1. Building the application. //! 2. Starting / stopping the application in development. //! 3. Deploying / upgrading / removing the application in test servers. //! 4. Configuration management of the application. //! 5. Deploying / upgrading / removing the application in live servers. //! 6. Diffing the application and configuration across environments. //! 7. Creating a replica environment from an existing environment. //! //! Example commands: //! //! ```bash //! ## Initialize different deployment environments //! ## Local development //! envman init dev --type development azriel91/web_app 0.1.1 //! //! ## AWS -- defaults to reading ~/.aws/credentials //! envman init demo --type production azriel91/web_app 0.1.1 //! //! ## Shows current environment //! envman profile //! //! envman switch dev //! envman status //! envman goal //! envman diff //! envman deploy //! ## make config changes on server / locally //! envman discover //! envman diff //! envman deploy # ensure compliance //! envman diff //! envman clean //! //! envman switch demo //! envman status //! envman goal //! envman deploy //! envman clean //! //! ## `diff` defaults to current profile, current and goal state. //! ## But we can tell it to diff between different profiles' current states. //! envman diff dev demo //! ``` cfg_if::cfg_if! { if #[cfg(feature = "flow_logic")] { pub mod cmds; pub mod flows; pub mod items; pub mod model; pub mod output; pub mod rt_model; } } cfg_if::cfg_if! { if #[cfg(feature = "hydrate")] { use wasm_bindgen::prelude::wasm_bindgen; use leptos::prelude::view; use peace::webi_components::{App, ChildrenFn}; #[wasm_bindgen] pub async fn hydrate() { use crate::web_components::EnvDeployHome; // initializes logging using the `log` crate let _log = console_log::init_with_level(log::Level::Debug); console_error_panic_hook::set_once(); let app_home = ChildrenFn::new(EnvDeployHome); leptos::mount::hydrate_body(move || { view! { <App app_home /> } }); } } } #[cfg(any(feature = "web_server", feature = "hydrate"))] pub mod web_components;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/web_components.rs
examples/envman/src/web_components.rs
#![allow(non_snake_case)] // Components are all PascalCase. pub use self::{ cmd_exec_request::CmdExecRequest, env_deploy_home::EnvDeployHome, tab_label::TabLabel, }; mod cmd_exec_request; mod env_deploy_home; mod tab_label;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items.rs
examples/envman/src/items.rs
//! Umbrella module for items. pub mod peace_aws_iam_policy; pub mod peace_aws_iam_role; pub mod peace_aws_instance_profile; pub mod peace_aws_s3_bucket; pub mod peace_aws_s3_object; // Hack: need to find a better way to do this. #[cfg(feature = "error_reporting")] macro_rules! aws_error_desc { ($error:expr) => {{ use aws_sdk_iam::error::ProvideErrorMetadata; let (error_code, desc) = match $error { aws_sdk_iam::error::SdkError::ServiceError(service_error) => { let error_code = service_error.err().code().map(|s| s.to_string()); let desc = service_error.err().message().map(|s| s.to_string()); (error_code, desc) } _ => { // most variants do not `impl Error`, but we can // access the underlying error through // `sdk_error.source()`. let mut source = Option::<&dyn std::error::Error>::Some($error); while let Some(source_next) = source.and_then(std::error::Error::source) { source = Some(source_next); } let error_code = None; let desc = source.map(|source| format!("{source}")); (error_code, desc) } }; let mut aws_desc = String::new(); let mut desc_span_start = 0; let mut desc_len = 0; if let Some(error_code) = error_code { aws_desc.push_str(&format!("{error_code}: ")); desc_span_start = aws_desc.len(); } if let Some(desc) = desc { aws_desc.push_str(&desc); desc_len = desc.len(); } let aws_desc_span = peace::miette::SourceSpan::from((desc_span_start, desc_len)); (aws_desc, aws_desc_span) }}; } #[cfg(feature = "error_reporting")] pub(crate) use aws_error_desc;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/flows.rs
examples/envman/src/flows.rs
//! Flows that users can invoke. pub use self::{ app_upload_flow::{AppUploadFlow, AppUploadFlowParamsSpecs}, env_deploy_flow::{EnvDeployFlow, EnvDeployFlowParamsSpecs}, envman_mapping_fns::EnvmanMappingFns, }; mod app_upload_flow; mod env_deploy_flow; mod envman_mapping_fns;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/model.rs
examples/envman/src/model.rs
//! Data structures pub use self::{ env_diff_selection::EnvDiffSelection, env_man_flow::EnvManFlow, env_man_flow_parse_error::EnvManFlowParseError, env_type::EnvType, env_type_parse_error::EnvTypeParseError, envman_error::EnvManError, item_ids::WebApp, params_keys::{ProfileParamsKey, WorkspaceParamsKey}, profile_switch::ProfileSwitch, repo_slug::RepoSlug, repo_slug_error::RepoSlugError, }; #[cfg(feature = "cli")] pub mod cli_args; mod env_diff_selection; mod env_man_flow; mod env_man_flow_parse_error; mod env_type; mod env_type_parse_error; mod envman_error; mod item_ids; mod params_keys; mod profile_switch; mod repo_slug; mod repo_slug_error;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/main_cli.rs
examples/envman/src/main_cli.rs
use std::net::SocketAddr; use clap::Parser; use envman::{ cmds::{ CmdOpts, EnvCleanCmd, EnvDeployCmd, EnvDiffCmd, EnvDiscoverCmd, EnvGoalCmd, EnvStatusCmd, ProfileInitCmd, ProfileListCmd, ProfileShowCmd, ProfileSwitchCmd, }, model::{ cli_args::{CliArgs, EnvManCommand, ProfileCommand}, EnvDiffSelection, EnvManError, ProfileSwitch, }, }; use peace::cli::output::CliOutput; use tokio::io::Stdout; pub fn run() -> Result<(), EnvManError> { let CliArgs { command, fast, format, color, debug, } = CliArgs::parse(); let runtime = if fast { tokio::runtime::Builder::new_multi_thread() } else { tokio::runtime::Builder::new_current_thread() } .thread_name("main") .thread_stack_size(3 * 1024 * 1024) .enable_io() .enable_time() .build() .map_err(EnvManError::TokioRuntimeInit)?; runtime.block_on(async { let mut cli_output = { let mut builder = CliOutput::builder().with_colorize(color); if let Some(format) = format { builder = builder.with_outcome_format(format); #[cfg(feature = "output_progress")] { use peace::cli::output::CliProgressFormatOpt; builder = builder.with_progress_format(CliProgressFormatOpt::Outcome); } } builder.build() }; match run_command(&mut cli_output, command, debug).await { Ok(()) => Ok(()), Err(error) => envman::output::errors_present(&mut cli_output, &[error]).await, } }) } async fn run_command( cli_output: &mut CliOutput<Stdout>, command: EnvManCommand, debug: bool, ) -> Result<(), EnvManError> { match command { EnvManCommand::Init { profile, flow, r#type, slug, version, url, } => { ProfileInitCmd::run( cli_output, profile, flow, r#type, &slug, &version, url, true, ) .await?; } EnvManCommand::Profile { command } => { let command = command.unwrap_or(ProfileCommand::Show); match command { ProfileCommand::List => ProfileListCmd::run(cli_output).await?, ProfileCommand::Show => ProfileShowCmd::run(cli_output).await?, } } EnvManCommand::Switch { profile, create, r#type, slug, version, url, } => { let profile_switch = if create { let Some(((env_type, slug), version)) = r#type.zip(slug).zip(version) else { unreachable!( "`clap` should ensure `env_type`, `slug`, and `version` are \ `Some` when `create` is `true`." ); }; ProfileSwitch::CreateNew { profile, env_type, slug, version, url, } } else { ProfileSwitch::ToExisting { profile } }; ProfileSwitchCmd::run(cli_output, profile_switch).await? } EnvManCommand::Discover => EnvDiscoverCmd::run(cli_output, debug).await?, EnvManCommand::Status => EnvStatusCmd::run(cli_output).await?, EnvManCommand::Goal => EnvGoalCmd::run(cli_output).await?, EnvManCommand::Diff { profile_a, profile_b, } => { let env_diff_selection = profile_a .zip(profile_b) .map( |(profile_a, profile_b)| EnvDiffSelection::DiffProfilesCurrent { profile_a, profile_b, }, ) .unwrap_or(EnvDiffSelection::CurrentAndGoal); EnvDiffCmd::run(cli_output, env_diff_selection).await? } EnvManCommand::Deploy => EnvDeployCmd::run(cli_output, debug).await?, EnvManCommand::Clean => EnvCleanCmd::run(cli_output, debug).await?, #[cfg(feature = "web_server")] EnvManCommand::Web { address, port } => { use futures::FutureExt; use peace::{ cmd_ctx::CmdCtxSpsfFields, cmd_model::CmdOutcome, webi::output::{CmdExecSpawnCtx, FlowWebiFns, WebiServer}, webi_components::ChildrenFn, }; use envman::{ cmds::EnvCmd, flows::EnvDeployFlow, web_components::{CmdExecRequest, EnvDeployHome}, }; let flow = EnvDeployFlow::flow() .await .expect("Failed to instantiate EnvDeployFlow."); let flow_webi_fns = FlowWebiFns { flow: flow.clone(), outcome_info_graph_fn: Box::new(|webi_output, outcome_info_graph_gen| { async move { let cmd_ctx = EnvCmd::cmd_ctx(webi_output) .await .expect("Expected CmdCtx to be successfully constructed."); // TODO: consolidate the `flow` above with this? let CmdCtxSpsfFields { flow, params_specs, mapping_fn_reg, resources, .. } = cmd_ctx.fields(); outcome_info_graph_gen(flow, params_specs, mapping_fn_reg, resources) } .boxed_local() }), cmd_exec_spawn_fn: Box::new(|mut webi_output, cmd_exec_request| { use peace::rt::cmds::{ ApplyStoredStateSync, CleanCmd, EnsureCmd, StatesDiscoverCmd, }; let cmd_exec_task = async move { let mut cli_output = CliOutput::builder().build(); let cli_output = &mut cli_output; let (cmd_error, item_errors) = match cmd_exec_request { CmdExecRequest::Discover => { eprintln!("Running discover."); let result = EnvCmd::run(&mut webi_output, CmdOpts::default(), |cmd_ctx| { async { StatesDiscoverCmd::current_and_goal(cmd_ctx).await } .boxed_local() }) .await; match result { Ok(cmd_outcome) => { if let CmdOutcome::ItemError { errors, .. } = cmd_outcome { (None, Some(errors)) } else { (None, None) } } Err(error) => (Some(error), None), } } CmdExecRequest::Ensure => { eprintln!("Running ensure."); let result = EnvCmd::run(&mut webi_output, CmdOpts::default(), |cmd_ctx| { async { EnsureCmd::exec_with( cmd_ctx, ApplyStoredStateSync::Current, ) .await } .boxed_local() }) .await; match result { Ok(cmd_outcome) => { if let CmdOutcome::ItemError { errors, .. } = cmd_outcome { (None, Some(errors)) } else { (None, None) } } Err(error) => (Some(error), None), } } CmdExecRequest::Clean => { eprintln!("Running clean."); let result = EnvCmd::run(&mut webi_output, CmdOpts::default(), |cmd_ctx| { async { CleanCmd::exec_with( cmd_ctx, ApplyStoredStateSync::Current, ) .await } .boxed_local() }) .await; match result { Ok(cmd_outcome) => { if let CmdOutcome::ItemError { errors, .. } = cmd_outcome { (None, Some(errors)) } else { (None, None) } } Err(error) => (Some(error), None), } } }; if let Some(cmd_error) = cmd_error { let _ = envman::output::errors_present(cli_output, &[cmd_error]).await; } if let Some(item_errors) = item_errors.as_ref() { let _ = envman::output::item_errors_present(cli_output, item_errors).await; } } .boxed_local(); CmdExecSpawnCtx { interrupt_tx: None, cmd_exec_task, } }), }; WebiServer::start( env!("CARGO_CRATE_NAME").to_string(), Some(SocketAddr::from((address, port))), ChildrenFn::new(EnvDeployHome), flow_webi_fns, ) .await?; } } Ok::<_, EnvManError>(()) }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/main.rs
examples/envman/src/main.rs
cfg_if::cfg_if! { if #[cfg(feature = "cli")] { // CLI app use envman::model::EnvManError; mod main_cli; #[cfg(not(feature = "error_reporting"))] pub fn main() -> Result<(), EnvManError> { main_cli::run() } #[cfg(feature = "error_reporting")] pub fn main() -> peace::miette::Result<(), peace::miette::Report> { // Important to return `peace::miette::Report` instead of calling // `IntoDiagnostic::intoDiagnostic` on the `Error`, as that does not present the // diagnostic contextual information to the user. // // See <https://docs.rs/miette/latest/miette/trait.IntoDiagnostic.html#warning>. // The explicit mapping for `PeaceRtError` appears to be necessary to display // the diagnostic information. i.e. `miette` does not automatically delegate to // the #[diagnostic_source]. // // This is fixed by <https://github.com/zkat/miette/pull/170>. main_cli::run().map_err(|envman_error| match envman_error { EnvManError::PeaceItemFileDownload(err) => peace::miette::Report::from(err), EnvManError::PeaceRtError(err) => peace::miette::Report::from(err), other => peace::miette::Report::from(other), }) } } else if #[cfg(feature = "ssr")] { // web server use envman::model::EnvManError; #[cfg(not(feature = "error_reporting"))] pub fn main() -> Result<(), EnvManError> { use envman::flows::EnvDeployFlow; use peace::webi::output::WebiOutput; let runtime = tokio::runtime::Builder::new_multi_thread() .thread_name("main") .thread_stack_size(3 * 1024 * 1024) .enable_io() .enable_time() .build() .map_err(EnvManError::TokioRuntimeInit)?; runtime.block_on(async move { let flow = EnvDeployFlow::flow().await?; let flow_spec_info = flow.flow_spec_info(); let webi_output = WebiOutput::new(None, flow_spec_info); webi_output.start().await.map_err(EnvManError::from) }) } #[cfg(feature = "error_reporting")] pub fn main() -> peace::miette::Result<(), peace::miette::Report> { // Important to return `peace::miette::Report` instead of calling // `IntoDiagnostic::intoDiagnostic` on the `Error`, as that does not present the // diagnostic contextual information to the user. // // See <https://docs.rs/miette/latest/miette/trait.IntoDiagnostic.html#warning>. // The explicit mapping for `PeaceRtError` appears to be necessary to display // the diagnostic information. i.e. `miette` does not automatically delegate to // the #[diagnostic_source]. // // This is fixed by <https://github.com/zkat/miette/pull/170>. let runtime = tokio::runtime::Builder::new_multi_thread() .thread_name("main") .thread_stack_size(3 * 1024 * 1024) .enable_io() .enable_time() .build() .map_err(EnvManError::TokioRuntimeInit)?; let webi_output = WebiOutput::new(None); runtime .block_on(async move { webi_output.start().await.map_err(EnvManError::from) }) .map_err(peace::miette::Report::from) } } else if #[cfg(feature = "csr")] { // web client logic fn main() {} } else { compile_error!( r#"Please enable one of the following features: * "cli" * "ssr" * "csr" "#); } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/cmds.rs
examples/envman/src/cmds.rs
//! User facing commands. //! //! These should be callable from different endpoints, e.g. CLI, or WASM. //! Each endpoint is responsible for receiving the parameters from the user. //! //! The `*Cmd` types map between the parameters received from users, to each //! `Item`'s params type. pub use self::{ app_upload_cmd::AppUploadCmd, cmd_ctx_builder::interruptibility_augment, cmd_opts::CmdOpts, env_clean_cmd::EnvCleanCmd, env_cmd::EnvCmd, env_deploy_cmd::EnvDeployCmd, env_diff_cmd::EnvDiffCmd, env_discover_cmd::EnvDiscoverCmd, env_goal_cmd::EnvGoalCmd, env_status_cmd::EnvStatusCmd, profile_init_cmd::ProfileInitCmd, profile_list_cmd::ProfileListCmd, profile_show_cmd::ProfileShowCmd, profile_switch_cmd::ProfileSwitchCmd, }; mod app_upload_cmd; mod cmd_ctx_builder; mod cmd_opts; mod env_clean_cmd; mod env_cmd; mod env_deploy_cmd; mod env_diff_cmd; mod env_discover_cmd; mod env_goal_cmd; mod env_status_cmd; mod profile_init_cmd; mod profile_list_cmd; mod profile_show_cmd; mod profile_switch_cmd; pub(crate) mod common;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/output.rs
examples/envman/src/output.rs
use peace::{ cmd_model::CmdOutcome, fmt::{ presentable::{Heading, HeadingLevel}, presentln, }, item_model::ItemId, resource_rt::{resources::ts::SetUp, Resources}, rt_model::{output::OutputWrite, IndexMap}, }; use crate::model::EnvManError; /// Presents errors. pub async fn errors_present<O>(output: &mut O, errors: &[EnvManError]) -> Result<(), EnvManError> where O: OutputWrite, EnvManError: From<<O as OutputWrite>::Error>, { output .present(Heading::new(HeadingLevel::Level1, "Errors")) .await?; #[cfg(feature = "error_reporting")] { use peace::miette::{Diagnostic, GraphicalReportHandler}; let report_handler = GraphicalReportHandler::new().without_cause_chain(); let mut err_buffer = String::new(); for error in errors.iter() { let mut diagnostic_opt: Option<&dyn Diagnostic> = Some(error); while let Some(diagnostic) = diagnostic_opt { if diagnostic.help().is_some() || diagnostic.labels().is_some() || diagnostic.diagnostic_source().is_none() { // Ignore failures when writing errors let (Ok(()) | Err(_)) = report_handler.render_report(&mut err_buffer, diagnostic); let (Ok(()) | Err(_)) = output.present(&err_buffer).await; let (Ok(()) | Err(_)) = output.present("\n").await; } diagnostic_opt = diagnostic.diagnostic_source(); } err_buffer.clear(); } } #[cfg(not(feature = "error_reporting"))] { use std::error::Error; errors.iter().for_each(|error| { eprintln!("\n{error}"); let mut error = error.source(); while let Some(source) = error { eprintln!(" caused by: {source}"); error = source.source(); } }); } Ok(()) } /// Presents item errors. pub async fn item_errors_present<O>( output: &mut O, errors: &IndexMap<ItemId, EnvManError>, ) -> Result<(), EnvManError> where O: OutputWrite, EnvManError: From<<O as OutputWrite>::Error>, { output .present(Heading::new(HeadingLevel::Level1, "Errors")) .await?; #[cfg(feature = "error_reporting")] { use peace::miette::{Diagnostic, GraphicalReportHandler}; let report_handler = GraphicalReportHandler::new().without_cause_chain(); let mut err_buffer = String::new(); for (item_id, error) in errors.iter() { // Ignore failures when writing errors let (Ok(()) | Err(_)) = output.present(item_id).await; let (Ok(()) | Err(_)) = output.present(":\n").await; let mut diagnostic_opt: Option<&dyn Diagnostic> = Some(error); while let Some(diagnostic) = diagnostic_opt { if diagnostic.help().is_some() || diagnostic.labels().is_some() || diagnostic.diagnostic_source().is_none() { // Ignore failures when writing errors let (Ok(()) | Err(_)) = report_handler.render_report(&mut err_buffer, diagnostic); let (Ok(()) | Err(_)) = output.present(&err_buffer).await; let (Ok(()) | Err(_)) = output.present("\n").await; } diagnostic_opt = diagnostic.diagnostic_source(); } err_buffer.clear(); } } #[cfg(not(feature = "error_reporting"))] { use std::error::Error; errors.iter().for_each(|(item_id, error)| { eprintln!("\n{item_id}: {error}"); let mut error = error.source(); while let Some(source) = error { eprintln!(" caused by: {source}"); error = source.source(); } }); } Ok(()) } /// Presents interruption or error information of a `CmdOutcome`. pub async fn cmd_outcome_completion_present<O, T>( output: &mut O, resources: &Resources<SetUp>, cmd_outcome: CmdOutcome<T, EnvManError>, ) -> Result<(), EnvManError> where O: OutputWrite, EnvManError: From<<O as OutputWrite>::Error>, { match &cmd_outcome { CmdOutcome::Complete { value: _, cmd_blocks_processed: _, } => { // Nothing to do. } CmdOutcome::BlockInterrupted { item_stream_outcome, cmd_blocks_processed, cmd_blocks_not_processed, } => { let cmd_blocks_complete = cmd_blocks_processed .iter() .map(|cmd_block_desc| cmd_block_desc.cmd_block_name()) .collect::<Vec<_>>(); let cmd_blocks_incomplete = cmd_blocks_not_processed .iter() .map(|cmd_block_desc| cmd_block_desc.cmd_block_name()) .collect::<Vec<_>>(); let item_ids_processed = item_stream_outcome .item_ids_processed() .iter() .collect::<Vec<_>>(); let item_ids_not_processed = item_stream_outcome .item_ids_not_processed() .iter() .collect::<Vec<_>>(); presentln!(output, ["Execution was interrupted."]); presentln!(output, [""]); presentln!(output, ["`CmdBlock`s completed:"]); presentln!(output, [""]); presentln!(output, [&cmd_blocks_complete]); presentln!(output, ["`CmdBlock`s not completed:"]); presentln!(output, [""]); presentln!(output, [&cmd_blocks_incomplete]); presentln!(output, ["Items completed:"]); presentln!(output, [""]); presentln!(output, [&item_ids_processed]); presentln!(output, ["Items not completed:"]); presentln!(output, [""]); presentln!(output, [&item_ids_not_processed]); } CmdOutcome::ExecutionInterrupted { value: _, cmd_blocks_processed, cmd_blocks_not_processed, } => { let cmd_blocks_complete = cmd_blocks_processed .iter() .map(|cmd_block_desc| cmd_block_desc.cmd_block_name()) .collect::<Vec<_>>(); let cmd_blocks_incomplete = cmd_blocks_not_processed .iter() .map(|cmd_block_desc| cmd_block_desc.cmd_block_name()) .collect::<Vec<_>>(); presentln!(output, ["Execution was interrupted."]); presentln!(output, [""]); presentln!(output, ["`CmdBlock`s completed:"]); presentln!(output, [""]); presentln!(output, [&cmd_blocks_complete]); presentln!(output, ["`CmdBlock`s not completed:"]); presentln!(output, [""]); presentln!(output, [&cmd_blocks_incomplete]); } CmdOutcome::ItemError { item_stream_outcome: _, cmd_blocks_processed: _, cmd_blocks_not_processed: _, errors, } => { item_errors_present(output, errors).await?; let _ = tokio::fs::write("resources.ron", format!("{resources:#?}")).await; } } Ok(()) }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/rt_model.rs
examples/envman/src/rt_model.rs
//! Runtime data types for the EnvMan example pub use self::envman_cmd_ctx_types::EnvmanCmdCtxTypes; mod envman_cmd_ctx_types;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/web_components/tab_label.rs
examples/envman/src/web_components/tab_label.rs
use leptos::{ callback::{Callable, Callback}, component, ev::Event, html, prelude::{ ClassAttribute, ElementChild, GlobalAttributes, NodeRef, NodeRefAttribute, OnAttribute, }, view, IntoView, }; /// The label that users click to switch to that tab. #[component] pub fn TabLabel( tab_group_name: &'static str, tab_id: &'static str, #[prop(default = "")] label: &'static str, #[prop(default = "")] class: &'static str, #[prop(default = false)] checked: bool, #[prop(into, optional, default = None)] on_change: Option<Callback<Event>>, #[prop(into, optional, default = leptos::prelude::create_node_ref::<html::Input>())] node_ref: NodeRef<html::Input>, ) -> impl IntoView { let tab_classes = format!( "\ peer/{tab_id} \ hidden \ " ); let label_classes = format!( "\ {class} \ \ inline-block \ h-7 \ lg:h-9 \ px-2.5 \ \ cursor-pointer \ border-t \ border-x \ border-slate-400 \ \ peer-checked/{tab_id}:border-t-4 \ peer-checked/{tab_id}:border-t-blue-500 \ " ); #[cfg(not(target_arch = "wasm32"))] let _node_ref = node_ref; view! { <input type="radio" name=tab_group_name id=tab_id class=tab_classes checked=checked on:change={move |ev| { if let Some(on_change) = on_change { on_change.run(ev) } }} node_ref=node_ref /> <label for=tab_id class=label_classes> {label} </label> } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/web_components/env_deploy_home.rs
examples/envman/src/web_components/env_deploy_home.rs
use leptos::{ component, prelude::{ClassAttribute, ElementChild, OnAttribute, ServerFnError}, server, task::spawn_local, view, IntoView, }; use peace::webi_components::{FlowGraph, FlowGraphCurrent}; use crate::web_components::TabLabel; #[server] async fn discover_cmd_exec() -> Result<(), ServerFnError> { use tokio::sync::mpsc; use crate::web_components::CmdExecRequest; let cmd_exec_request_tx = leptos::context::use_context::<mpsc::Sender<CmdExecRequest>>(); if let Some(cmd_exec_request_tx) = cmd_exec_request_tx { match cmd_exec_request_tx.try_send(CmdExecRequest::Discover) { Ok(()) => {} Err(e) => { leptos::logging::log!("Failed to send Discover cmd: {e}"); } } } else { leptos::logging::log!("`cmd_exec_request_tx` is None"); } Ok(()) } #[server] async fn deploy_cmd_exec() -> Result<(), ServerFnError> { use tokio::sync::mpsc; use crate::web_components::CmdExecRequest; let cmd_exec_request_tx = leptos::context::use_context::<mpsc::Sender<CmdExecRequest>>(); if let Some(cmd_exec_request_tx) = cmd_exec_request_tx { match cmd_exec_request_tx.try_send(CmdExecRequest::Ensure) { Ok(()) => {} Err(e) => { leptos::logging::log!("Failed to send Ensure cmd: {e}"); } } } else { leptos::logging::log!("`cmd_exec_request_tx` is None"); } Ok(()) } #[server] async fn clean_cmd_exec() -> Result<(), ServerFnError> { use tokio::sync::mpsc; use crate::web_components::CmdExecRequest; let cmd_exec_request_tx = leptos::context::use_context::<mpsc::Sender<CmdExecRequest>>(); if let Some(cmd_exec_request_tx) = cmd_exec_request_tx { match cmd_exec_request_tx.try_send(CmdExecRequest::Clean) { Ok(()) => {} Err(e) => { leptos::logging::log!("Failed to send Clean cmd: {e}"); } } } else { leptos::logging::log!("`cmd_exec_request_tx` is None"); } Ok(()) } /// Top level component of the `WebiOutput`. #[component] pub fn EnvDeployHome() -> impl IntoView { let button_tw_classes = "\ border \ rounded \ px-4 \ py-3 \ text-m \ \ border-slate-400 \ bg-gradient-to-b \ from-slate-200 \ to-slate-300 \ \ hover:border-slate-300 \ hover:bg-gradient-to-b \ hover:from-slate-100 \ hover:to-slate-200 \ \ active:border-slate-500 \ active:bg-gradient-to-b \ active:from-slate-300 \ active:to-slate-400 \ "; view! { <div> <h1>"Environment"</h1> <TabLabel tab_group_name="environment_tabs" tab_id="tab_environment_example" label="Environment Example" checked=true /> <TabLabel tab_group_name="environment_tabs" tab_id="tab_environment_current" label="Current" /> <div class="\ invisible \ clear-both \ h-0 \ peer-checked/tab_environment_example:visible \ peer-checked/tab_environment_example:h-full \ " > <FlowGraph /> </div> <div class="\ invisible \ clear-both \ h-0 \ peer-checked/tab_environment_current:visible \ peer-checked/tab_environment_current:h-full \ " > <button on:click=move |_| { spawn_local(async { discover_cmd_exec() .await .expect("Expected `discover_cmd_exec` call to succeed."); }); } class=button_tw_classes > "🗺️ Discover" </button> <button on:click=move |_| { spawn_local(async { deploy_cmd_exec() .await .expect("Expected `deploy_cmd_exec` call to succeed."); }); } class=button_tw_classes > "🚀 Deploy" </button> <button on:click=move |_| { spawn_local(async { clean_cmd_exec() .await .expect("Expected `clean_cmd_exec` call to succeed."); }); } class=button_tw_classes > "🧹 Clean" </button> <FlowGraphCurrent /> </div> </div> } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/web_components/cmd_exec_request.rs
examples/envman/src/web_components/cmd_exec_request.rs
use serde::{Deserialize, Serialize}; /// Request for a command execution. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum CmdExecRequest { /// Run the `StatesDiscoverCmd`. Discover, /// Run the `EnsureCmd`. Ensure, /// Run the `CleanCmd`. Clean, }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/model/item_ids.rs
examples/envman/src/model/item_ids.rs
/// Marker type for item specs to do with deploying the web application. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct WebApp;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/model/env_type_parse_error.rs
examples/envman/src/model/env_type_parse_error.rs
use std::fmt; /// Failed to parse environment type from string. #[derive(Clone, Debug, PartialEq, Eq)] pub struct EnvTypeParseError(pub String); impl fmt::Display for EnvTypeParseError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, r#"Failed to parse environment type from string: `"{}"`. Valid values are ["development", "production"]"#, self.0 ) } } impl std::error::Error for EnvTypeParseError {}
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/model/params_keys.rs
examples/envman/src/model/params_keys.rs
use peace::{ cmd_ctx::type_reg::untagged::TypeReg, enum_iterator::Sequence, params::ParamsKey, profile_model::Profile, }; use serde::{Deserialize, Serialize}; use crate::model::{EnvManFlow, EnvType}; /// Keys for workspace parameters. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Deserialize, Serialize, Sequence)] #[enum_iterator(crate = peace::enum_iterator)] #[serde(rename_all = "snake_case")] pub enum WorkspaceParamsKey { /// Default profile to use. Profile, /// Which flow this workspace is using. Flow, } impl ParamsKey for WorkspaceParamsKey { fn register_value_type(self, type_reg: &mut TypeReg<Self>) { match self { Self::Profile => type_reg.register::<Profile>(self), Self::Flow => type_reg.register::<EnvManFlow>(self), } } } /// Keys for profile parameters. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Deserialize, Serialize, Sequence)] #[enum_iterator(crate = peace::enum_iterator)] #[serde(rename_all = "snake_case")] pub enum ProfileParamsKey { /// Whether the environment is for `Development`, `Production`. EnvType, } impl ParamsKey for ProfileParamsKey { fn register_value_type(self, type_reg: &mut TypeReg<Self>) { match self { Self::EnvType => type_reg.register::<EnvType>(self), } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/model/env_type.rs
examples/envman/src/model/env_type.rs
use std::str::FromStr; use peace::fmt::Presenter; use serde::{Deserialize, Serialize}; use crate::model::EnvTypeParseError; /// Type of environment: development or production. #[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)] pub enum EnvType { /// Development environment that runs on `localhost`. Development, /// Environment that runs in AWS. /// /// Credentials are read from the environment. Production, } impl FromStr for EnvType { type Err = EnvTypeParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "development" => Ok(Self::Development), "production" => Ok(Self::Production), _ => Err(EnvTypeParseError(s.to_string())), } } } impl std::fmt::Display for EnvType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { EnvType::Development => "development".fmt(f), EnvType::Production => "production".fmt(f), } } } #[peace::fmt::async_trait(?Send)] impl peace::fmt::Presentable for EnvType { async fn present<'output, PR>(&self, presenter: &mut PR) -> Result<(), PR::Error> where PR: Presenter<'output>, { match self { EnvType::Development => presenter.code_inline("development").await, EnvType::Production => presenter.code_inline("production").await, } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/model/cli_args.rs
examples/envman/src/model/cli_args.rs
#[cfg(feature = "web_server")] use std::net::IpAddr; use clap::{Parser, Subcommand, ValueHint}; use peace::{cli::output::CliColorizeOpt, cli_model::OutputFormat, profile_model::Profile}; use semver::Version; use url::Url; use crate::model::{EnvManFlow, EnvType, RepoSlug}; #[derive(Parser)] #[clap( author, version, about = "Manages an application's lifecycle.", long_about = "Manages deployment, configuration, upgrading, and cleaning up of an application." )] pub struct CliArgs { /// Command to run. #[command(subcommand)] pub command: EnvManCommand, /// Whether to run with multiple threads. #[arg(long, default_value = "false", global(true))] pub fast: bool, /// The format of the command output. /// /// At this level, this needs to be specified before the subcommand. /// <https://github.com/clap-rs/clap/issues/3002> needs to be implemented /// for the argument to be passed in after the subcommand. #[arg(long, global(true))] pub format: Option<OutputFormat>, /// Whether output should be colorized. /// /// * "auto" (default): Colorize when used interactively. /// * "always": Always colorize output. /// * "never": Never colorize output. #[arg(long, default_value = "auto", global(true))] pub color: CliColorizeOpt, /// Whether to show debug information. #[arg(long, default_value = "false", global(true))] pub debug: bool, } #[derive(Subcommand)] pub enum EnvManCommand { /// Initializes a profile to deploy a web application. Init { /// Name to use for the profile. profile: Profile, /// Type of the profile's deployed environment. #[arg(short, long)] r#type: EnvType, /// Which flow to use: `"upload"` or `"deploy"`. #[arg(long, default_value = "deploy")] flow: EnvManFlow, /// Username and repository of the application to download. slug: RepoSlug, /// Version of the application to download. version: Version, /// URL to override the default download URL. #[arg(long, value_hint(ValueHint::Url))] url: Option<Url>, }, /// Shows or initializes the current profile. Profile { /// Profile command to run. #[command(subcommand)] command: Option<ProfileCommand>, }, /// Switches the current profile. /// /// Similar to changing the branch in git. Switch { /// Profile name to switch to. profile: Profile, /// Whether or not to create the profile. /// /// * If this flag is specified, and the profile already exists, then /// the switch does not happen. /// * If this flag is not specified, and the profile does not exist, /// then the switch does not happen. #[arg(short, long)] create: bool, /// Type of the profile's deployed environment. #[arg(short, long, required_if_eq("create", "true"))] r#type: Option<EnvType>, /// Username and repository of the application to download. #[arg(required_if_eq("create", "true"))] slug: Option<RepoSlug>, /// Version of the application to download. #[arg(required_if_eq("create", "true"))] version: Option<Version>, /// URL to override the default download URL. #[arg(short, long, value_hint(ValueHint::Url))] url: Option<Url>, }, /// Discovers the state of the environment. Discover, /// Shows the state of the environment. Status, /// Shows the goal state of the environment. Goal, /// Shows the diff between states of the environment. /// /// By default, this compares the current and goal states of the active /// profile. /// /// Users may pass in two profiles to compare the current states of both /// profiles. Diff { /// First profile in the comparison. #[arg(requires("profile_b"))] profile_a: Option<Profile>, /// Second profile in the comparison. profile_b: Option<Profile>, }, /// Deploys / updates the environment. Deploy, /// Cleans the current environment. Clean, /// Runs `envman` as a web server. #[cfg(feature = "web_server")] Web { /// The address to bind to, defaults to `127.0.0.1`. /// /// If you want to listen on all interfaces, use `0.0.0.0`. #[arg(long, default_value = "127.0.0.1", value_hint(ValueHint::Other))] address: IpAddr, /// Port to listen on, defaults to `7890`. #[arg(short, long, default_value = "7890", value_hint(ValueHint::Other))] port: u16, }, } #[derive(Subcommand)] pub enum ProfileCommand { /// Lists available profiles. List, /// Shows the current profile, if any. Show, }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/model/env_man_flow.rs
examples/envman/src/model/env_man_flow.rs
use std::str::FromStr; use peace::fmt::Presenter; use serde::{Deserialize, Serialize}; use crate::model::EnvManFlowParseError; /// Which flow to use: application upload or environment deploy. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize, Serialize)] pub enum EnvManFlow { /// Upload the application to S3. AppUpload, /// Deploy the full environment. #[default] EnvDeploy, } impl FromStr for EnvManFlow { type Err = EnvManFlowParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "upload" => Ok(Self::AppUpload), "deploy" => Ok(Self::EnvDeploy), _ => Err(EnvManFlowParseError(s.to_string())), } } } impl std::fmt::Display for EnvManFlow { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { EnvManFlow::AppUpload => "upload".fmt(f), EnvManFlow::EnvDeploy => "deploy".fmt(f), } } } #[peace::fmt::async_trait(?Send)] impl peace::fmt::Presentable for EnvManFlow { async fn present<'output, PR>(&self, presenter: &mut PR) -> Result<(), PR::Error> where PR: Presenter<'output>, { match self { EnvManFlow::AppUpload => presenter.code_inline("upload").await, EnvManFlow::EnvDeploy => presenter.code_inline("deploy").await, } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/model/env_man_flow_parse_error.rs
examples/envman/src/model/env_man_flow_parse_error.rs
use std::fmt; /// Failed to parse flow from string. #[derive(Clone, Debug, PartialEq, Eq)] pub struct EnvManFlowParseError(pub String); impl fmt::Display for EnvManFlowParseError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, r#"Failed to parse flow from string: `"{}"`. Valid values are ["upload", "deploy"]"#, self.0 ) } } impl std::error::Error for EnvManFlowParseError {}
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/model/repo_slug_error.rs
examples/envman/src/model/repo_slug_error.rs
#[cfg(feature = "error_reporting")] use peace::miette::{self, SourceSpan}; /// Error parsing a [`RepoSlug`]. /// /// [`RepoSlug`]: crate::RepoSlug #[cfg_attr(feature = "error_reporting", derive(peace::miette::Diagnostic))] #[derive(Debug, thiserror::Error)] pub enum RepoSlugError { /// Account ID provided is invalid. #[error("Account ID provided is invalid: `{}`.", account)] #[cfg_attr( feature = "error_reporting", diagnostic( code(envman::account_invalid), help( "Account IDs must begin with an ascii letter, \ and only contain letters, numbers, hyphens, and underscores." ) ) )] AccountInvalid { /// Repository slug input string. #[cfg_attr(feature = "error_reporting", source_code)] input: String, /// The account segment of the string. account: String, /// Span of the account segment in the slug. #[cfg(feature = "error_reporting")] #[label] span: SourceSpan, }, /// Repository name provided is invalid. #[error("Repository name provided is invalid: `{}`.", repo_name)] #[cfg_attr( feature = "error_reporting", diagnostic( code(envman::repo_name_invalid), help( "Repository names must begin with an ascii letter, \ and only contain letters, numbers, hyphens, and underscores." ) ) )] RepoNameInvalid { /// Repository slug input string. #[cfg_attr(feature = "error_reporting", source_code)] input: String, /// The repository name segment of the string. repo_name: String, /// Span of the repository name segment in the slug. #[cfg(feature = "error_reporting")] #[label] span: SourceSpan, }, /// Repository slug has invalid number of segments. #[error("Repository slug has invalid number of segments: `{}`.", input)] #[cfg_attr( feature = "error_reporting", diagnostic( code(envman::segment_count_invalid), help("Repository slug must contain exactly one slash.") ) )] SegmentCountInvalid { /// Repository slug input string. input: String, }, }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/model/envman_error.rs
examples/envman/src/model/envman_error.rs
use std::convert::Infallible; #[cfg(feature = "error_reporting")] use peace::miette; use peace::{ cfg::AppName, profile_model::Profile, rt_model::fn_graph::{Edge, WouldCycle}, }; /// Error while managing a web application. #[cfg_attr(feature = "error_reporting", derive(peace::miette::Diagnostic))] #[derive(Debug, thiserror::Error)] pub enum EnvManError { /// Failed to construct web application download URL. #[error("Failed to construct web application download URL.")] #[cfg_attr( feature = "error_reporting", diagnostic( code(envman::envman_url_build), help("If the URL is valid, this may be a bug in the example, or the `url` library.") ) )] EnvManUrlBuild { /// Computed URL that is attempted to be parsed. #[cfg_attr(feature = "error_reporting", source_code)] url_candidate: String, /// URL parse error. #[source] error: url::ParseError, }, /// Failed to parse environment type. #[error("Failed to parse environment type.")] EnvTypeParseError( #[source] #[from] crate::model::EnvTypeParseError, ), /// User tried to switch to a profile that doesn't exist. #[error("Profile to switch to does not exist.")] #[cfg_attr( feature = "error_reporting", diagnostic( code(envman::profile_switch_to_non_existent), help( "The `{profile_to_switch_to}` profile does not exist.\n\ You can create it by passing the `--create --type development` parameters\n\ or run `{app_name} profile list` to see profiles you can switch to." ) ) )] ProfileSwitchToNonExistent { /// The profile that the user tried to switch to. profile_to_switch_to: Profile, /// Name of this app. app_name: AppName, }, /// User tried to create a profile that already exists. #[error("Profile to create already exists.")] #[cfg_attr( feature = "error_reporting", diagnostic( code(envman::profile_to_create_exists), help( "The `{profile_to_create}` profile already exists.\n\ You may switch to the profile using `{app_name} switch {profile_to_create}`\n\ or create a profile with a different name." ) ) )] ProfileToCreateExists { /// The profile that the user tried to create. profile_to_create: Profile, /// Name of this app. app_name: AppName, }, // === Item errors === // /// A `FileDownload` item error occurred. #[error("A `FileDownload` item error occurred.")] PeaceItemFileDownload( #[cfg_attr(feature = "error_reporting", diagnostic_source)] #[source] #[from] peace_items::file_download::FileDownloadError, ), /// An `InstanceProfile` item error occurred. #[error("An `InstanceProfile` item error occurred.")] InstanceProfileItem( #[cfg_attr(feature = "error_reporting", diagnostic_source)] #[source] #[from] crate::items::peace_aws_instance_profile::InstanceProfileError, ), /// An `IamPolicy` item error occurred. #[error("An `IamPolicy` item error occurred.")] IamPolicyItem( #[cfg_attr(feature = "error_reporting", diagnostic_source)] #[source] #[from] crate::items::peace_aws_iam_policy::IamPolicyError, ), /// An `IamRole` item error occurred. #[error("An `IamRole` item error occurred.")] IamRoleItem( #[cfg_attr(feature = "error_reporting", diagnostic_source)] #[source] #[from] crate::items::peace_aws_iam_role::IamRoleError, ), /// An `S3Bucket` item error occurred. #[error("An `S3Bucket` item error occurred.")] S3BucketItem( #[cfg_attr(feature = "error_reporting", diagnostic_source)] #[source] #[from] crate::items::peace_aws_s3_bucket::S3BucketError, ), /// An `S3Object` item error occurred. #[error("An `S3Object` item error occurred.")] S3ObjectItem( #[cfg_attr(feature = "error_reporting", diagnostic_source)] #[source] #[from] crate::items::peace_aws_s3_object::S3ObjectError, ), // === Framework errors === // /// A `peace` runtime error occurred. #[error("A `peace` runtime error occurred.")] PeaceRtError( #[cfg_attr(feature = "error_reporting", diagnostic_source)] #[source] #[from] peace::rt_model::Error, ), /// A graph `WouldCycle` error occurred. #[error("A `peace` runtime error occurred.")] WouldCycleError( #[source] #[from] WouldCycle<Edge>, ), // === Scaffolding errors === // #[error("Failed to initialize tokio runtime.")] TokioRuntimeInit(#[source] std::io::Error), // === Web Server errors === // /// Web interface server produced an error. #[cfg(feature = "ssr")] #[error("Web interface server produced an error.")] #[cfg_attr(feature = "error_reporting", diagnostic(code(envman::webi)))] Webi { /// Underlying error. #[cfg_attr(feature = "error_reporting", diagnostic_source)] #[from] #[source] error: peace::webi_model::WebiError, }, /// Web server ended due to an error. #[cfg(feature = "ssr")] #[error("Web server ended due to an error.")] #[cfg_attr( feature = "error_reporting", diagnostic(code(envman::web_server_serve),) )] WebServerServe { /// Underlying error. #[source] error: std::io::Error, }, /// Failed to join thread that rendered web server home page. #[cfg(feature = "ssr")] #[error("Failed to join thread that rendered web server home page.")] #[cfg_attr( feature = "error_reporting", diagnostic(code(envman::web_server_render_join)) )] WebServerRenderJoin { /// Underlying error. #[source] error: tokio::task::JoinError, }, } impl From<Infallible> for EnvManError { fn from(_infallible: Infallible) -> Self { unreachable!("By definition the `Infallible` error can never be reached."); } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/model/repo_slug.rs
examples/envman/src/model/repo_slug.rs
use std::{fmt, str::FromStr}; #[cfg(feature = "error_reporting")] use peace::miette::SourceSpan; use serde::{Deserialize, Serialize}; use crate::model::RepoSlugError; const FORWARD_SLASH: char = '/'; /// A repository slug, e.g. `username/repo_name`. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub struct RepoSlug { /// Account repo_name the app resides in. account: String, /// Name of the repository. repo_name: String, } impl RepoSlug { fn account_validate(input: &str, account_segment: &str) -> Result<(), RepoSlugError> { if Self::is_valid_segment(account_segment) { Ok(()) } else { #[cfg(feature = "error_reporting")] let span = { let start = 0; let length = account_segment.len(); SourceSpan::from((start, length)) }; Err(RepoSlugError::AccountInvalid { input: input.to_string(), account: account_segment.to_string(), #[cfg(feature = "error_reporting")] span, }) } } fn repo_name_validate( input: &str, repo_name_segment: &str, #[cfg(feature = "error_reporting")] segment_byte_offset: usize, ) -> Result<(), RepoSlugError> { if Self::is_valid_segment(repo_name_segment) { Ok(()) } else { #[cfg(feature = "error_reporting")] let span = { let start = segment_byte_offset; let length = repo_name_segment.len(); SourceSpan::from((start, length)) }; Err(RepoSlugError::RepoNameInvalid { input: input.to_string(), repo_name: repo_name_segment.to_string(), #[cfg(feature = "error_reporting")] span, }) } } /// Returns whether the provided `&str` is a valid account or repo_name. /// /// The ID must begin with an ascii alphabetic character, and subsequent /// characters must be either a letter, number, hyphen, or underscore. fn is_valid_segment(segment: &str) -> bool { let mut chars = segment.chars(); let first_char = chars.next(); let first_char_valid = first_char.map(|c| c.is_ascii_alphabetic()).unwrap_or(false); let remainder_chars_valid = chars.all(|c| c.is_ascii_alphabetic() || c.is_ascii_digit() || c == '-' || c == '_'); first_char_valid && remainder_chars_valid } /// Returns the account the repository belongs to. pub fn account(&self) -> &str { self.account.as_ref() } /// Returns the name of the repository. pub fn repo_name(&self) -> &str { self.repo_name.as_ref() } } impl fmt::Display for RepoSlug { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}/{}", self.account, self.repo_name) } } impl FromStr for RepoSlug { type Err = RepoSlugError; fn from_str(input: &str) -> Result<Self, Self::Err> { let mut segments = input.splitn(3, FORWARD_SLASH); let account = segments.next(); let repo_name = segments.next(); let remainder = segments.next(); if let (Some(account), Some(repo_name), None) = (account, repo_name, remainder) { Self::account_validate(input, account)?; #[cfg(not(feature = "error_reporting"))] Self::repo_name_validate(input, repo_name)?; #[cfg(feature = "error_reporting")] Self::repo_name_validate(input, repo_name, account.len() + FORWARD_SLASH.len_utf8())?; let account = account.to_string(); let repo_name = repo_name.to_string(); Ok(RepoSlug { account, repo_name }) } else { Err(RepoSlugError::SegmentCountInvalid { input: input.to_string(), }) } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/model/profile_switch.rs
examples/envman/src/model/profile_switch.rs
use peace::profile_model::Profile; use semver::Version; use url::Url; use crate::model::{EnvType, RepoSlug}; /// Whether to switch to an existing profile or to a new one. #[derive(Clone, Debug, PartialEq, Eq)] pub enum ProfileSwitch { /// Switch to an existing profile. ToExisting { /// The existing profile to switch to. profile: Profile, }, /// Switch to a newly created profile. CreateNew { /// The existing profile to switch to. profile: Profile, /// Type of environment: development or production. env_type: EnvType, /// Username and repository of the application to download. slug: RepoSlug, /// Version of the application to download. version: Version, /// URL to override where to download the application from. url: Option<Url>, }, }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/model/env_diff_selection.rs
examples/envman/src/model/env_diff_selection.rs
use peace::profile_model::Profile; /// What to run the diff on. /// /// Of note is, this is for showing diffs between flow states, but what is /// valuable to the user may be any combination within the following groupings. /// /// Within one profile: /// /// * previous vs current workspace params /// * previous vs current profile params /// * previous vs current flow params /// * previous vs current item params /// * previous vs current state /// * current vs goal state /// /// Between two profiles: /// /// * profile params /// * flow params /// * item params /// * current states #[derive(Clone, Debug, PartialEq, Eq)] pub enum EnvDiffSelection { /// Compare the current and goal states of the active profile. CurrentAndGoal, /// Compare the current states of the specified profiles. DiffProfilesCurrent { /// First profile in the comparison, the reference point. profile_a: Profile, /// Second profile in the comparison. profile_b: Profile, }, }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/flows/env_deploy_flow.rs
examples/envman/src/flows/env_deploy_flow.rs
use std::path::PathBuf; use peace::{ cfg::app_name, flow_model::flow_id, flow_rt::{Flow, ItemGraphBuilder}, item_model::item_id, params::{Params, ParamsSpec}, profile_model::Profile, }; use peace_items::file_download::{FileDownloadItem, FileDownloadParams}; use semver::Version; use url::Url; use crate::{ flows::EnvmanMappingFns, items::{ peace_aws_iam_policy::{IamPolicyItem, IamPolicyParams}, peace_aws_iam_role::{IamRoleItem, IamRoleParams}, peace_aws_instance_profile::{InstanceProfileItem, InstanceProfileParams}, peace_aws_s3_bucket::{S3BucketItem, S3BucketParams}, peace_aws_s3_object::{S3ObjectItem, S3ObjectParams}, }, model::{EnvManError, RepoSlug, WebApp}, }; /// Flow to deploy a web application. #[derive(Debug)] pub struct EnvDeployFlow; impl EnvDeployFlow { /// Returns the `Flow` graph. pub async fn flow() -> Result<Flow<EnvManError>, EnvManError> { let flow = { let graph = { let mut graph_builder = ItemGraphBuilder::<EnvManError>::new(); let [app_download_id, iam_policy_item_id, iam_role_item_id, instance_profile_item_id, s3_bucket_id, s3_object_id] = graph_builder.add_fns([ FileDownloadItem::<WebApp>::new(item_id!("app_download")).into(), IamPolicyItem::<WebApp>::new(item_id!("iam_policy")).into(), IamRoleItem::<WebApp>::new(item_id!("iam_role")).into(), InstanceProfileItem::<WebApp>::new(item_id!("instance_profile")).into(), S3BucketItem::<WebApp>::new(item_id!("s3_bucket")).into(), S3ObjectItem::<WebApp>::new(item_id!("s3_object")).into(), ]); graph_builder.add_logic_edges([ (iam_policy_item_id, iam_role_item_id), (iam_role_item_id, instance_profile_item_id), // Download the file before uploading it. (app_download_id, s3_object_id), ])?; // Create the bucket before uploading to it. graph_builder.add_contains_edge(s3_bucket_id, s3_object_id)?; graph_builder.build() }; Flow::new(flow_id!("env_deploy"), graph) }; Ok(flow) } /// Returns the params needed for this flow. pub fn params( profile: &Profile, slug: &RepoSlug, version: &Version, url: Option<Url>, ) -> Result<EnvDeployFlowParamsSpecs, EnvManError> { let account = slug.account(); let repo_name = slug.repo_name(); let app_download_dir = PathBuf::from_iter([account, repo_name, &format!("{version}")]); // https://github.com/azriel91/web_app/releases/download/0.1.0/web_app.tar let file_ext = "tar"; let web_app_file_url = url.map(Result::Ok).unwrap_or_else(|| { let url_candidate = format!( "https://github.com/{account}/{repo_name}/releases/download/{version}/{repo_name}.{file_ext}" ); Url::parse(&url_candidate).map_err(|error| EnvManError::EnvManUrlBuild { url_candidate, error, }) })?; let web_app_path_local = app_download_dir.join(format!("{repo_name}.{file_ext}")); let app_download_params_spec = FileDownloadParams::new( web_app_file_url, web_app_path_local.clone(), #[cfg(target_arch = "wasm32")] peace_items::file_download::StorageForm::Base64, ) .into(); let iam_policy_name = profile.to_string(); let iam_role_name = profile.to_string(); let instance_profile_name = profile.to_string(); let bucket_name = { let username = whoami::username(); let app_name = app_name!(); format!("{username}-peace-{app_name}-{profile}").replace('_', "-") }; let path = String::from("/"); let iam_policy_params_spec = IamPolicyParams::<WebApp>::field_wise_spec() .with_name(iam_policy_name) .with_path(path.clone()) .with_policy_document(format!( include_str!("ec2_to_s3_bucket_policy.json"), bucket_name = bucket_name )) .build(); let iam_role_params_spec = IamRoleParams::<WebApp>::field_wise_spec() .with_name(iam_role_name) .with_path(path.clone()) .with_managed_policy_arn_from_mapping_fn( EnvmanMappingFns::IamRoleManagedPolicyArnFromIamPolicyState_v0_1_0, ) .build(); let instance_profile_params_spec = InstanceProfileParams::<WebApp>::field_wise_spec() .with_name(instance_profile_name) .with_path(path) .with_role_associate(true) .build(); let object_key = web_app_path_local .file_name() .expect("Expected web app file name to exist.") .to_string_lossy() .to_string(); let s3_bucket_params_spec = S3BucketParams::<WebApp>::field_wise_spec() .with_name(bucket_name.clone()) .build(); let s3_object_params_spec = S3ObjectParams::<WebApp>::field_wise_spec() .with_file_path(web_app_path_local) .with_bucket_name(bucket_name) .with_object_key(object_key) .build(); Ok(EnvDeployFlowParamsSpecs { app_download_params_spec, iam_policy_params_spec, iam_role_params_spec, instance_profile_params_spec, s3_bucket_params_spec, s3_object_params_spec, }) } } #[derive(Debug)] pub struct EnvDeployFlowParamsSpecs { pub app_download_params_spec: ParamsSpec<FileDownloadParams<WebApp>>, pub iam_policy_params_spec: ParamsSpec<IamPolicyParams<WebApp>>, pub iam_role_params_spec: ParamsSpec<IamRoleParams<WebApp>>, pub instance_profile_params_spec: ParamsSpec<InstanceProfileParams<WebApp>>, pub s3_bucket_params_spec: ParamsSpec<S3BucketParams<WebApp>>, pub s3_object_params_spec: ParamsSpec<S3ObjectParams<WebApp>>, }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/flows/envman_mapping_fns.rs
examples/envman/src/flows/envman_mapping_fns.rs
use peace::{ enum_iterator::Sequence, params::{FromFunc, MappingFn, MappingFnId, MappingFnImpl, MappingFns}, profile_model::Profile, }; use serde::{Deserialize, Serialize}; use crate::items::{peace_aws_iam_policy::IamPolicyState, peace_aws_s3_bucket::S3BucketState}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize, Sequence)] #[allow(non_camel_case_types)] #[enum_iterator(crate = peace::enum_iterator)] pub enum EnvmanMappingFns { /// Returns the `IamRole` name from profile. IamRoleNameFromProfile_v0_1_0, /// Returns the `IamRole` Managed Policy ARN from the `IamPolicyState`'s /// `policy_id_arn_version`. IamRoleManagedPolicyArnFromIamPolicyState_v0_1_0, /// Returns the `S3Bucket` name from the `S3BucketState`. S3BucketNameFromS3BucketState_v0_1_0, } impl MappingFns for EnvmanMappingFns { fn id(self) -> MappingFnId { let name = match self { Self::IamRoleNameFromProfile_v0_1_0 => "IamRoleNameFromProfile_v0_1_0", Self::IamRoleManagedPolicyArnFromIamPolicyState_v0_1_0 => { "IamRoleManagedPolicyArnFromIamPolicyState_v0_1_0" } Self::S3BucketNameFromS3BucketState_v0_1_0 => "S3BucketNameFromS3BucketState_v0_1_0", }; MappingFnId::new(name.to_string()) } fn mapping_fn(self) -> Box<dyn MappingFn> { match self { Self::IamRoleNameFromProfile_v0_1_0 => { MappingFnImpl::from_func(|profile: &Profile| Some(profile.to_string())) } Self::IamRoleManagedPolicyArnFromIamPolicyState_v0_1_0 => { MappingFnImpl::from_func(IamPolicyState::policy_id_arn_version) } Self::S3BucketNameFromS3BucketState_v0_1_0 => { MappingFnImpl::from_func(S3BucketState::bucket_name) } } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/flows/app_upload_flow.rs
examples/envman/src/flows/app_upload_flow.rs
use std::path::PathBuf; use peace::{ cfg::app_name, flow_model::flow_id, flow_rt::{Flow, ItemGraphBuilder}, item_model::item_id, params::{Params, ParamsSpec}, profile_model::Profile, }; use peace_items::file_download::{FileDownloadItem, FileDownloadParams}; use semver::Version; use url::Url; use crate::{ items::{ peace_aws_s3_bucket::{S3BucketItem, S3BucketParams}, peace_aws_s3_object::{S3ObjectItem, S3ObjectParams}, }, model::{EnvManError, RepoSlug, WebApp}, }; /// Flow to upload a web application to S3. #[derive(Debug)] pub struct AppUploadFlow; impl AppUploadFlow { /// Returns the `Flow` graph. pub async fn flow() -> Result<Flow<EnvManError>, EnvManError> { let flow = { let graph = { let mut graph_builder = ItemGraphBuilder::<EnvManError>::new(); let [a, b, c] = graph_builder.add_fns([ FileDownloadItem::<WebApp>::new(item_id!("app_download")).into(), S3BucketItem::<WebApp>::new(item_id!("s3_bucket")).into(), S3ObjectItem::<WebApp>::new(item_id!("s3_object")).into(), ]); graph_builder.add_logic_edge(a, c)?; graph_builder.add_contains_edge(b, c)?; graph_builder.build() }; Flow::new(flow_id!("app_upload"), graph) }; Ok(flow) } /// Returns the params needed for this flow. pub fn params( profile: &Profile, slug: &RepoSlug, version: &Version, url: Option<Url>, ) -> Result<AppUploadFlowParamsSpecs, EnvManError> { let account = slug.account(); let repo_name = slug.repo_name(); let app_download_dir = PathBuf::from_iter([account, repo_name, &format!("{version}")]); #[cfg(target_family = "windows")] let file_ext = "zip"; #[cfg(any(target_family = "unix", target_family = "wasm"))] let file_ext = "tar"; // windows: // https://github.com/azriel91/web_app/releases/download/0.1.0/web_app.zip // // linux: // https://github.com/azriel91/web_app/releases/download/0.1.0/web_app.tar let web_app_file_url = url.map(Result::Ok).unwrap_or_else(|| { let url_candidate = format!( "https://github.com/{account}/{repo_name}/releases/download/{version}/{repo_name}.{file_ext}" ); Url::parse(&url_candidate).map_err(|error| EnvManError::EnvManUrlBuild { url_candidate, error, }) })?; let web_app_path_local = app_download_dir.join(format!("{repo_name}.{file_ext}")); let app_download_params_spec = FileDownloadParams::new( web_app_file_url, web_app_path_local.clone(), #[cfg(target_arch = "wasm32")] peace_items::file_download::StorageForm::Base64, ) .into(); let bucket_name = { let username = whoami::username(); let app_name = app_name!(); format!("{username}-peace-{app_name}-{profile}").replace('_', "-") }; let object_key = web_app_path_local .file_name() .expect("Expected web app file name to exist.") .to_string_lossy() .to_string(); let s3_bucket_params_spec = S3BucketParams::<WebApp>::field_wise_spec() .with_name(bucket_name.clone()) .build(); let s3_object_params_spec = S3ObjectParams::<WebApp>::field_wise_spec() .with_file_path(web_app_path_local) .with_object_key(object_key) .with_bucket_name(bucket_name) .build(); Ok(AppUploadFlowParamsSpecs { app_download_params_spec, s3_bucket_params_spec, s3_object_params_spec, }) } } #[derive(Debug)] pub struct AppUploadFlowParamsSpecs { pub app_download_params_spec: ParamsSpec<FileDownloadParams<WebApp>>, pub s3_bucket_params_spec: ParamsSpec<S3BucketParams<WebApp>>, pub s3_object_params_spec: ParamsSpec<S3ObjectParams<WebApp>>, }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/rt_model/envman_cmd_ctx.rs
examples/envman/src/rt_model/envman_cmd_ctx.rs
use peace::cmd_ctx::CmdCtxSpsf; use crate::rt_model::EnvmanCmdCtxTypes; /// Alias to simplify naming the `CmdCtx` type. pub type EnvManCmdCtx<'ctx, O> = CmdCtxSpsf<'_, EnvmanCmdCtxTypes<O>>;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/rt_model/envman_cmd_ctx_types.rs
examples/envman/src/rt_model/envman_cmd_ctx_types.rs
use std::marker::PhantomData; use peace::{cmd_ctx::CmdCtxTypes, rt_model::output::OutputWrite}; use crate::{ flows::EnvmanMappingFns, model::{EnvManError, ProfileParamsKey, WorkspaceParamsKey}, }; #[derive(Debug)] pub struct EnvmanCmdCtxTypes<Output>(PhantomData<Output>); impl<Output> CmdCtxTypes for EnvmanCmdCtxTypes<Output> where Output: OutputWrite, EnvManError: From<<Output as OutputWrite>::Error>, { type AppError = EnvManError; type FlowParamsKey = (); type MappingFns = EnvmanMappingFns; type Output = Output; type ProfileParamsKey = ProfileParamsKey; type WorkspaceParamsKey = WorkspaceParamsKey; }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_instance_profile.rs
examples/envman/src/items/peace_aws_instance_profile.rs
//! Copies a number from one resource to another. pub use self::{ instance_profile_apply_fns::InstanceProfileApplyFns, instance_profile_data::InstanceProfileData, instance_profile_error::InstanceProfileError, instance_profile_item::InstanceProfileItem, instance_profile_params::{ InstanceProfileParams, InstanceProfileParamsFieldWise, InstanceProfileParamsPartial, }, instance_profile_state::InstanceProfileState, instance_profile_state_current_fn::InstanceProfileStateCurrentFn, instance_profile_state_diff::InstanceProfileStateDiff, instance_profile_state_diff_fn::InstanceProfileStateDiffFn, instance_profile_state_goal_fn::InstanceProfileStateGoalFn, }; pub mod model; mod instance_profile_apply_fns; mod instance_profile_data; mod instance_profile_error; mod instance_profile_item; mod instance_profile_params; mod instance_profile_state; mod instance_profile_state_current_fn; mod instance_profile_state_diff; mod instance_profile_state_diff_fn; mod instance_profile_state_goal_fn;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_iam_policy.rs
examples/envman/src/items/peace_aws_iam_policy.rs
//! Copies a number from one resource to another. pub use self::{ iam_policy_apply_fns::IamPolicyApplyFns, iam_policy_data::IamPolicyData, iam_policy_error::IamPolicyError, iam_policy_item::IamPolicyItem, iam_policy_params::{IamPolicyParams, IamPolicyParamsFieldWise, IamPolicyParamsPartial}, iam_policy_state::IamPolicyState, iam_policy_state_current_fn::IamPolicyStateCurrentFn, iam_policy_state_diff::IamPolicyStateDiff, iam_policy_state_diff_fn::IamPolicyStateDiffFn, iam_policy_state_goal_fn::IamPolicyStateGoalFn, }; pub mod model; mod iam_policy_apply_fns; mod iam_policy_data; mod iam_policy_error; mod iam_policy_item; mod iam_policy_params; mod iam_policy_state; mod iam_policy_state_current_fn; mod iam_policy_state_diff; mod iam_policy_state_diff_fn; mod iam_policy_state_goal_fn;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_s3_object.rs
examples/envman/src/items/peace_aws_s3_object.rs
//! Uploads a file to S3. pub use self::{ s3_object_apply_fns::S3ObjectApplyFns, s3_object_data::S3ObjectData, s3_object_error::S3ObjectError, s3_object_item::S3ObjectItem, s3_object_params::{S3ObjectParams, S3ObjectParamsFieldWise, S3ObjectParamsPartial}, s3_object_state::S3ObjectState, s3_object_state_current_fn::S3ObjectStateCurrentFn, s3_object_state_diff::S3ObjectStateDiff, s3_object_state_diff_fn::S3ObjectStateDiffFn, s3_object_state_goal_fn::S3ObjectStateGoalFn, }; mod s3_object_apply_fns; mod s3_object_data; mod s3_object_error; mod s3_object_item; mod s3_object_params; mod s3_object_state; mod s3_object_state_current_fn; mod s3_object_state_diff; mod s3_object_state_diff_fn; mod s3_object_state_goal_fn;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_iam_role.rs
examples/envman/src/items/peace_aws_iam_role.rs
//! Copies a number from one resource to another. pub use self::{ iam_role_apply_fns::IamRoleApplyFns, iam_role_data::IamRoleData, iam_role_error::IamRoleError, iam_role_item::IamRoleItem, iam_role_params::{IamRoleParams, IamRoleParamsFieldWise, IamRoleParamsPartial}, iam_role_state::IamRoleState, iam_role_state_current_fn::IamRoleStateCurrentFn, iam_role_state_diff::IamRoleStateDiff, iam_role_state_diff_fn::IamRoleStateDiffFn, iam_role_state_goal_fn::IamRoleStateGoalFn, }; pub mod model; mod iam_role_apply_fns; mod iam_role_data; mod iam_role_error; mod iam_role_item; mod iam_role_params; mod iam_role_state; mod iam_role_state_current_fn; mod iam_role_state_diff; mod iam_role_state_diff_fn; mod iam_role_state_goal_fn;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_s3_bucket.rs
examples/envman/src/items/peace_aws_s3_bucket.rs
//! Copies a number from one resource to another. pub use self::{ s3_bucket_apply_fns::S3BucketApplyFns, s3_bucket_data::S3BucketData, s3_bucket_error::S3BucketError, s3_bucket_item::S3BucketItem, s3_bucket_params::{S3BucketParams, S3BucketParamsFieldWise, S3BucketParamsPartial}, s3_bucket_state::S3BucketState, s3_bucket_state_current_fn::S3BucketStateCurrentFn, s3_bucket_state_diff::S3BucketStateDiff, s3_bucket_state_diff_fn::S3BucketStateDiffFn, s3_bucket_state_goal_fn::S3BucketStateGoalFn, }; mod s3_bucket_apply_fns; mod s3_bucket_data; mod s3_bucket_error; mod s3_bucket_item; mod s3_bucket_params; mod s3_bucket_state; mod s3_bucket_state_current_fn; mod s3_bucket_state_diff; mod s3_bucket_state_diff_fn; mod s3_bucket_state_goal_fn;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_s3_bucket/s3_bucket_item.rs
examples/envman/src/items/peace_aws_s3_bucket/s3_bucket_item.rs
use std::marker::PhantomData; use aws_config::BehaviorVersion; use peace::{ cfg::{async_trait, ApplyCheck, FnCtx, Item}, item_model::ItemId, params::Params, resource_rt::{resources::ts::Empty, Resources}, }; use crate::items::peace_aws_s3_bucket::{ S3BucketApplyFns, S3BucketData, S3BucketError, S3BucketParams, S3BucketState, S3BucketStateCurrentFn, S3BucketStateDiff, S3BucketStateDiffFn, S3BucketStateGoalFn, }; /// Item to create an IAM S3 bucket and IAM role. /// /// In sequence, this will: /// /// * Create the IAM Role. /// * Create the S3 bucket. /// * Add the IAM role to the S3 bucket. /// /// The `Id` type parameter is needed for each S3 bucket params to be a /// distinct type. /// /// # Type Parameters /// /// * `Id`: A zero-sized type used to distinguish different S3 bucket parameters /// from each other. #[derive(Debug)] pub struct S3BucketItem<Id> { /// ID of the S3 bucket item. item_id: ItemId, /// Marker for unique S3 bucket parameters type. marker: PhantomData<Id>, } impl<Id> S3BucketItem<Id> { /// Returns a new `S3BucketItem`. pub fn new(item_id: ItemId) -> Self { Self { item_id, marker: PhantomData, } } } impl<Id> Clone for S3BucketItem<Id> { fn clone(&self) -> Self { Self { item_id: self.item_id.clone(), marker: PhantomData, } } } #[async_trait(?Send)] impl<Id> Item for S3BucketItem<Id> where Id: Send + Sync + 'static, { type Data<'exec> = S3BucketData<'exec, Id>; type Error = S3BucketError; type Params<'exec> = S3BucketParams<Id>; type State = S3BucketState; type StateDiff = S3BucketStateDiff; fn id(&self) -> &ItemId { &self.item_id } async fn setup(&self, resources: &mut Resources<Empty>) -> Result<(), S3BucketError> { if !resources.contains::<aws_sdk_s3::Client>() { let sdk_config = aws_config::load_defaults(BehaviorVersion::latest()).await; resources.insert(sdk_config.region().cloned()); let client = aws_sdk_s3::Client::new(&sdk_config); resources.insert(client); } Ok(()) } #[cfg(feature = "item_state_example")] fn state_example(params: &Self::Params<'_>, _data: Self::Data<'_>) -> Self::State { use chrono::Utc; use peace::cfg::state::Timestamped; S3BucketState::Some { name: params.name().to_string(), creation_date: Timestamped::Value(Utc::now()), } } async fn try_state_current( fn_ctx: FnCtx<'_>, params_partial: &<Self::Params<'_> as Params>::Partial, data: Self::Data<'_>, ) -> Result<Option<Self::State>, S3BucketError> { S3BucketStateCurrentFn::try_state_current(fn_ctx, params_partial, data).await } async fn state_current( fn_ctx: FnCtx<'_>, params: &Self::Params<'_>, data: Self::Data<'_>, ) -> Result<Self::State, S3BucketError> { S3BucketStateCurrentFn::state_current(fn_ctx, params, data).await } async fn try_state_goal( fn_ctx: FnCtx<'_>, params_partial: &<Self::Params<'_> as Params>::Partial, data: Self::Data<'_>, ) -> Result<Option<Self::State>, S3BucketError> { S3BucketStateGoalFn::try_state_goal(fn_ctx, params_partial, data).await } async fn state_goal( fn_ctx: FnCtx<'_>, params: &Self::Params<'_>, data: Self::Data<'_>, ) -> Result<Self::State, S3BucketError> { S3BucketStateGoalFn::state_goal(fn_ctx, params, data).await } async fn state_diff( _params_partial: &<Self::Params<'_> as Params>::Partial, _data: Self::Data<'_>, state_current: &Self::State, state_goal: &Self::State, ) -> Result<Self::StateDiff, S3BucketError> { S3BucketStateDiffFn::state_diff(state_current, state_goal).await } async fn state_clean( _params_partial: &<Self::Params<'_> as Params>::Partial, _data: Self::Data<'_>, ) -> Result<Self::State, S3BucketError> { Ok(S3BucketState::None) } async fn apply_check( params: &Self::Params<'_>, data: Self::Data<'_>, state_current: &Self::State, state_target: &Self::State, diff: &Self::StateDiff, ) -> Result<ApplyCheck, Self::Error> { S3BucketApplyFns::<Id>::apply_check(params, data, state_current, state_target, diff).await } async fn apply_dry( fn_ctx: FnCtx<'_>, params: &Self::Params<'_>, data: Self::Data<'_>, state_current: &Self::State, state_target: &Self::State, diff: &Self::StateDiff, ) -> Result<Self::State, Self::Error> { S3BucketApplyFns::<Id>::apply_dry(fn_ctx, params, data, state_current, state_target, diff) .await } async fn apply( fn_ctx: FnCtx<'_>, params: &Self::Params<'_>, data: Self::Data<'_>, state_current: &Self::State, state_target: &Self::State, diff: &Self::StateDiff, ) -> Result<Self::State, Self::Error> { S3BucketApplyFns::<Id>::apply(fn_ctx, params, data, state_current, state_target, diff).await } #[cfg(feature = "item_interactions")] fn interactions( params: &Self::Params<'_>, _data: Self::Data<'_>, ) -> Vec<peace::item_interaction_model::ItemInteraction> { use peace::item_interaction_model::{ ItemInteractionPush, ItemLocation, ItemLocationAncestors, }; let s3_bucket_name = format!("🪣 {}", params.name()); let item_interaction = ItemInteractionPush::new( ItemLocationAncestors::new(vec![ItemLocation::localhost()]), ItemLocationAncestors::new(vec![ ItemLocation::group(String::from("S3")), ItemLocation::path(s3_bucket_name), ]), ) .into(); vec![item_interaction] } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_s3_bucket/s3_bucket_state_diff.rs
examples/envman/src/items/peace_aws_s3_bucket/s3_bucket_state_diff.rs
use std::fmt; use serde::{Deserialize, Serialize}; /// Diff between current (dest) and goal (src) state. #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] pub enum S3BucketStateDiff { /// S3Bucket would be added. Added, /// S3Bucket would be removed. Removed, /// S3Bucket renamed. /// /// AWS' SDK doesn't support modifying an S3 bucket's name. NameModified { /// Current bucket name. s3_bucket_name_current: String, /// Goal bucket name. s3_bucket_name_goal: String, }, /// S3Bucket exists and is up to date. InSyncExists, /// S3Bucket does not exist, which is goal. InSyncDoesNotExist, } impl fmt::Display for S3BucketStateDiff { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { S3BucketStateDiff::Added => { write!(f, "will be created.") } S3BucketStateDiff::Removed => { write!(f, "will be removed.") } S3BucketStateDiff::NameModified { s3_bucket_name_current, s3_bucket_name_goal, } => write!( f, "name has changed from {s3_bucket_name_current} to {s3_bucket_name_goal}" ), S3BucketStateDiff::InSyncExists => { write!(f, "exists and is up to date.") } S3BucketStateDiff::InSyncDoesNotExist => { write!(f, "does not exist as intended.") } } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_s3_bucket/s3_bucket_error.rs
examples/envman/src/items/peace_aws_s3_bucket/s3_bucket_error.rs
use aws_sdk_s3::{ error::SdkError, operation::{ create_bucket::CreateBucketError, delete_bucket::DeleteBucketError, head_bucket::HeadBucketError, list_buckets::ListBucketsError, }, types::error::{BucketAlreadyExists, BucketAlreadyOwnedByYou}, }; #[cfg(feature = "error_reporting")] use peace::miette::{self, SourceSpan}; /// Error while managing S3 bucket state. #[cfg_attr(feature = "error_reporting", derive(peace::miette::Diagnostic))] #[derive(Debug, thiserror::Error)] pub enum S3BucketError { /// S3 bucket name was attempted to be modified. #[error("S3 bucket name modification is not supported.")] NameModificationNotSupported { /// Current name of the s3 bucket. s3_bucket_name_current: String, /// Goal name of the s3 bucket. s3_bucket_name_goal: String, }, /// Failed to list S3 buckets. #[error("Failed to discover: `{s3_bucket_name}`.")] #[cfg_attr( feature = "error_reporting", diagnostic(help("Make sure you are connected to the internet and try again.")) )] S3BucketListError { /// S3Bucket friendly name. s3_bucket_name: String, /// Error description from AWS error. #[cfg(feature = "error_reporting")] #[source_code] aws_desc: String, /// Span of the description to highlight. #[cfg(feature = "error_reporting")] #[label] aws_desc_span: SourceSpan, /// Underlying error. #[source] error: Box<SdkError<ListBucketsError>>, }, /// Failed to create S3 bucket as someone else owns the name. #[error("Failed to create S3 bucket: `{s3_bucket_name}`.")] #[cfg_attr( feature = "error_reporting", diagnostic(help( "Someone else owns the S3 bucket name.\n\ \n\ Please use a different profile name by running:\n\ ```\n\ ./envman switch <profile_name> --create --type development username/repo <version>\n\ ```\n\ " )) )] S3BucketOwnedBySomeoneElseError { /// S3Bucket friendly name. s3_bucket_name: String, /// Underlying error. #[source] error: Box<BucketAlreadyExists>, }, /// Failed to create S3 bucket as you already have one with the same name. #[error( "Failed to create S3 bucket as you already have one with the same name: `{s3_bucket_name}`." )] S3BucketOwnedByYouError { /// S3Bucket friendly name. s3_bucket_name: String, /// Underlying error. #[source] error: Box<BucketAlreadyOwnedByYou>, }, /// Failed to create S3 bucket. #[error("Failed to create S3 bucket: `{s3_bucket_name}`.")] #[cfg_attr( feature = "error_reporting", diagnostic(help("Make sure you are connected to the internet and try again.")) )] S3BucketCreateError { /// S3Bucket friendly name. s3_bucket_name: String, /// Error description from AWS error. #[cfg(feature = "error_reporting")] #[source_code] aws_desc: String, /// Span of the description to highlight. #[cfg(feature = "error_reporting")] #[label] aws_desc_span: SourceSpan, /// Underlying error. #[source] error: Box<SdkError<CreateBucketError>>, }, /// Failed to discover S3 bucket. #[error("Failed to discover S3 bucket: `{s3_bucket_name}`.")] #[cfg_attr( feature = "error_reporting", diagnostic(help("Make sure you are connected to the internet and try again.")) )] S3BucketGetError { /// Expected S3 bucket friendly name. s3_bucket_name: String, /// Error description from AWS error. #[cfg(feature = "error_reporting")] #[source_code] aws_desc: String, /// Span of the description to highlight. #[cfg(feature = "error_reporting")] #[label] aws_desc_span: SourceSpan, /// Underlying error. #[source] error: Box<SdkError<HeadBucketError>>, }, /// Failed to delete S3 bucket. #[error("Failed to delete S3 bucket: `{s3_bucket_name}`.")] #[cfg_attr( feature = "error_reporting", diagnostic(help("Make sure you are connected to the internet and try again.")) )] S3BucketDeleteError { /// S3Bucket friendly name. s3_bucket_name: String, /// Error description from AWS error. #[cfg(feature = "error_reporting")] #[source_code] aws_desc: String, /// Span of the description to highlight. #[cfg(feature = "error_reporting")] #[label] aws_desc_span: SourceSpan, /// Underlying error. #[source] error: Box<SdkError<DeleteBucketError>>, }, /// User changed the S3 bucket name, but AWS does not support /// changing this. #[error( "S3Bucket name cannot be modified, as it is not supported by AWS: current: `{s3_bucket_name_current}`, goal: `{s3_bucket_name_goal}`." )] S3BucketModificationNotSupported { /// Current name of the s3 bucket. s3_bucket_name_current: String, /// Goal name of the s3 bucket. s3_bucket_name_goal: String, }, }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_s3_bucket/s3_bucket_state_goal_fn.rs
examples/envman/src/items/peace_aws_s3_bucket/s3_bucket_state_goal_fn.rs
use std::marker::PhantomData; use peace::{ cfg::{state::Timestamped, FnCtx}, params::Params, }; use crate::items::peace_aws_s3_bucket::{ S3BucketData, S3BucketError, S3BucketParams, S3BucketState, }; /// Reads the goal state of the S3 bucket state. #[derive(Debug)] pub struct S3BucketStateGoalFn<Id>(PhantomData<Id>); impl<Id> S3BucketStateGoalFn<Id> where Id: Send + Sync, { pub async fn try_state_goal( _fn_ctx: FnCtx<'_>, params_partial: &<S3BucketParams<Id> as Params>::Partial, _data: S3BucketData<'_, Id>, ) -> Result<Option<S3BucketState>, S3BucketError> { if let Some(name) = params_partial.name() { Self::state_goal_internal(name.to_string()).await.map(Some) } else { Ok(None) } } pub async fn state_goal( _fn_ctx: FnCtx<'_>, params: &S3BucketParams<Id>, _data: S3BucketData<'_, Id>, ) -> Result<S3BucketState, S3BucketError> { let name = params.name().to_string(); Self::state_goal_internal(name).await } async fn state_goal_internal(name: String) -> Result<S3BucketState, S3BucketError> { Ok(S3BucketState::Some { name, creation_date: Timestamped::Tbd, }) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_s3_bucket/s3_bucket_state_current_fn.rs
examples/envman/src/items/peace_aws_s3_bucket/s3_bucket_state_current_fn.rs
use std::marker::PhantomData; use chrono::DateTime; use peace::{ cfg::{state::Timestamped, FnCtx}, params::Params, }; use crate::items::peace_aws_s3_bucket::{ S3BucketData, S3BucketError, S3BucketParams, S3BucketState, }; #[cfg(feature = "output_progress")] use peace::progress_model::ProgressMsgUpdate; /// Reads the current state of the S3 bucket state. #[derive(Debug)] pub struct S3BucketStateCurrentFn<Id>(PhantomData<Id>); impl<Id> S3BucketStateCurrentFn<Id> where Id: Send + Sync, { pub async fn try_state_current( fn_ctx: FnCtx<'_>, params_partial: &<S3BucketParams<Id> as Params>::Partial, data: S3BucketData<'_, Id>, ) -> Result<Option<S3BucketState>, S3BucketError> { if let Some(name) = params_partial.name() { Self::state_current_internal(fn_ctx, data, name) .await .map(Some) } else { Ok(None) } } pub async fn state_current( fn_ctx: FnCtx<'_>, params: &S3BucketParams<Id>, data: S3BucketData<'_, Id>, ) -> Result<S3BucketState, S3BucketError> { let name = params.name(); Self::state_current_internal(fn_ctx, data, name).await } async fn state_current_internal( fn_ctx: FnCtx<'_>, data: S3BucketData<'_, Id>, name: &str, ) -> Result<S3BucketState, S3BucketError> { let client = data.client(); #[cfg(not(feature = "output_progress"))] let _fn_ctx = fn_ctx; #[cfg(feature = "output_progress")] let progress_sender = &fn_ctx.progress_sender; #[cfg(feature = "output_progress")] progress_sender.tick(ProgressMsgUpdate::Set(String::from("listing buckets"))); let list_buckets_output = client.list_buckets().send().await.map_err(|error| { #[cfg(feature = "error_reporting")] let (aws_desc, aws_desc_span) = crate::items::aws_error_desc!(&error); let error = Box::new(error); S3BucketError::S3BucketListError { s3_bucket_name: name.to_string(), #[cfg(feature = "error_reporting")] aws_desc, #[cfg(feature = "error_reporting")] aws_desc_span, error, } })?; #[cfg(feature = "output_progress")] progress_sender.tick(ProgressMsgUpdate::Set(String::from("finding bucket"))); let creation_date = list_buckets_output.buckets().iter().find_map(|bucket| { if matches!(bucket.name(), Some(bucket_name_listed) if bucket_name_listed == name) { Some( bucket .creation_date() .cloned() .expect("Expected bucket creation date to be Some."), ) } else { None } }); #[cfg(feature = "output_progress")] { let message = if creation_date.is_some() { "bucket found" } else { "bucket not found" }; progress_sender.tick(ProgressMsgUpdate::Set(String::from(message))); } // let head_bucket_result = client.head_bucket().bucket(name).send().await; // let s3_bucket_exists = match head_bucket_result { // Ok(_head_bucket_output) => true, // Err(error) => match &error { // SdkError::ServiceError(service_error) => { // dbg!(&service_error); // // If your user does not have permissions, AWS SDK Rust does not // return an // access denied error. It just returns "Error" // with no other information. // // // https://github.com/awslabs/aws-sdk-rust/issues/227 // match service_error.err().kind { // HeadBucketErrorKind::NotFound(_) => false, // _ => { // return Err(S3BucketError::S3BucketGetError { // s3_bucket_name: name.to_string(), // error, // }); // } // } // } // _ => { // return Err(S3BucketError::S3BucketGetError { // s3_bucket_name: name.to_string(), // error, // }); // } // }, // }; if let Some(creation_date) = creation_date { let state_current = S3BucketState::Some { name: name.to_string(), creation_date: Timestamped::Value( DateTime::from_timestamp(creation_date.secs(), creation_date.subsec_nanos()) .unwrap(), ), }; Ok(state_current) } else { Ok(S3BucketState::None) } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_s3_bucket/s3_bucket_state_diff_fn.rs
examples/envman/src/items/peace_aws_s3_bucket/s3_bucket_state_diff_fn.rs
use crate::items::peace_aws_s3_bucket::{S3BucketError, S3BucketState, S3BucketStateDiff}; /// Tar extraction status diff function. #[derive(Debug)] pub struct S3BucketStateDiffFn; impl S3BucketStateDiffFn { pub async fn state_diff( state_current: &S3BucketState, state_goal: &S3BucketState, ) -> Result<S3BucketStateDiff, S3BucketError> { let diff = match (state_current, state_goal) { (S3BucketState::None, S3BucketState::None) => S3BucketStateDiff::InSyncDoesNotExist, (S3BucketState::None, S3BucketState::Some { .. }) => S3BucketStateDiff::Added, (S3BucketState::Some { .. }, S3BucketState::None) => S3BucketStateDiff::Removed, ( S3BucketState::Some { name: s3_bucket_name_current, creation_date: _, }, S3BucketState::Some { name: s3_bucket_name_goal, creation_date: _, }, ) => { if s3_bucket_name_current != s3_bucket_name_goal { S3BucketStateDiff::NameModified { s3_bucket_name_current: s3_bucket_name_current.to_string(), s3_bucket_name_goal: s3_bucket_name_goal.to_string(), } } else { // We don't care about the creation date, as existence is sufficient. S3BucketStateDiff::InSyncExists } } }; Ok(diff) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_s3_bucket/s3_bucket_params.rs
examples/envman/src/items/peace_aws_s3_bucket/s3_bucket_params.rs
use std::marker::PhantomData; use derivative::Derivative; use peace::params::Params; use serde::{Deserialize, Serialize}; /// S3Bucket item parameters. /// /// The `Id` type parameter is needed for each S3 bucket params to be a /// distinct type. /// /// # Type Parameters /// /// * `Id`: A zero-sized type used to distinguish different S3 bucket parameters /// from each other. #[derive(Derivative, Params, PartialEq, Eq, Deserialize, Serialize)] #[derivative(Clone, Debug)] #[serde(bound = "")] pub struct S3BucketParams<Id> { /// Name for both the S3 bucket and role. /// /// Alphanumeric characters and `_+=,.@-` are allowed. /// /// TODO: newtype + proc macro. name: String, /// Marker for unique S3 bucket parameters type. marker: PhantomData<Id>, } impl<Id> S3BucketParams<Id> { pub fn new(name: String) -> Self { Self { name, marker: PhantomData, } } /// Returns the name for both the S3 bucket and role. /// /// Alphanumeric characters and `_+=,.@-` are allowed. pub fn name(&self) -> &str { self.name.as_ref() } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_s3_bucket/s3_bucket_apply_fns.rs
examples/envman/src/items/peace_aws_s3_bucket/s3_bucket_apply_fns.rs
use std::marker::PhantomData; use aws_sdk_iam::error::{ProvideErrorMetadata, SdkError}; use aws_sdk_s3::{ operation::create_bucket::CreateBucketError, types::{BucketLocationConstraint, CreateBucketConfiguration}, }; use peace::cfg::{ApplyCheck, FnCtx}; #[cfg(feature = "output_progress")] use peace::progress_model::{ProgressLimit, ProgressMsgUpdate}; use crate::items::peace_aws_s3_bucket::{ S3BucketData, S3BucketError, S3BucketParams, S3BucketState, S3BucketStateDiff, }; use super::S3BucketStateCurrentFn; /// ApplyFns for the S3 bucket state. #[derive(Debug)] pub struct S3BucketApplyFns<Id>(PhantomData<Id>); impl<Id> S3BucketApplyFns<Id> where Id: Send + Sync + 'static, { pub async fn apply_check( _params: &S3BucketParams<Id>, _data: S3BucketData<'_, Id>, state_current: &S3BucketState, _state_goal: &S3BucketState, diff: &S3BucketStateDiff, ) -> Result<ApplyCheck, S3BucketError> { match diff { S3BucketStateDiff::Added => { let apply_check = { #[cfg(not(feature = "output_progress"))] { ApplyCheck::ExecRequired } #[cfg(feature = "output_progress")] { let progress_limit = ProgressLimit::Steps(1); ApplyCheck::ExecRequired { progress_limit } } }; Ok(apply_check) } S3BucketStateDiff::Removed => { let apply_check = match state_current { S3BucketState::None => ApplyCheck::ExecNotRequired, S3BucketState::Some { name: _, creation_date: _, } => { #[cfg(not(feature = "output_progress"))] { ApplyCheck::ExecRequired } #[cfg(feature = "output_progress")] { let steps_required = 1; let progress_limit = ProgressLimit::Steps(steps_required); ApplyCheck::ExecRequired { progress_limit } } } }; Ok(apply_check) } S3BucketStateDiff::NameModified { s3_bucket_name_current, s3_bucket_name_goal, } => Err(S3BucketError::S3BucketModificationNotSupported { s3_bucket_name_current: s3_bucket_name_current.clone(), s3_bucket_name_goal: s3_bucket_name_goal.clone(), }), S3BucketStateDiff::InSyncExists | S3BucketStateDiff::InSyncDoesNotExist => { Ok(ApplyCheck::ExecNotRequired) } } } pub async fn apply_dry( _fn_ctx: FnCtx<'_>, _params: &S3BucketParams<Id>, _data: S3BucketData<'_, Id>, _state_current: &S3BucketState, state_goal: &S3BucketState, _diff: &S3BucketStateDiff, ) -> Result<S3BucketState, S3BucketError> { Ok(state_goal.clone()) } pub async fn apply( fn_ctx: FnCtx<'_>, params: &S3BucketParams<Id>, data: S3BucketData<'_, Id>, state_current: &S3BucketState, state_goal: &S3BucketState, diff: &S3BucketStateDiff, ) -> Result<S3BucketState, S3BucketError> { #[cfg(feature = "output_progress")] let progress_sender = &fn_ctx.progress_sender; match diff { S3BucketStateDiff::Added => match state_goal { S3BucketState::None => { panic!("`S3BucketApplyFns::exec` called with state_goal being None."); } S3BucketState::Some { name, creation_date: _, } => { let client = data.client(); #[cfg(feature = "output_progress")] progress_sender.tick(ProgressMsgUpdate::Set(String::from("creating bucket"))); let mut create_bucket = client.create_bucket().bucket(name); if let Some(region) = data.region().as_ref() { create_bucket = create_bucket.create_bucket_configuration( CreateBucketConfiguration::builder() .location_constraint(BucketLocationConstraint::from( region.as_ref(), )) .build(), ); } let _create_bucket_output = create_bucket.send().await.map_err(|error| { let s3_bucket_name = name.to_string(); #[cfg(feature = "error_reporting")] let (aws_desc, aws_desc_span) = crate::items::aws_error_desc!(&error); match &error { SdkError::ServiceError(service_error) => match &service_error.err() { CreateBucketError::BucketAlreadyExists(error) => { S3BucketError::S3BucketOwnedBySomeoneElseError { s3_bucket_name, error: Box::new(error.clone()), } } CreateBucketError::BucketAlreadyOwnedByYou(error) => { S3BucketError::S3BucketOwnedByYouError { s3_bucket_name, error: Box::new(error.clone()), } } _ => S3BucketError::S3BucketCreateError { s3_bucket_name, #[cfg(feature = "error_reporting")] aws_desc, #[cfg(feature = "error_reporting")] aws_desc_span, error: Box::new(error), }, }, _ => S3BucketError::S3BucketCreateError { s3_bucket_name, #[cfg(feature = "error_reporting")] aws_desc, #[cfg(feature = "error_reporting")] aws_desc_span, error: Box::new(error), }, } })?; #[cfg(feature = "output_progress")] progress_sender.inc(1, ProgressMsgUpdate::Set(String::from("bucket created"))); let state_applied = S3BucketStateCurrentFn::<Id>::state_current(fn_ctx, params, data).await?; Ok(state_applied) } }, S3BucketStateDiff::Removed => { match state_current { S3BucketState::None => {} S3BucketState::Some { name, creation_date: _, } => { let client = data.client(); #[cfg(feature = "output_progress")] progress_sender .tick(ProgressMsgUpdate::Set(String::from("deleting bucket"))); let delete_bucket_result = client.delete_bucket().bucket(name).send().await; // Sometimes AWS returns this error: // // ```xml // <Code>NoSuchBucket</Code> // <Message>The specified bucket does not exist</Message> // <BucketName>the-bucket-name</BucketName> // ``` // // This is really an issue with AWS, where they still show the // bucket even though it *has* been deleted. See: // // <https://serverfault.com/questions/969962/how-to-remove-orphaned-s3-bucket> delete_bucket_result .map(|_delete_bucket_output| ()) .or_else(|error| { if let SdkError::ServiceError(service_error) = &error { if let Some("NoSuchBucket") = service_error.err().code() { return Ok(()); } } #[cfg(feature = "error_reporting")] let (aws_desc, aws_desc_span) = crate::items::aws_error_desc!(&error); let s3_bucket_name = name.to_string(); Err(S3BucketError::S3BucketDeleteError { s3_bucket_name, #[cfg(feature = "error_reporting")] aws_desc, #[cfg(feature = "error_reporting")] aws_desc_span, error: Box::new(error), }) })?; #[cfg(feature = "output_progress")] progress_sender .inc(1, ProgressMsgUpdate::Set(String::from("bucket deleted"))); } } let state_applied = state_goal.clone(); Ok(state_applied) } S3BucketStateDiff::InSyncExists | S3BucketStateDiff::InSyncDoesNotExist => { unreachable!( "`S3BucketApplyFns::exec` should never be called when state is in sync." ); } S3BucketStateDiff::NameModified { s3_bucket_name_current, s3_bucket_name_goal, } => Err(S3BucketError::NameModificationNotSupported { s3_bucket_name_current: s3_bucket_name_current.clone(), s3_bucket_name_goal: s3_bucket_name_goal.clone(), }), } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_s3_bucket/s3_bucket_state.rs
examples/envman/src/items/peace_aws_s3_bucket/s3_bucket_state.rs
use std::fmt; use chrono::{DateTime, Utc}; use peace::cfg::state::Timestamped; use serde::{Deserialize, Serialize}; #[cfg(feature = "output_progress")] use peace::item_interaction_model::ItemLocationState; /// S3 bucket state. #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] pub enum S3BucketState { /// S3 bucket does not exist. None, /// S3 bucket exists. Some { /// S3 bucket name. /// /// Alphanumeric characters and `_+=,.@-` are allowed. /// /// TODO: newtype + proc macro. name: String, /// Timestamp that the S3Bucket was created. creation_date: Timestamped<DateTime<Utc>>, }, } impl S3BucketState { /// Returns the bucket name if the bucket exists. pub fn bucket_name(&self) -> Option<String> { match self { S3BucketState::None => None, S3BucketState::Some { name, creation_date: _, } => Some(name.clone()), } } } impl fmt::Display for S3BucketState { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Self::None => "does not exist".fmt(f), // https://s3.console.aws.amazon.com/s3/buckets/azriel-peace-envman-demo Self::Some { name, creation_date, } => match creation_date { Timestamped::Tbd => write!(f, "`{name}` should exist"), Timestamped::Value(_) => write!( f, "exists at https://s3.console.aws.amazon.com/s3/buckets/{name}" ), }, } } } #[cfg(feature = "output_progress")] impl<'state> From<&'state S3BucketState> for ItemLocationState { fn from(s3_bucket_state: &'state S3BucketState) -> ItemLocationState { match s3_bucket_state { S3BucketState::Some { .. } => ItemLocationState::Exists, S3BucketState::None => ItemLocationState::NotExists, } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_s3_bucket/s3_bucket_data.rs
examples/envman/src/items/peace_aws_s3_bucket/s3_bucket_data.rs
use std::marker::PhantomData; use peace::data::{ accessors::{ROpt, R}, Data, }; /// Data used to manage S3 bucket state. /// /// # Type Parameters /// /// * `Id`: A zero-sized type used to distinguish different S3 bucket parameters /// from each other. #[derive(Data, Debug)] pub struct S3BucketData<'exec, Id> where Id: Send + Sync + 'static, { /// IAM client to communicate with AWS. client: R<'exec, aws_sdk_s3::Client>, /// Region to use to constrain S3 bucket. region: ROpt<'exec, aws_sdk_s3::config::Region>, /// Marker. marker: PhantomData<Id>, } impl<'exec, Id> S3BucketData<'exec, Id> where Id: Send + Sync + 'static, { pub fn client(&self) -> &R<'exec, aws_sdk_s3::Client> { &self.client } pub fn region(&self) -> &ROpt<'exec, aws_sdk_s3::config::Region> { &self.region } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_s3_object/s3_object_apply_fns.rs
examples/envman/src/items/peace_aws_s3_object/s3_object_apply_fns.rs
use std::marker::PhantomData; use aws_smithy_types::byte_stream::ByteStream; use base64::Engine; use peace::cfg::{state::Generated, ApplyCheck, FnCtx}; #[cfg(feature = "output_progress")] use peace::progress_model::{ProgressLimit, ProgressMsgUpdate}; use crate::items::peace_aws_s3_object::{ S3ObjectData, S3ObjectError, S3ObjectParams, S3ObjectState, S3ObjectStateDiff, }; /// ApplyFns for the S3 object state. #[derive(Debug)] pub struct S3ObjectApplyFns<Id>(PhantomData<Id>); impl<Id> S3ObjectApplyFns<Id> where Id: Send + Sync + 'static, { pub async fn apply_check( _params: &S3ObjectParams<Id>, _data: S3ObjectData<'_, Id>, state_current: &S3ObjectState, _state_goal: &S3ObjectState, diff: &S3ObjectStateDiff, ) -> Result<ApplyCheck, S3ObjectError> { match diff { S3ObjectStateDiff::Added | S3ObjectStateDiff::ObjectContentModified { .. } => { let apply_check = { #[cfg(not(feature = "output_progress"))] { ApplyCheck::ExecRequired } #[cfg(feature = "output_progress")] { let progress_limit = ProgressLimit::Steps(1); ApplyCheck::ExecRequired { progress_limit } } }; Ok(apply_check) } S3ObjectStateDiff::Removed => { let apply_check = match state_current { S3ObjectState::None => ApplyCheck::ExecNotRequired, S3ObjectState::Some { bucket_name: _, object_key: _, content_md5_hexstr: _, e_tag: _, } => { #[cfg(not(feature = "output_progress"))] { ApplyCheck::ExecRequired } #[cfg(feature = "output_progress")] { let steps_required = 1; let progress_limit = ProgressLimit::Steps(steps_required); ApplyCheck::ExecRequired { progress_limit } } } }; Ok(apply_check) } S3ObjectStateDiff::BucketNameModified { bucket_name_current, bucket_name_goal, } => Err(S3ObjectError::BucketModificationNotSupported { bucket_name_current: bucket_name_current.clone(), bucket_name_goal: bucket_name_goal.clone(), }), S3ObjectStateDiff::ObjectKeyModified { object_key_current, object_key_goal, } => Err(S3ObjectError::S3ObjectModificationNotSupported { object_key_current: object_key_current.clone(), object_key_goal: object_key_goal.clone(), }), S3ObjectStateDiff::InSyncExists | S3ObjectStateDiff::InSyncDoesNotExist => { Ok(ApplyCheck::ExecNotRequired) } } } pub async fn apply_dry( _fn_ctx: FnCtx<'_>, _params: &S3ObjectParams<Id>, _data: S3ObjectData<'_, Id>, _state_current: &S3ObjectState, state_goal: &S3ObjectState, _diff: &S3ObjectStateDiff, ) -> Result<S3ObjectState, S3ObjectError> { Ok(state_goal.clone()) } pub async fn apply( #[cfg(not(feature = "output_progress"))] _fn_ctx: FnCtx<'_>, #[cfg(feature = "output_progress")] fn_ctx: FnCtx<'_>, params: &S3ObjectParams<Id>, data: S3ObjectData<'_, Id>, state_current: &S3ObjectState, state_goal: &S3ObjectState, diff: &S3ObjectStateDiff, ) -> Result<S3ObjectState, S3ObjectError> { #[cfg(feature = "output_progress")] let progress_sender = &fn_ctx.progress_sender; match diff { S3ObjectStateDiff::Added | S3ObjectStateDiff::ObjectContentModified { .. } => { match state_goal { S3ObjectState::None => { panic!("`S3ObjectApplyFns::exec` called with state_goal being None."); } S3ObjectState::Some { bucket_name, object_key, content_md5_hexstr, e_tag: _, } => { let client = data.client(); #[cfg(feature = "output_progress")] progress_sender .tick(ProgressMsgUpdate::Set(String::from("uploading object"))); let file_path = params.file_path(); let Some(content_md5_hexstr) = content_md5_hexstr else { panic!( "Content MD5 must be Some as this is calculated from an existent local file." ); }; let content_md5_b64 = { let bytes = (0..content_md5_hexstr.len()) .step_by(2) .map(|index_start| { &content_md5_hexstr[index_start..index_start + 2] }) .map(|byte_hexstr| u8::from_str_radix(byte_hexstr, 16)) .try_fold( Vec::<u8>::with_capacity(content_md5_hexstr.len() / 2), |mut bytes, byte_result| { byte_result.map(|byte| { bytes.push(byte); bytes }) }, ) .map_err(|error| { let file_path = file_path.to_path_buf(); let bucket_name = bucket_name.clone(); let object_key = object_key.clone(); let content_md5_hexstr = content_md5_hexstr.clone(); S3ObjectError::ObjectContentMd5HexstrParse { file_path, bucket_name, object_key, content_md5_hexstr, error, } })?; base64::engine::general_purpose::STANDARD.encode(bytes) }; let put_object_output = client .put_object() .bucket(bucket_name) .key(object_key) .content_md5(content_md5_b64) .metadata("content_md5_hexstr", content_md5_hexstr) .body(ByteStream::from_path(file_path).await.map_err(|error| { let file_path = file_path.to_path_buf(); let bucket_name = bucket_name.clone(); let object_key = object_key.clone(); S3ObjectError::ObjectFileStream { file_path, bucket_name, object_key, error, } })?) .send() .await .map_err(|error| { let bucket_name = bucket_name.to_string(); let object_key = object_key.to_string(); #[cfg(feature = "error_reporting")] let (aws_desc, aws_desc_span) = crate::items::aws_error_desc!(&error); let error = Box::new(error); S3ObjectError::S3ObjectUploadError { bucket_name, object_key, #[cfg(feature = "error_reporting")] aws_desc, #[cfg(feature = "error_reporting")] aws_desc_span, error, } })?; #[cfg(feature = "output_progress")] progress_sender .inc(1, ProgressMsgUpdate::Set(String::from("object uploaded"))); let e_tag = put_object_output .e_tag() .expect("Expected ETag to be some when put_object is successful.") .to_string(); let state_applied = S3ObjectState::Some { bucket_name: bucket_name.clone(), object_key: object_key.clone(), content_md5_hexstr: Some(content_md5_hexstr.clone()), e_tag: Generated::Value(e_tag), }; Ok(state_applied) } } } S3ObjectStateDiff::Removed => { match state_current { S3ObjectState::None => {} S3ObjectState::Some { bucket_name, object_key, content_md5_hexstr: _, e_tag: _, } => { let client = data.client(); #[cfg(feature = "output_progress")] progress_sender .tick(ProgressMsgUpdate::Set(String::from("deleting object"))); client .delete_object() .bucket(bucket_name) .key(object_key) .send() .await .map_err(|error| { let bucket_name = bucket_name.to_string(); let object_key = object_key.to_string(); #[cfg(feature = "error_reporting")] let (aws_desc, aws_desc_span) = crate::items::aws_error_desc!(&error); let error = Box::new(error); S3ObjectError::S3ObjectDeleteError { bucket_name, object_key, #[cfg(feature = "error_reporting")] aws_desc, #[cfg(feature = "error_reporting")] aws_desc_span, error, } })?; #[cfg(feature = "output_progress")] progress_sender .inc(1, ProgressMsgUpdate::Set(String::from("object deleted"))); } } let state_applied = state_goal.clone(); Ok(state_applied) } S3ObjectStateDiff::InSyncExists | S3ObjectStateDiff::InSyncDoesNotExist => { unreachable!( "`S3ObjectApplyFns::exec` should never be called when state is in sync." ); } S3ObjectStateDiff::BucketNameModified { bucket_name_current, bucket_name_goal, } => Err(S3ObjectError::BucketModificationNotSupported { bucket_name_current: bucket_name_current.clone(), bucket_name_goal: bucket_name_goal.clone(), }), S3ObjectStateDiff::ObjectKeyModified { object_key_current, object_key_goal, } => { let S3ObjectState::Some { bucket_name, .. } = state_goal else { panic!("`S3ObjectApplyFns::exec` called with state_goal being None."); }; Err(S3ObjectError::ObjectKeyModificationNotSupported { bucket_name: bucket_name.clone(), object_key_current: object_key_current.clone(), object_key_goal: object_key_goal.clone(), }) } } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_s3_object/s3_object_state.rs
examples/envman/src/items/peace_aws_s3_object/s3_object_state.rs
use std::fmt; use peace::cfg::state::Generated; use serde::{Deserialize, Serialize}; #[cfg(feature = "output_progress")] use peace::item_interaction_model::ItemLocationState; /// S3 object state. #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] pub enum S3ObjectState { /// S3 object does not exist. None, /// S3 object exists. Some { /// S3 bucket to insert the object into, bucket_name: String, /// S3 object key. object_key: String, /// MD5 hex string of the content. content_md5_hexstr: Option<String>, /// ETag served by S3. e_tag: Generated<String>, }, } impl fmt::Display for S3ObjectState { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Self::None => "does not exist".fmt(f), Self::Some { bucket_name, object_key, content_md5_hexstr, e_tag, } => { match e_tag { Generated::Tbd => { write!(f, "`{object_key}` should be uploaded to `{bucket_name}`")? } Generated::Value(_) => { // https://s3.console.aws.amazon.com/s3/object/azriel-peace-envman-demo?prefix=web_app.tar write!( f, "uploaded at https://s3.console.aws.amazon.com/s3/object/{bucket_name}?prefix={object_key}" )?; } } if let Some(content_md5_hexstr) = content_md5_hexstr { write!(f, " (MD5: {content_md5_hexstr})") } else { write!(f, " (MD5 unknown)") } } } } } #[cfg(feature = "output_progress")] impl<'state> From<&'state S3ObjectState> for ItemLocationState { fn from(s3_object_state: &'state S3ObjectState) -> ItemLocationState { match s3_object_state { S3ObjectState::Some { .. } => ItemLocationState::Exists, S3ObjectState::None => ItemLocationState::NotExists, } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_s3_object/s3_object_state_current_fn.rs
examples/envman/src/items/peace_aws_s3_object/s3_object_state_current_fn.rs
use std::marker::PhantomData; use aws_sdk_iam::error::SdkError; use aws_sdk_s3::operation::head_object::HeadObjectError; use peace::{ cfg::{state::Generated, FnCtx}, params::Params, }; use crate::items::peace_aws_s3_object::{ S3ObjectData, S3ObjectError, S3ObjectParams, S3ObjectState, }; #[cfg(feature = "output_progress")] use peace::progress_model::ProgressMsgUpdate; /// Reads the current state of the S3 object state. #[derive(Debug)] pub struct S3ObjectStateCurrentFn<Id>(PhantomData<Id>); impl<Id> S3ObjectStateCurrentFn<Id> where Id: Send + Sync, { pub async fn try_state_current( fn_ctx: FnCtx<'_>, params_partial: &<S3ObjectParams<Id> as Params>::Partial, data: S3ObjectData<'_, Id>, ) -> Result<Option<S3ObjectState>, S3ObjectError> { let bucket_name = params_partial.bucket_name(); let object_key = params_partial.object_key(); if let Some((bucket_name, object_key)) = bucket_name.zip(object_key) { Self::state_current_internal(fn_ctx, data, bucket_name, object_key) .await .map(Some) } else { Ok(Some(S3ObjectState::None)) } } pub async fn state_current( fn_ctx: FnCtx<'_>, params: &S3ObjectParams<Id>, data: S3ObjectData<'_, Id>, ) -> Result<S3ObjectState, S3ObjectError> { let bucket_name = params.bucket_name(); let object_key = params.object_key(); Self::state_current_internal(fn_ctx, data, bucket_name, object_key).await } async fn state_current_internal( fn_ctx: FnCtx<'_>, data: S3ObjectData<'_, Id>, bucket_name: &str, object_key: &str, ) -> Result<S3ObjectState, S3ObjectError> { let client = data.client(); #[cfg(not(feature = "output_progress"))] let _fn_ctx = fn_ctx; #[cfg(feature = "output_progress")] let progress_sender = &fn_ctx.progress_sender; #[cfg(feature = "output_progress")] progress_sender.tick(ProgressMsgUpdate::Set(String::from( "fetching object metadata", ))); let head_object_result = client .head_object() .bucket(bucket_name) .key(object_key) .send() .await; let content_md5_and_e_tag = match head_object_result { Ok(head_object_output) => { #[cfg(feature = "output_progress")] progress_sender.tick(ProgressMsgUpdate::Set(String::from( "object metadata fetched", ))); let content_md5_hexstr = head_object_output .metadata() .and_then(|metadata| metadata.get("content_md5_hexstr")) .cloned(); let e_tag = head_object_output .e_tag() .expect("Expected S3 object e_tag to be Some when head_object is successful.") .to_string(); Some((content_md5_hexstr, e_tag)) } Err(error) => { #[cfg(feature = "output_progress")] progress_sender.tick(ProgressMsgUpdate::Set(String::from( "object metadata not fetched", ))); #[cfg(feature = "error_reporting")] let (aws_desc, aws_desc_span) = crate::items::aws_error_desc!(&error); match &error { SdkError::ServiceError(service_error) => match service_error.err() { HeadObjectError::NotFound(_) => None, _ => { let error = Box::new(error); return Err(S3ObjectError::S3ObjectGetError { object_key: object_key.to_string(), #[cfg(feature = "error_reporting")] aws_desc, #[cfg(feature = "error_reporting")] aws_desc_span, error, }); } }, _ => { let error = Box::new(error); return Err(S3ObjectError::S3ObjectGetError { object_key: object_key.to_string(), #[cfg(feature = "error_reporting")] aws_desc, #[cfg(feature = "error_reporting")] aws_desc_span, error, }); } } } }; if let Some((content_md5_hexstr, e_tag)) = content_md5_and_e_tag { let state_current = S3ObjectState::Some { bucket_name: bucket_name.to_string(), object_key: object_key.to_string(), content_md5_hexstr, e_tag: Generated::Value(e_tag), }; Ok(state_current) } else { Ok(S3ObjectState::None) } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_s3_object/s3_object_state_goal_fn.rs
examples/envman/src/items/peace_aws_s3_object/s3_object_state_goal_fn.rs
use std::{fmt::Write, marker::PhantomData, path::Path}; use peace::{ cfg::{state::Generated, FnCtx}, params::Params, }; use crate::items::peace_aws_s3_object::{ S3ObjectData, S3ObjectError, S3ObjectParams, S3ObjectState, }; #[cfg(feature = "output_progress")] use peace::progress_model::ProgressMsgUpdate; /// Reads the goal state of the S3 object state. #[derive(Debug)] pub struct S3ObjectStateGoalFn<Id>(PhantomData<Id>); impl<Id> S3ObjectStateGoalFn<Id> where Id: Send + Sync, { pub async fn try_state_goal( fn_ctx: FnCtx<'_>, params_partial: &<S3ObjectParams<Id> as Params>::Partial, _data: S3ObjectData<'_, Id>, ) -> Result<Option<S3ObjectState>, S3ObjectError> { let file_path = params_partial.file_path(); let bucket_name = params_partial.bucket_name(); let object_key = params_partial.object_key(); if let Some(((file_path, bucket_name), object_key)) = file_path.zip(bucket_name).zip(object_key) { #[cfg(not(target_arch = "wasm32"))] { if !tokio::fs::try_exists(file_path).await.map_err(|error| { S3ObjectError::ObjectFileExists { file_path: file_path.to_path_buf(), bucket_name: bucket_name.to_string(), object_key: object_key.to_string(), error, } })? { return Ok(None); } } Self::state_goal_internal( fn_ctx, file_path, bucket_name.to_string(), object_key.to_string(), ) .await .map(Some) } else { Ok(None) } } pub async fn state_goal( fn_ctx: FnCtx<'_>, params: &S3ObjectParams<Id>, _data: S3ObjectData<'_, Id>, ) -> Result<S3ObjectState, S3ObjectError> { let file_path = params.file_path(); let bucket_name = params.bucket_name().to_string(); let object_key = params.object_key().to_string(); Self::state_goal_internal(fn_ctx, file_path, bucket_name, object_key).await } async fn state_goal_internal( fn_ctx: FnCtx<'_>, file_path: &Path, bucket_name: String, object_key: String, ) -> Result<S3ObjectState, S3ObjectError> { #[cfg(not(feature = "output_progress"))] let _fn_ctx = fn_ctx; #[cfg(feature = "output_progress")] let progress_sender = &fn_ctx.progress_sender; #[cfg(feature = "output_progress")] progress_sender.tick(ProgressMsgUpdate::Set(String::from("computing MD5 sum"))); #[cfg(not(target_arch = "wasm32"))] let content_md5_bytes = { use tokio::{fs::File, io::AsyncReadExt}; let mut md5_ctx = md5_rs::Context::new(); let mut file = File::open(file_path) .await .map_err(|error| S3ObjectError::ObjectFileOpen { file_path: file_path.to_path_buf(), bucket_name: bucket_name.clone(), object_key: object_key.clone(), error, })?; let mut bytes_buffer = [0u8; 1024]; loop { match file.read(&mut bytes_buffer).await.map_err(|error| { S3ObjectError::ObjectFileRead { file_path: file_path.to_path_buf(), bucket_name: bucket_name.clone(), object_key: object_key.clone(), error, } })? { 0 => break md5_ctx.finish(), n => { md5_ctx.read(&bytes_buffer[..n]); } } } }; #[cfg(feature = "output_progress")] progress_sender.tick(ProgressMsgUpdate::Set(String::from("MD5 sum computed"))); let content_md5_hexstr = content_md5_bytes .iter() .try_fold( String::with_capacity(content_md5_bytes.len() * 2), |mut hexstr, x| { write!(&mut hexstr, "{:02x}", x)?; Result::<_, std::fmt::Error>::Ok(hexstr) }, ) .expect("Failed to construct hexstring from S3 object MD5."); Ok(S3ObjectState::Some { bucket_name, object_key, content_md5_hexstr: Some(content_md5_hexstr), e_tag: Generated::Tbd, }) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_s3_object/s3_object_state_diff_fn.rs
examples/envman/src/items/peace_aws_s3_object/s3_object_state_diff_fn.rs
use crate::items::peace_aws_s3_object::{S3ObjectError, S3ObjectState, S3ObjectStateDiff}; /// Tar extraction status diff function. #[derive(Debug)] pub struct S3ObjectStateDiffFn; impl S3ObjectStateDiffFn { pub async fn state_diff( state_current: &S3ObjectState, state_goal: &S3ObjectState, ) -> Result<S3ObjectStateDiff, S3ObjectError> { let diff = match (state_current, state_goal) { (S3ObjectState::None, S3ObjectState::None) => S3ObjectStateDiff::InSyncDoesNotExist, (S3ObjectState::None, S3ObjectState::Some { .. }) => S3ObjectStateDiff::Added, (S3ObjectState::Some { .. }, S3ObjectState::None) => S3ObjectStateDiff::Removed, ( S3ObjectState::Some { bucket_name: bucket_name_current, object_key: object_key_current, content_md5_hexstr: content_md5_hexstr_current, e_tag: _e_tag_current, }, S3ObjectState::Some { bucket_name: bucket_name_goal, object_key: object_key_goal, content_md5_hexstr: content_md5_hexstr_goal, e_tag: _e_tag_goal, }, ) => { if bucket_name_current != bucket_name_goal { S3ObjectStateDiff::BucketNameModified { bucket_name_current: bucket_name_current.to_string(), bucket_name_goal: bucket_name_goal.to_string(), } } else if object_key_current != object_key_goal { S3ObjectStateDiff::ObjectKeyModified { object_key_current: object_key_current.to_string(), object_key_goal: object_key_goal.to_string(), } } else if content_md5_hexstr_current != content_md5_hexstr_goal { S3ObjectStateDiff::ObjectContentModified { content_md5_hexstr_current: content_md5_hexstr_current.clone(), content_md5_hexstr_goal: content_md5_hexstr_goal.clone(), } } else { S3ObjectStateDiff::InSyncExists } } }; Ok(diff) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_s3_object/s3_object_data.rs
examples/envman/src/items/peace_aws_s3_object/s3_object_data.rs
use std::marker::PhantomData; use peace::data::{ accessors::{ROpt, R}, Data, }; /// Data used to manage S3 object state. /// /// # Type Parameters /// /// * `Id`: A zero-sized type used to distinguish different S3 object parameters /// from each other. #[derive(Data, Debug)] pub struct S3ObjectData<'exec, Id> where Id: Send + Sync + 'static, { /// IAM client to communicate with AWS. client: R<'exec, aws_sdk_s3::Client>, /// Region to use to constrain S3 object. region: ROpt<'exec, aws_sdk_s3::config::Region>, /// Marker. marker: PhantomData<Id>, } impl<'exec, Id> S3ObjectData<'exec, Id> where Id: Send + Sync + 'static, { pub fn client(&self) -> &R<'exec, aws_sdk_s3::Client> { &self.client } pub fn region(&self) -> &ROpt<'exec, aws_sdk_s3::config::Region> { &self.region } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_s3_object/s3_object_error.rs
examples/envman/src/items/peace_aws_s3_object/s3_object_error.rs
use std::{num::ParseIntError, path::PathBuf}; use aws_sdk_s3::{ error::SdkError, operation::{ delete_object::DeleteObjectError, head_object::HeadObjectError, list_objects::ListObjectsError, put_object::PutObjectError, }, }; #[cfg(feature = "error_reporting")] use peace::miette::{self, SourceSpan}; /// Error while managing S3 object state. #[cfg_attr(feature = "error_reporting", derive(peace::miette::Diagnostic))] #[derive(Debug, thiserror::Error)] pub enum S3ObjectError { /// Bucket for S3 object was attempted to be modified. #[error("S3 object bucket modification is not supported.")] BucketModificationNotSupported { /// Current S3 bucket for the object. bucket_name_current: String, /// Goal S3 bucket for the object. bucket_name_goal: String, }, /// Failed to check file to upload existence. #[error("Failed to check file to upload existence: {}.", file_path.display())] ObjectFileExists { /// Path to the file to be uploaded. file_path: PathBuf, /// S3 bucket name. bucket_name: String, /// S3 object key. object_key: String, /// Underlying error. #[source] error: std::io::Error, }, /// Failed to open file to upload. #[error("Failed to open file to upload.")] ObjectFileOpen { /// Path to the file to be uploaded. file_path: PathBuf, /// S3 bucket name. bucket_name: String, /// S3 object key. object_key: String, /// Underlying error. #[source] error: std::io::Error, }, /// Error occurred reading file to upload. #[error("Error occurred reading file to upload.")] ObjectFileRead { /// Path to the file to be uploaded. file_path: PathBuf, /// S3 bucket name. bucket_name: String, /// S3 object key. object_key: String, /// Underlying error. #[source] error: std::io::Error, }, /// Error occurred opening file to stream. #[error("Error occurred opening file to stream.")] ObjectFileStream { /// Path to the file to be uploaded. file_path: PathBuf, /// S3 bucket name. bucket_name: String, /// S3 object key. object_key: String, /// Underlying error. #[source] error: aws_smithy_types::byte_stream::error::Error, }, /// Content MD5 hex string failed to be parsed as bytes. #[error("Content MD5 hex string failed to be parsed as bytes.")] ObjectContentMd5HexstrParse { /// Path to the file to be uploaded. file_path: PathBuf, /// S3 bucket name. bucket_name: String, /// S3 object key. object_key: String, /// Content MD5 string that was attempted to be parsed. content_md5_hexstr: String, /// Underlying error. #[source] error: ParseIntError, }, /// Failed to base64 decode object ETag. #[error( "Failed to base64 decode object ETag. Bucket: {bucket_name}, object: {object_key}, etag: {content_md5_b64}." )] ObjectETagB64Decode { /// S3 bucket name. bucket_name: String, /// S3 object key. object_key: String, /// ETag that should represent base64 encoded MD5 hash. /// /// This was the value that was attempted to be parsed. content_md5_b64: String, error: base64::DecodeError, }, /// S3 object key was attempted to be modified. #[error("S3 object key modification is not supported.")] ObjectKeyModificationNotSupported { /// S3 bucket name. bucket_name: String, /// Current key of the s3 object. object_key_current: String, /// Goal key of the s3 object. object_key_goal: String, }, /// Failed to list S3 objects. #[error("Failed to list S3 objects to discover: `{object_key}`.")] #[cfg_attr( feature = "error_reporting", diagnostic(help("Make sure you are connected to the internet and try again.")) )] S3ObjectListError { /// S3 bucket name. bucket_name: String, /// S3 object key. object_key: String, /// Error description from AWS error. #[cfg(feature = "error_reporting")] #[source_code] aws_desc: String, /// Span of the description to highlight. #[cfg(feature = "error_reporting")] #[label] aws_desc_span: SourceSpan, /// Underlying error. #[source] error: Box<SdkError<ListObjectsError>>, }, /// Failed to upload S3 object. #[error("Failed to upload S3 object: `{object_key}`.")] #[cfg_attr( feature = "error_reporting", diagnostic(help("Make sure you are connected to the internet and try again.")) )] S3ObjectUploadError { /// S3 bucket name. bucket_name: String, /// S3 object key. object_key: String, /// Error description from AWS error. #[cfg(feature = "error_reporting")] #[source_code] aws_desc: String, /// Span of the description to highlight. #[cfg(feature = "error_reporting")] #[label] aws_desc_span: SourceSpan, /// Underlying error. #[source] error: Box<SdkError<PutObjectError>>, }, /// Failed to discover S3 object. #[error("Failed to discover S3 object: `{object_key}`.")] #[cfg_attr( feature = "error_reporting", diagnostic(help("Make sure you are connected to the internet and try again.")) )] S3ObjectGetError { /// Expected S3 object friendly name. object_key: String, /// Error description from AWS error. #[cfg(feature = "error_reporting")] #[source_code] aws_desc: String, /// Span of the description to highlight. #[cfg(feature = "error_reporting")] #[label] aws_desc_span: SourceSpan, /// Underlying error. #[source] error: Box<SdkError<HeadObjectError>>, }, /// Failed to delete S3 object. #[error("Failed to delete S3 object: `{object_key}`.")] #[cfg_attr( feature = "error_reporting", diagnostic(help("Make sure you are connected to the internet and try again.")) )] S3ObjectDeleteError { /// S3 bucket name. bucket_name: String, /// S3 object key. object_key: String, /// Error description from AWS error. #[cfg(feature = "error_reporting")] #[source_code] aws_desc: String, /// Span of the description to highlight. #[cfg(feature = "error_reporting")] #[label] aws_desc_span: SourceSpan, /// Underlying error. #[source] error: Box<SdkError<DeleteObjectError>>, }, /// User changed the S3 object name, but AWS does not support /// changing this. #[error( "S3Object name cannot be modified, as it is not supported by AWS: current: `{object_key_current}`, goal: `{object_key_goal}`." )] S3ObjectModificationNotSupported { /// Current name of the s3 object. object_key_current: String, /// Goal name of the s3 object. object_key_goal: String, }, }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/examples/envman/src/items/peace_aws_s3_object/s3_object_item.rs
examples/envman/src/items/peace_aws_s3_object/s3_object_item.rs
use std::marker::PhantomData; use aws_config::BehaviorVersion; use peace::{ cfg::{async_trait, ApplyCheck, FnCtx, Item}, item_model::ItemId, params::Params, resource_rt::{resources::ts::Empty, Resources}, }; use crate::items::peace_aws_s3_object::{ S3ObjectApplyFns, S3ObjectData, S3ObjectError, S3ObjectParams, S3ObjectState, S3ObjectStateCurrentFn, S3ObjectStateDiff, S3ObjectStateDiffFn, S3ObjectStateGoalFn, }; /// Item to create an IAM S3 object and IAM role. /// /// In sequence, this will: /// /// * Create the IAM Role. /// * Create the S3 object. /// * Add the IAM role to the S3 object. /// /// The `Id` type parameter is needed for each S3 object params to be a /// distinct type. /// /// # Type Parameters /// /// * `Id`: A zero-sized type used to distinguish different S3 object parameters /// from each other. #[derive(Debug)] pub struct S3ObjectItem<Id> { /// ID of the S3 object item. item_id: ItemId, /// Marker for unique S3 object parameters type. marker: PhantomData<Id>, } impl<Id> S3ObjectItem<Id> { /// Returns a new `S3ObjectItem`. pub fn new(item_id: ItemId) -> Self { Self { item_id, marker: PhantomData, } } } impl<Id> Clone for S3ObjectItem<Id> { fn clone(&self) -> Self { Self { item_id: self.item_id.clone(), marker: PhantomData, } } } #[async_trait(?Send)] impl<Id> Item for S3ObjectItem<Id> where Id: Send + Sync + 'static, { type Data<'exec> = S3ObjectData<'exec, Id>; type Error = S3ObjectError; type Params<'exec> = S3ObjectParams<Id>; type State = S3ObjectState; type StateDiff = S3ObjectStateDiff; fn id(&self) -> &ItemId { &self.item_id } async fn setup(&self, resources: &mut Resources<Empty>) -> Result<(), S3ObjectError> { if !resources.contains::<aws_sdk_s3::Client>() { let sdk_config = aws_config::load_defaults(BehaviorVersion::latest()).await; resources.insert(sdk_config.region().cloned()); let client = aws_sdk_s3::Client::new(&sdk_config); resources.insert(client); } Ok(()) } #[cfg(feature = "item_state_example")] fn state_example(params: &Self::Params<'_>, _data: Self::Data<'_>) -> Self::State { use std::fmt::Write; use peace::cfg::state::Generated; let example_content = b"s3_object_example"; let content_md5_hexstr = { let content_md5_bytes = { let mut md5_ctx = md5_rs::Context::new(); md5_ctx.read(example_content); md5_ctx.finish() }; content_md5_bytes .iter() .try_fold( String::with_capacity(content_md5_bytes.len() * 2), |mut hexstr, x| { write!(&mut hexstr, "{:02x}", x)?; Result::<_, std::fmt::Error>::Ok(hexstr) }, ) .expect("Failed to construct hexstring from S3 object MD5.") }; S3ObjectState::Some { bucket_name: params.bucket_name().to_string(), object_key: params.object_key().to_string(), content_md5_hexstr: Some(content_md5_hexstr.clone()), e_tag: Generated::Value(content_md5_hexstr), } } async fn try_state_current( fn_ctx: FnCtx<'_>, params_partial: &<Self::Params<'_> as Params>::Partial, data: Self::Data<'_>, ) -> Result<Option<Self::State>, S3ObjectError> { S3ObjectStateCurrentFn::try_state_current(fn_ctx, params_partial, data).await } async fn state_current( fn_ctx: FnCtx<'_>, params: &Self::Params<'_>, data: Self::Data<'_>, ) -> Result<Self::State, S3ObjectError> { S3ObjectStateCurrentFn::state_current(fn_ctx, params, data).await } async fn try_state_goal( fn_ctx: FnCtx<'_>, params_partial: &<Self::Params<'_> as Params>::Partial, data: Self::Data<'_>, ) -> Result<Option<Self::State>, S3ObjectError> { S3ObjectStateGoalFn::try_state_goal(fn_ctx, params_partial, data).await } async fn state_goal( fn_ctx: FnCtx<'_>, params: &Self::Params<'_>, data: Self::Data<'_>, ) -> Result<Self::State, S3ObjectError> { S3ObjectStateGoalFn::state_goal(fn_ctx, params, data).await } async fn state_diff( _params_partial: &<Self::Params<'_> as Params>::Partial, _data: Self::Data<'_>, state_current: &Self::State, state_goal: &Self::State, ) -> Result<Self::StateDiff, S3ObjectError> { S3ObjectStateDiffFn::state_diff(state_current, state_goal).await } async fn state_clean( _params_partial: &<Self::Params<'_> as Params>::Partial, _data: Self::Data<'_>, ) -> Result<Self::State, S3ObjectError> { Ok(S3ObjectState::None) } async fn apply_check( params: &Self::Params<'_>, data: Self::Data<'_>, state_current: &Self::State, state_target: &Self::State, diff: &Self::StateDiff, ) -> Result<ApplyCheck, Self::Error> { S3ObjectApplyFns::<Id>::apply_check(params, data, state_current, state_target, diff).await } async fn apply_dry( fn_ctx: FnCtx<'_>, params: &Self::Params<'_>, data: Self::Data<'_>, state_current: &Self::State, state_target: &Self::State, diff: &Self::StateDiff, ) -> Result<Self::State, Self::Error> { S3ObjectApplyFns::<Id>::apply_dry(fn_ctx, params, data, state_current, state_target, diff) .await } async fn apply( fn_ctx: FnCtx<'_>, params: &Self::Params<'_>, data: Self::Data<'_>, state_current: &Self::State, state_target: &Self::State, diff: &Self::StateDiff, ) -> Result<Self::State, Self::Error> { S3ObjectApplyFns::<Id>::apply(fn_ctx, params, data, state_current, state_target, diff).await } #[cfg(feature = "item_interactions")] fn interactions( params: &Self::Params<'_>, _data: Self::Data<'_>, ) -> Vec<peace::item_interaction_model::ItemInteraction> { use peace::item_interaction_model::{ ItemInteractionPush, ItemLocation, ItemLocationAncestors, }; let file_path = format!("📄 {}", params.file_path().display()); let bucket_name = format!("🪣 {}", params.bucket_name()); let object_name = format!("📄 {}", params.object_key()); let item_interaction = ItemInteractionPush::new( ItemLocationAncestors::new(vec![ ItemLocation::localhost(), ItemLocation::path(file_path), ]), ItemLocationAncestors::new(vec![ ItemLocation::path(bucket_name), ItemLocation::path(object_name), ]), ) .into(); vec![item_interaction] } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false